/* ===========================================================================
   CX-Feedback — shared sections and primitives
   ---------------------------------------------------------------------------
   British English. No em dashes. No banned vocabulary.
   Voice rules in Docs/02-brand-voice.md are non-negotiable.
   =========================================================================== */

const { useState, useEffect, useRef, useId } = React;

/* ---------------------------------------------------------------------------
   Utility: scroll-triggered reveal
   --------------------------------------------------------------------------- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    if (!('IntersectionObserver' in window)) {
      els.forEach((e) => e.classList.add('is-visible'));
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add('is-visible');
            io.unobserve(entry.target);
          }
        });
      },
      { rootMargin: '0px 0px -8% 0px', threshold: 0.08 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* ---------------------------------------------------------------------------
   Brand wordmark (inline SVG; swap for a real logo when one exists)
   --------------------------------------------------------------------------- */
const Wordmark = ({ className = '', variant = 'colour' }) => {
  const src = variant === 'white'
    ? 'assets/cx_feedback_logo_no_strap_light_cropped.png'
    : 'assets/cx_feedback_logo_no_strap_rgb_cropped.png';
  return (
    <a
      href="index.html"
      className={`inline-flex items-center ${className}`}
      aria-label="CX-Feedback, home"
    >
      <img
        src={src}
        alt="CX-Feedback Logo"
        className="h-8 lg:h-9 w-auto object-contain block"
      />
    </a>
  );
};

/* ---------------------------------------------------------------------------
   Buttons & Links (Disabled dynamically if not pointing to the homepage)
   --------------------------------------------------------------------------- */
const isNotHomepage = (href) => {
  if (!href) return false;
  const h = href.trim();
  if (h === '#' || h === '' || h.startsWith('#')) return false;
  if (h === 'index.html' || h === '/' || h.includes('index.html')) return false;
  return true;
};

const BtnPrimary = ({ href = 'Book-a-call.html', children, className = '', icon = null, fullWidth = false, ...rest }) => {
  const disabled = isNotHomepage(href);
  if (disabled) {
    return (
      <a
        href={href}
        onClick={(e) => e.preventDefault()}
        className={`btn inline-flex items-center justify-center gap-2 bg-slate-100 border border-slate-200 text-slate-400 font-semibold rounded-lg px-6 py-3 pointer-events-none opacity-60 cursor-not-allowed ${fullWidth ? 'w-full' : ''} ${className}`}
        {...rest}
      >
        {children}
        {icon}
      </a>
    );
  }
  return (
    <a
      href={href}
      className={`btn inline-flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 active:bg-blue-800 text-white font-semibold rounded-lg px-6 py-3 ${fullWidth ? 'w-full' : ''} ${className}`}
      {...rest}
    >
      {children}
      {icon}
    </a>
  );
};

const BtnSecondary = ({ href = '#', children, className = '', icon = null, ...rest }) => {
  const disabled = isNotHomepage(href);
  if (disabled) {
    return (
      <a
        href={href}
        onClick={(e) => e.preventDefault()}
        className={`btn inline-flex items-center justify-center gap-2 bg-slate-100 border border-slate-200 text-slate-400 font-semibold rounded-lg px-6 py-3 pointer-events-none opacity-60 cursor-not-allowed ${className}`}
        {...rest}
      >
        {icon}
        {children}
      </a>
    );
  }
  return (
    <a
      href={href}
      className={`btn inline-flex items-center justify-center gap-2 bg-white hover:bg-blue-50 active:bg-blue-100 text-blue-600 font-semibold rounded-lg px-6 py-3 border-2 border-blue-600 ${className}`}
      {...rest}
    >
      {icon}
      {children}
    </a>
  );
};

const TextLinkCTA = ({ href, children }) => {
  const disabled = isNotHomepage(href);
  if (disabled) {
    return (
      <span className="inline-flex items-center gap-1.5 text-slate-400 font-semibold opacity-60 cursor-not-allowed pointer-events-none">
        <span className="underline-offset-4">{children}</span>
        <IconArrowRight size={18} />
      </span>
    );
  }
  return (
    <a
      href={href}
      className="inline-flex items-center gap-1.5 text-blue-600 hover:text-blue-700 font-semibold group transition-colors"
    >
      <span className="underline-offset-4 group-hover:underline">{children}</span>
      <IconArrowRight size={18} className="transition-transform group-hover:translate-x-1" />
    </a>
  );
};

/* ---------------------------------------------------------------------------
   Calm image placeholder (replace one-for-one with real photography)
   --------------------------------------------------------------------------- */
const ImagePlaceholder = ({ alt, ratio = '4 / 3', tone = 'slate', className = '' }) => {
  const tones = {
    slate: 'from-slate-100 to-slate-200 text-slate-500',
    blue: 'from-blue-50 to-blue-100 text-blue-700',
    warm: 'from-amber-50 to-orange-100 text-amber-800',
    dark: 'from-slate-800 to-slate-900 text-slate-300',
  };
  return (
    <figure
      role="img"
      aria-label={alt}
      className={`relative w-full overflow-hidden rounded-xl border border-slate-200 bg-gradient-to-br ${tones[tone]} ${className}`}
      style={{ aspectRatio: ratio }}
    >
      <div className="absolute inset-0 opacity-50" aria-hidden="true">
        <div className="absolute left-0 right-0 top-1/2 h-px bg-current opacity-20" />
        <div className="absolute top-0 bottom-0 left-1/3 w-px bg-current opacity-20" />
      </div>
      <div className="absolute inset-0 flex items-end p-5 sm:p-6">
        <div className="flex items-start gap-3 max-w-[90%]">
          <span className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-white/80 backdrop-blur-sm shadow-card text-current">
            <IconCamera size={18} />
          </span>
          <span className="text-[13px] font-medium leading-snug text-current">
            <span className="block opacity-70 text-[11px] uppercase tracking-wider font-semibold mb-0.5">Photograph</span>
            {alt}
          </span>
        </div>
      </div>
    </figure>
  );
};

/* ===========================================================================
   Sticky header
   =========================================================================== */
function Header() {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 4);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    if (!mobileOpen) return;
    const onKey = (e) => e.key === 'Escape' && setMobileOpen(false);
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [mobileOpen]);

  const nav = [
    { label: 'Product', href: 'Product-surveys.html' },
    { label: 'Pricing', href: 'Pricing.html' },
    { label: 'Customers', href: 'Customers.html' },
    { label: 'Knowledge', href: 'Knowledge.html' },
    { label: 'Why us', href: 'Why-us.html' },
    { label: 'About', href: 'About.html' },
  ];

  return (
    <header
      className={`fixed top-0 inset-x-0 z-40 bg-white transition-shadow ${scrolled ? 'border-b border-slate-200' : 'border-b border-transparent'}`}
      role="banner"
    >
      <div className="max-w-container mx-auto px-5 sm:px-8 h-16 lg:h-[72px] flex items-center justify-between gap-6">
        <Wordmark />

        <nav className="hidden lg:flex items-center gap-7" aria-label="Primary">
          {nav.map((n) => {
            const disabled = isNotHomepage(n.href);
            return (
              <a
                key={n.href}
                href={n.href}
                onClick={disabled ? (e) => e.preventDefault() : undefined}
                className={disabled
                  ? "text-[15px] text-slate-400 font-medium pointer-events-none opacity-50 cursor-not-allowed"
                  : "text-[15px] text-slate-700 hover:text-blue-600 font-medium transition-colors"
                }
              >
                {n.label}
              </a>
            );
          })}
        </nav>

        <div className="flex items-center gap-3">
          <a
            href="https://cxfb.co.uk/login"
            onClick={(e) => e.preventDefault()}
            className="hidden lg:inline-flex text-[15px] text-slate-400 font-medium px-2 pointer-events-none opacity-50 cursor-not-allowed"
          >
            Log in
          </a>
          <a
            href="Book-a-call.html"
            onClick={(e) => e.preventDefault()}
            className="hidden lg:inline-flex btn items-center justify-center bg-slate-100 border border-slate-200 text-slate-400 font-semibold rounded-lg px-5 py-2.5 pointer-events-none opacity-60 cursor-not-allowed"
          >
            Book a call
          </a>
          <button
            type="button"
            onClick={() => setMobileOpen(true)}
            className="lg:hidden inline-flex items-center justify-center h-11 w-11 rounded-lg text-slate-700 hover:bg-slate-100"
            aria-label="Open menu"
            aria-expanded={mobileOpen}
            aria-controls="mobile-nav"
          >
            <IconMenu size={22} />
          </button>
        </div>
      </div>

      <div
        id="mobile-nav"
        className={`lg:hidden fixed inset-0 z-50 ${mobileOpen ? '' : 'pointer-events-none'}`}
        aria-hidden={!mobileOpen}
      >
        <div
          className={`absolute inset-0 bg-slate-900/40 transition-opacity ${mobileOpen ? 'opacity-100' : 'opacity-0'}`}
          onClick={() => setMobileOpen(false)}
        />
        <div
          className={`absolute right-0 top-0 bottom-0 w-[88%] max-w-[360px] bg-white shadow-cardlg transform transition-transform ${mobileOpen ? 'translate-x-0' : 'translate-x-full'}`}
          role="dialog"
          aria-modal="true"
          aria-label="Site menu"
        >
          <div className="h-16 px-5 flex items-center justify-between border-b border-slate-200">
            <Wordmark />
            <button
              type="button"
              onClick={() => setMobileOpen(false)}
              className="h-11 w-11 inline-flex items-center justify-center rounded-lg text-slate-700 hover:bg-slate-100"
              aria-label="Close menu"
            >
              <IconX size={22} />
            </button>
          </div>
          <nav className="p-5 flex flex-col gap-1" aria-label="Mobile">
            {nav.map((n) => {
              const disabled = isNotHomepage(n.href);
              return (
                <a
                  key={n.href}
                  href={n.href}
                  onClick={disabled ? (e) => e.preventDefault() : () => setMobileOpen(false)}
                  className={disabled
                    ? "px-3 py-3 rounded-lg text-slate-400 text-[17px] font-medium pointer-events-none opacity-50 cursor-not-allowed"
                    : "px-3 py-3 rounded-lg text-slate-800 text-[17px] font-medium hover:bg-blue-50 hover:text-blue-700"
                  }
                >
                  {n.label}
                </a>
              );
            })}
            <a
              href="Book-a-call.html"
              onClick={(e) => e.preventDefault()}
              className="mt-4 inline-flex items-center justify-center btn bg-slate-100 border border-slate-200 text-slate-400 font-semibold rounded-lg px-5 py-3 pointer-events-none opacity-60 cursor-not-allowed"
            >
              Book a call
            </a>
            <a
              href="https://cxfb.co.uk/login"
              onClick={(e) => e.preventDefault()}
              className="mt-2 inline-flex items-center justify-center btn bg-slate-50 text-slate-400 font-semibold rounded-lg px-5 py-3 pointer-events-none opacity-50 cursor-not-allowed"
            >
              Log in
            </a>
          </nav>
        </div>
      </div>
    </header>
  );
}

/* ===========================================================================
   Footer
   =========================================================================== */
const FooterLink = ({ href, children }) => {
  const disabled = isNotHomepage(href);
  if (disabled) {
    return (
      <a
        href={href}
        onClick={(e) => e.preventDefault()}
        className="text-slate-500 font-medium pointer-events-none opacity-60 cursor-not-allowed"
      >
        {children}
      </a>
    );
  }
  return (
    <a
      href={href}
      className="hover:text-white transition-colors"
    >
      {children}
    </a>
  );
};

function Footer() {
  return (
    <footer className="bg-slate-900 text-slate-300" role="contentinfo">
      <div className="max-w-container mx-auto px-5 sm:px-8 pt-20 pb-12">
        <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-8">
          <p className="text-[26px] sm:text-[30px] font-bold text-white max-w-[600px] leading-tight tracking-tight">
            Tenant engagement, done properly.
          </p>
          <a
            href="Book-a-call.html"
            onClick={(e) => e.preventDefault()}
            className="btn self-start inline-flex items-center justify-center gap-2 border border-slate-700 bg-slate-800 text-slate-500 font-semibold rounded-lg px-6 py-3 pointer-events-none opacity-50 cursor-not-allowed"
          >
            Book a thirty-minute call
          </a>
        </div>

        <div className="mt-16 grid sm:grid-cols-2 lg:grid-cols-4 gap-10">
          <div>
            <h3 className="text-[12px] uppercase tracking-wider text-slate-400 font-semibold mb-4">Product</h3>
            <ul className="space-y-2.5 text-[15px]">
              <li><FooterLink href="Product-surveys.html">Surveys</FooterLink></li>
              <li><FooterLink href="Product-messaging.html">Targeted messaging</FooterLink></li>
              <li><FooterLink href="Product-loop.html">Closing the feedback loop</FooterLink></li>
              <li><FooterLink href="Product-tsm.html">Managed TSM service</FooterLink></li>
              <li><FooterLink href="Product-integrations.html">Integrations</FooterLink></li>
              <li><FooterLink href="Product-security.html">Security and compliance</FooterLink></li>
              <li><FooterLink href="Pricing.html">Pricing</FooterLink></li>
            </ul>
          </div>
          <div>
            <h3 className="text-[12px] uppercase tracking-wider text-slate-400 font-semibold mb-4">Knowledge</h3>
            <ul className="space-y-2.5 text-[15px]">
              <li><FooterLink href="Knowledge-tsm.html">TSM guide</FooterLink></li>
              <li><FooterLink href="Knowledge-charter.html">Charter and ARC guide</FooterLink></li>
              <li><FooterLink href="Knowledge-standards.html">Consumer standards</FooterLink></li>
              <li><FooterLink href="Knowledge-loop.html">Closing the feedback loop</FooterLink></li>
              <li><FooterLink href="Knowledge.html">All guides</FooterLink></li>
            </ul>
          </div>
          <div>
            <h3 className="text-[12px] uppercase tracking-wider text-slate-400 font-semibold mb-4">Company</h3>
            <ul className="space-y-2.5 text-[15px]">
              <li><FooterLink href="About.html">About</FooterLink></li>
              <li><FooterLink href="Team.html">Our team</FooterLink></li>
              <li><FooterLink href="Why-us.html">Why CX-Feedback</FooterLink></li>
              <li><FooterLink href="Customers.html">Customers</FooterLink></li>
              <li><FooterLink href="Contact.html">Contact</FooterLink></li>
              <li><FooterLink href="https://www.colleaguepulse.co.uk">Sister platform: Colleague Pulse</FooterLink></li>
            </ul>
          </div>
          <div>
            <h3 className="text-[12px] uppercase tracking-wider text-slate-400 font-semibold mb-4">Legal</h3>
            <ul className="space-y-2.5 text-[15px]">
              <li><FooterLink href="Privacy.html">Privacy policy</FooterLink></li>
              <li><FooterLink href="Cookies.html">Cookie policy</FooterLink></li>
              <li><FooterLink href="Terms.html">Terms of use</FooterLink></li>
              <li><FooterLink href="Accessibility.html">Accessibility</FooterLink></li>
            </ul>
          </div>
        </div>

        <hr className="border-slate-700 mt-14" />

        <div className="mt-8 flex flex-col sm:flex-row gap-6 sm:gap-10 sm:items-start">
          <Wordmark variant="white" className="shrink-0" />
          <div className="space-y-3 text-[13px] text-slate-400 leading-relaxed">
            <div className="flex flex-col sm:flex-row sm:flex-wrap sm:items-center gap-x-6 gap-y-2">
              <a href="tel:+441418102599" className="inline-flex items-center gap-2 text-white text-[15px] font-semibold hover:text-blue-300 transition-colors">
                <IconPhoneCall size={16} className="text-blue-400" />
                0141 810 2599
              </a>
              <a href="mailto:info@cx-feedback.co.uk" className="inline-flex items-center gap-2 text-white text-[15px] font-semibold hover:text-blue-300 transition-colors">
                <IconSend size={16} className="text-blue-400" />
                info@cx-feedback.co.uk
              </a>
              <span className="text-slate-400">Monday to Friday, 9am to 5pm UK time</span>
            </div>
            <p>Target Applications Ltd, Centura Court, Hillington, Glasgow G52 4PR. Trading since 2008.</p>
            <p>UK-built, EU-hosted, fully UK GDPR compliant.</p>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ===========================================================================
   Reusable: Page hero (used on every subpage)
   =========================================================================== */
function PageHero({ eyebrow, h1, sub, primary = { label: 'Book a thirty-minute call', href: 'Book-a-call.html' }, secondary, bg = '#FFFFFF' }) {
  return (
    <section className="relative pt-32 lg:pt-40 pb-16 lg:pb-24" style={{ backgroundColor: bg }}>
      <div className="max-w-container mx-auto px-5 sm:px-8">
        <div className="max-w-[920px]">
          {eyebrow && <p className="eyebrow reveal mb-5">{eyebrow}</p>}
          <h1 className="h1 reveal" style={{ transitionDelay: '60ms' }}>{h1}</h1>
          {sub && (
            <p className="mt-7 body-lg text-slate-600 max-w-[760px] reveal" style={{ transitionDelay: '120ms' }}>
              {sub}
            </p>
          )}
          <div className="mt-9 flex flex-col sm:flex-row gap-3 sm:gap-4 reveal" style={{ transitionDelay: '180ms' }}>
            {primary && <BtnPrimary href={primary.href}>{primary.label}</BtnPrimary>}
            {secondary && <BtnSecondary href={secondary.href} icon={<IconArrowRight size={16} />}>{secondary.label}</BtnSecondary>}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ===========================================================================
   Reusable: Section heading
   =========================================================================== */
function SectionHeading({ eyebrow, h2, intro, centred = false, id }) {
  return (
    <div className={`max-w-prose-wide ${centred ? 'mx-auto text-center' : ''}`}>
      {eyebrow && <p className="eyebrow mb-4">{eyebrow}</p>}
      {h2 && <h2 id={id} className="h2">{h2}</h2>}
      {intro && <p className="mt-5 body-lg text-slate-600">{intro}</p>}
    </div>
  );
}

/* ===========================================================================
   Reusable: Big quote card
   =========================================================================== */
function QuoteCard({ quote, name, role, org, tag, accent = false, link, logo }) {
  const disabled = isNotHomepage(link);
  return (
    <figure className={`rounded-xl border ${accent ? 'border-blue-200 bg-blue-50' : 'border-slate-200 bg-white'} p-7 sm:p-8 reveal`}>
      {tag && (
        <span className="inline-block text-[11px] uppercase tracking-wider font-semibold text-blue-700 bg-blue-100 rounded-full px-2.5 py-1 mb-4">
          {tag}
        </span>
      )}
      <blockquote className="text-[17px] sm:text-[18px] leading-relaxed text-slate-700">
        &ldquo;{quote}&rdquo;
      </blockquote>
      <figcaption className="mt-5 pt-5 border-t border-slate-200 flex items-center gap-4">
        {logo && (
          <div className="shrink-0 h-16 w-20 flex items-center justify-center">
            <img src={logo} alt={`${org} logo`} className="max-h-full max-w-full object-contain" loading="lazy" />
          </div>
        )}
        <div className="min-w-0">
          <div className="font-semibold text-slate-900 text-[15px]">{name}</div>
          <div className="text-[14px] text-slate-600">{role}, {org}</div>
        </div>
        {link && (
          disabled ? (
            <span className="mt-2 inline-block text-[13px] font-semibold text-slate-400 opacity-60 pointer-events-none cursor-not-allowed">Read the full story &rarr;</span>
          ) : (
            <a href={link} className="mt-2 inline-block text-[13px] font-semibold text-blue-600 hover:text-blue-700">Read the full story &rarr;</a>
          )
        )}
      </figcaption>
    </figure>
  );
}

/* ===========================================================================
   Reusable: Stat tile
   =========================================================================== */
function StatTile({ value, label, source, href }) {
  const disabled = isNotHomepage(href);
  const Tag = (href && !disabled) ? 'a' : 'div';
  return (
    <Tag
      href={href && !disabled ? href : undefined}
      className={`group rounded-xl border border-slate-200 bg-white p-7 sm:p-8 reveal ${(href && !disabled) ? 'hover:border-blue-300 hover:shadow-card transition' : ''}`}
    >
      <div className="text-[40px] sm:text-[48px] leading-none font-extrabold tracking-tight text-blue-600 tabular-nums">{value}</div>
      <div className="mt-3 text-[15px] text-slate-700 leading-snug">{label}</div>
      {source && (
        <div className="mt-4 pt-4 border-t border-slate-100 text-[13px] font-semibold text-slate-500">
          {source}
          {href && !disabled && <span className="text-blue-600 ml-1 group-hover:translate-x-0.5 inline-block transition">&rarr;</span>}
          {href && disabled && <span className="text-slate-400 ml-1 opacity-60 cursor-not-allowed font-normal">(Coming soon)</span>}
        </div>
      )}
    </Tag>
  );
}

/* ===========================================================================
   Reusable: Pain/answer card
   =========================================================================== */
function PainAnswerCard({ pain, answer, Icon }) {
  return (
    <div className="rounded-xl border border-slate-200 bg-white p-7 sm:p-8 reveal flex flex-col">
      {Icon && (
        <span className="inline-flex h-10 w-10 items-center justify-center rounded-lg bg-blue-50 text-blue-600 mb-5">
          <Icon size={22} />
        </span>
      )}
      <p className="text-[15px] font-semibold text-slate-900 leading-snug mb-3">{pain}</p>
      <p className="text-[15px] text-slate-600 leading-relaxed mt-auto">{answer}</p>
    </div>
  );
}

/* ===========================================================================
   Reusable: Feature card
   =========================================================================== */
function FeatureCard({ Icon, title, body, href, linkLabel = 'Learn more' }) {
  return (
    <div className="rounded-xl border border-slate-200 bg-white p-7 sm:p-8 reveal flex flex-col h-full">
      {Icon && (
        <span className="inline-flex h-12 w-12 items-center justify-center rounded-lg bg-blue-50 text-blue-600 mb-5">
          <Icon size={24} />
        </span>
      )}
      <h3 className="h3 mb-3">{title}</h3>
      <p className="body-md text-slate-600 mb-5">{body}</p>
      {href && <div className="mt-auto"><TextLinkCTA href={href}>{linkLabel}</TextLinkCTA></div>}
    </div>
  );
}

/* ===========================================================================
   Reusable: Lead capture form (Book a call / Contact)
   =========================================================================== */
function LeadForm({ buttonLabel = 'Send my details', compact = false }) {
  const [submitted, setSubmitted] = useState(false);
  const onSubmit = (e) => {
    e.preventDefault();
    setSubmitted(true);
  };
  if (submitted) {
    return (
      <div className="rounded-xl border border-blue-200 bg-blue-50 p-7 sm:p-8 text-center">
        <h3 className="text-[22px] font-bold text-slate-900 mb-2">Thanks. We will be in touch.</h3>
        <p className="body-md text-slate-700">
          We have your details. Expect a reply from the sales team the same working day with a few times that suit you. If it is urgent, call us on
          {' '}<a href="tel:+441418102599" className="font-semibold text-blue-700 hover:underline">0141 810 2599</a>.
        </p>
      </div>
    );
  }
  return (
    <form onSubmit={onSubmit} className={`rounded-xl border border-slate-200 bg-white ${compact ? 'p-6' : 'p-7 sm:p-8'} space-y-4`}>
      <div className="grid sm:grid-cols-2 gap-4">
        <Field label="Your name" name="name" required />
        <Field label="Organisation" name="org" required />
      </div>
      <Field label="Work email" name="email" type="email" required />
      <Field label="Phone (optional)" name="phone" type="tel" />
      <TextareaField label="Anything you'd like us to know? (optional)" name="message" rows={3} />
      <input type="text" name="company_url" tabIndex={-1} autoComplete="off" aria-hidden="true" className="hidden" />
      <button
        type="submit"
        className="btn w-full sm:w-auto inline-flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg px-7 py-3.5"
      >
        {buttonLabel}
        <IconArrowRight size={18} />
      </button>
      <p className="text-[13px] text-slate-500 leading-relaxed">
        By submitting you agree to our <a href="Privacy.html" className="underline hover:text-blue-700">privacy policy</a>. We will only use your details to reply about CX-Feedback. No nurture spam.
      </p>
    </form>
  );
}

const Field = ({ label, name, type = 'text', required = false, hint, defaultValue }) => {
  const id = useId();
  return (
    <div>
      <label htmlFor={id} className="block text-[14px] font-semibold text-slate-800 mb-1.5">
        {label} {required && <span className="text-blue-600">*</span>}
      </label>
      <input
        id={id}
        name={name}
        type={type}
        required={required}
        defaultValue={defaultValue}
        className="w-full rounded-lg border border-slate-300 bg-white px-3.5 py-2.5 text-[15px] text-slate-900 placeholder-slate-400 focus:border-blue-600 focus:ring-0"
      />
      {hint && <p className="mt-1 text-[12px] text-slate-500">{hint}</p>}
    </div>
  );
};

const TextareaField = ({ label, name, rows = 4, required = false }) => {
  const id = useId();
  return (
    <div>
      <label htmlFor={id} className="block text-[14px] font-semibold text-slate-800 mb-1.5">
        {label} {required && <span className="text-blue-600">*</span>}
      </label>
      <textarea
        id={id}
        name={name}
        rows={rows}
        required={required}
        className="w-full rounded-lg border border-slate-300 bg-white px-3.5 py-2.5 text-[15px] text-slate-900 placeholder-slate-400 focus:border-blue-600 focus:ring-0"
      />
    </div>
  );
};

/* ===========================================================================
   Reusable: Final CTA band with form + sales team card
   =========================================================================== */
function FinalCTA({ heading = 'Ready to do tenant engagement properly?', body = 'Tell us who you are. We will reply the same working day with a few times that suit you. The call is thirty minutes. No slides, no pressure.' }) {
  return (
    <section id="next-steps" className="relative py-24 lg:py-32 bg-slate-900 text-white overflow-hidden" aria-labelledby="cta-h">
      <div className="absolute -top-32 -right-32 h-96 w-96 rounded-full bg-blue-600/20" aria-hidden="true" />
      <div className="absolute -bottom-32 -left-32 h-96 w-96 rounded-full bg-blue-600/10" aria-hidden="true" />
      <div className="relative max-w-container mx-auto px-5 sm:px-8">
        <div className="grid lg:grid-cols-5 gap-10 lg:gap-14 items-start">
          <div className="lg:col-span-3 reveal">
            <p className="eyebrow text-blue-300 mb-4">Talk to a real person</p>
            <h2 id="cta-h" className="text-[36px] sm:text-[44px] leading-tight font-bold tracking-tight mb-6">
              {heading}
            </h2>
            <p className="body-lg text-slate-300 mb-8 max-w-[560px]">{body}</p>
            <LeadForm />
          </div>
          <aside className="lg:col-span-2 rounded-xl border border-slate-700 bg-slate-800/60 backdrop-blur p-7 sm:p-8 reveal" style={{ transitionDelay: '120ms' }}>
            <p className="text-[13px] uppercase tracking-wider text-slate-400 font-semibold mb-4">You will speak to</p>
            <div className="space-y-5">
              <SalesPerson name="Johnathan Briggs" role="CEO" img="assets/Johnathan_profile100.jpg" />
              <SalesPerson name="Sales team" role="Customer engagement specialists" placeholder />
            </div>
            <hr className="border-slate-700 my-6" />
            <a href="tel:+441418102599" className="flex items-center gap-3 text-white hover:text-blue-300 transition-colors">
              <IconPhoneCall size={20} className="text-blue-400" />
              <div>
                <div className="text-[13px] text-slate-400">Or call us directly</div>
                <div className="text-[18px] font-bold tracking-tight">0141 810 2599</div>
              </div>
            </a>
            <p className="mt-4 text-[13px] text-slate-400 leading-relaxed">
              Monday to Friday, 9am to 5pm UK time. The sales line goes straight to a person, not a hold queue.
            </p>
          </aside>
        </div>
      </div>
    </section>
  );
}

function SalesPerson({ name, role, img, placeholder }) {
  return (
    <div className="flex items-center gap-3">
      {placeholder ? (
        <span className="inline-flex h-12 w-12 items-center justify-center rounded-full bg-blue-600/30 text-blue-200">
          <IconUsers size={20} />
        </span>
      ) : (
        <img src={img} alt={name} className="h-12 w-12 rounded-full object-cover border-2 border-slate-700" />
      )}
      <div>
        <div className="font-semibold text-white">{name}</div>
        <div className="text-[13px] text-slate-400">{role}</div>
      </div>
    </div>
  );
}

/* ===========================================================================
   Reusable: Built-for-UK-social-housing strip (used on multiple pages)
   =========================================================================== */
function BuiltForHousingStrip() {
  const cols = [
    {
      Icon: IconShield,
      title: 'British, UK-hosted, eighteen years in.',
      body: 'Built in the UK by an in-house British development team. Trading since 2008. Hosted in EU data centres. Fully UK GDPR compliant. No offshored code, no offshored support.',
    },
    {
      Icon: IconFileCheck,
      title: 'Procurement-ready.',
      body: 'Independent penetration testing on a regular schedule. Mature procurement documentation, security questionnaires and DPIA support available on request. Listed on G-Cloud.',
    },
    {
      Icon: IconPlug,
      title: 'Live in 30 minutes.',
      body: 'Connects to almost every UK housing management system out of the box. MRI Orchard, NEC, Capita NPS, Castleton, Civica Cx, Aareon QL, SDM, Open Housing, MIS Active H, MS Dynamics, HomeMaster.',
    },
  ];
  return (
    <section className="py-20 lg:py-28 bg-blue-50 border-y border-blue-100" aria-labelledby="bfh-h">
      <div className="max-w-container mx-auto px-5 sm:px-8">
        <SectionHeading eyebrow="Built for UK social housing" h2="The platform procurement teams clear." id="bfh-h" centred />
        <div className="mt-14 grid md:grid-cols-3 gap-7">
          {cols.map((c, i) => (
            <div key={c.title} className="reveal" style={{ transitionDelay: `${i * 80}ms` }}>
              <span className="inline-flex h-12 w-12 items-center justify-center rounded-lg bg-white text-blue-600 mb-5">
                <c.Icon size={24} />
              </span>
              <h3 className="h3 mb-3">{c.title}</h3>
              <p className="body-md text-slate-600">{c.body}</p>
            </div>
          ))}
        </div>
        <div className="mt-12 flex flex-wrap gap-x-7 gap-y-3 items-center justify-center text-[14px] text-slate-500 reveal">
          <span className="text-[12px] uppercase tracking-wider font-semibold text-slate-500">Integrates with:</span>
          {['MRI Orchard', 'NEC', 'Capita NPS', 'Castleton', 'Civica Cx', 'Aareon QL', 'SDM', 'Open Housing', 'MIS Active H', 'MS Dynamics', 'HomeMaster'].map((n) => (
            <span key={n} className="font-medium text-slate-700">{n}</span>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ===========================================================================
   Reusable: Three-step Closing the Loop diagram
   =========================================================================== */
function ClosingTheLoopDiagram({ compact = false }) {
  const steps = [
    {
      n: '01',
      title: 'Ask.',
      body: 'Send the right survey to the right tenant at the right time. Repairs, ASB, new lets, complaints, anniversaries, TSM perception, ad hoc consultations.',
      Icon: IconClipboard,
    },
    {
      n: '02',
      title: 'Acknowledge.',
      body: 'Send a targeted message back to the tenant the same week. A simple, personalised "thank you, we read what you said, here is what happens next" earns the next response.',
      Icon: IconSend,
    },
    {
      n: '03',
      title: 'Show the change.',
      body: 'Weeks or months later, message the same tenants with what was actually done. Pair it with a follow-up survey to measure whether the change worked.',
      Icon: IconRefresh,
    },
  ];
  return (
    <div className={`grid md:grid-cols-3 gap-5 ${compact ? '' : 'mt-12'}`}>
      {steps.map((s, i) => (
        <div key={s.n} className="relative rounded-xl border border-slate-200 bg-white p-7 sm:p-8 reveal" style={{ transitionDelay: `${i * 80}ms` }}>
          <div className="flex items-center gap-3 mb-4">
            <span className="text-[12px] font-bold text-blue-600 tracking-[0.18em]">{s.n}</span>
            <span className="h-px flex-1 bg-slate-200" />
            <span className="inline-flex h-9 w-9 items-center justify-center rounded-lg bg-blue-50 text-blue-600">
              <s.Icon size={18} />
            </span>
          </div>
          <h3 className="text-[24px] font-bold text-slate-900 mb-3 tracking-tight">{s.title}</h3>
          <p className="body-md text-slate-600">{s.body}</p>
        </div>
      ))}
    </div>
  );
}

/* ===========================================================================
   Customer data (single source of truth for quotes and case studies)
   =========================================================================== */
const CUSTOMERS = {
  quotes: [
    { name: 'Charmaine Simei', role: 'CEO', org: 'Tuntum Housing Association', tag: 'CEO endorsement', slug: 'tuntum',
      quote: 'Partnering with CX-Feedback has been the single most important ingredient in our transformation journey in terms of customer communication and engagement.' },
    { name: 'Craig Moran', role: 'Head of Performance and Business Improvement', org: 'Mosscare St Vincents', tag: 'C1 grading', slug: 'msv',
      quote: 'CX-Feedback has helped MSV move away from one-size-fits-all communication, supporting more targeted SMS and email engagement so customers receive clear, timely information about the things that matter to them. A key example was the targeted messaging campaign around stock condition surveys, which helped improve tenant understanding and access, directly supporting one of the key evidence areas in MSV\'s journey from C2 to C1.' },
    { name: 'Jamie Smith', role: 'Improvement and Engagement Officer', org: 'Dacorum Borough Council', tag: 'TIAA', slug: 'dacorum',
      logo: 'assets/logos/Dacorum Borough Council.png',
      quote: 'Dacorum Borough Council first started using the CX-Feedback software in April 2024. Since then it has revolutionised how we send transactional surveys, manage these surveys and analyse the data. This has helped us work more in line with the Transparency, Influence and Accountability standards.' },
    { name: 'Kim Ward', role: 'Head of Housing', org: 'Industrial Dwellings Society', tag: 'TSM uplift', slug: 'ids',
      logo: 'assets/logos/Industrial Dwellings Society.png',
      quote: 'The targeted communication via CX-Feedback has no doubt had a really positive improvement in how our residents are engaged and informed. Communications that might typically have taken a few days to orchestrate prior to using CX-Feedback now take minutes, even seconds sometimes.' },
    { name: 'Kirsty Rose', role: 'Marketing Communications Manager', org: 'Thrive Homes', tag: 'Incident comms', slug: 'thrive',
      logo: 'assets/logos/Thrive Homes.png',
      quote: 'CX-Feedback has honestly changed my life this week regarding communicating with customers. We\'ve been sending multiple updates throughout the day, and the push messages have been incredibly helpful, easy, and stress-free. I\'ve never felt our communications were quite this great during incidents like this, but this time I can say with confidence that every customer was kept updated and informed.' },
    { name: 'Rob Burrows', role: 'Customer Communications and Engagement Partner', org: 'Muir Group Housing Association', tag: 'Reach', slug: 'muir',
      logo: 'assets/logos/Muir Group.png',
      quote: 'Since we started using CX-Feedback 3 to 4 years ago it has revolutionised how we engage with our residents. In the last 12 months we\'ve engaged with 78% of our customers through tailored, relevant messaging via the E+ module and timely surveys.' },
    { name: 'Julie Clements', role: 'Data and Performance Manager', org: 'Regenda', tag: 'Underrepresented groups', slug: 'regenda',
      quote: 'CX-Feedback and the E+ Module have enabled us to bring together the TSM and transactional surveys all in one place. We have found this to be a great benefit. The ability to engage with specific demographics and underrepresented customer groups has been invaluable.' },
    { name: 'Gillian Bell', role: 'Housing Services Manager', org: 'Blairtummock Housing Association', tag: 'Scotland', slug: 'blairtummock',
      quote: 'We have seen a significant improvement in tenant engagement and response rates. Repairs satisfaction surveys: achieving approximately a 25% response rate, up from around 5%. We have 63% of tenants currently engaged and look forward to continuing to develop our use of it.' },
    { name: 'Ben Chilvers', role: 'Senior Customer Experience Officer', org: 'Castles and Coasts Housing Association', tag: 'Scrutiny', slug: 'castles',
      quote: 'Improving our services to tenants is our number one priority at CCHA. We know the best way to do that is to understand what tenants want to see, using tenant consultations. By involving our tenants in our decision making process, even in such a controlled way, we let tenants know that we care, that we\'re listening, and that we\'re willing to take action on their suggestions.' },
    { name: 'Linda Perkins', role: 'Customer Experience and Engagement Manager', org: 'Golding Homes', tag: 'Long-term partnership', slug: 'golding',
      quote: 'We\'ve been using the CX-Feedback system since August 2021 and it has been a central tool in helping us to achieve a complete transformation of our customer engagement practices here at Golding Homes.' },
    { name: 'Susan McDonald', role: 'Housing Officer', org: 'Kingdom Housing Association', tag: 'Scotland', slug: 'kingdom',
      quote: 'CX-Feedback has been a real step change for our tenant engagement. We have been able to engage with our tenants in different areas and adapt our services to meet their local needs.' },
    { name: 'Niki Rother', role: 'Housing Services Assistant', org: 'Albyn Housing Society', tag: 'Scotland', slug: 'albyn',
      quote: 'We\'ve used other, less inclusive, surveying methods before, but our tenants are spread over such a wide area. We wanted to do something different this time. Our tenants wanted to let us know how they feel and we wanted to listen.' },
  ],
  caseStudies: [
    { slug: 'ids', org: 'Industrial Dwellings Society', headline: 'TP07 from 57% to 81% in a year', summary: 'Targeted communications, segmented by estate and stairwell, lifted the headline TSM.', tags: ['HA', 'England', 'TSM uplift'] },
    { slug: 'tuntum', org: 'Tuntum Housing Association', headline: '+12% TP07 since adopting E+', summary: 'CEO-level endorsement. Engagement embedded in everyday operations at a small HA.', tags: ['HA', 'England', 'TSM uplift', 'CEO-endorsed'] },
    { slug: 'msv', org: 'Mosscare St Vincents', headline: 'C2 to C1 grading uplift', summary: 'Targeted messaging on stock condition surveys evidenced the regulator\'s expectations.', tags: ['HA', 'England', 'C1 grading', 'TIAA'] },
    { slug: 'thrive', org: 'Thrive Homes', headline: 'High-rise emergency comms over Christmas', summary: 'Push messaging kept every customer updated through a major water leak, out of hours.', tags: ['HA', 'England', 'Incident comms'] },
    { slug: 'castles', org: 'Castles and Coasts HA', headline: 'Tenants voted on the playpark that got built', summary: 'Textbook example of tenant influence on a real decision, mapped to the TIAA Standard.', tags: ['HA', 'England', 'Scrutiny', 'TIAA'] },
    { slug: 'grampian', org: 'Grampian Housing Association', headline: 'Daily-rolling ARC trend', summary: 'Scottish case study. Anniversary surveys produce a continuous Charter satisfaction trend.', tags: ['HA', 'Scotland', 'ARC'] },
    { slug: 'bury', org: 'Bury Council', headline: 'Closing the loop on the Annual Report', summary: 'Personalised thank-yous to every respondent moved the relationship from data collection to exchange.', tags: ['Council', 'England', 'TIAA'] },
    { slug: 'dacorum', org: 'Dacorum Borough Council', headline: '10-minute Lifeline outage comms', summary: 'Affected supported-housing tenants notified within minutes of an incident.', tags: ['Council', 'England', 'Incident comms', 'TIAA'] },
    { slug: 'blairtummock', org: 'Blairtummock Housing Association', headline: 'Repairs response 5% to 25%', summary: 'Scottish housing association with 63% of tenants actively engaged.', tags: ['HA', 'Scotland'] },
    { slug: 'muir', org: 'Muir Group Housing Association', headline: '78% of customers engaged', summary: 'Tailored messaging plus timely surveys reach a clear majority of tenants every year.', tags: ['HA', 'England', 'Reach'] },
    { slug: 'golding', org: 'Golding Homes', headline: 'Five years of platform partnership', summary: 'A complete transformation of customer engagement practice, on the platform since August 2021.', tags: ['HA', 'England', 'Long-term'] },
    { slug: 'regenda', org: 'Regenda', headline: 'TSM and transactional in one place', summary: 'Reaching underrepresented groups and bringing all surveys together.', tags: ['HA', 'England', 'Underrepresented groups'] },
  ],
};

/* ===========================================================================
   Reusable: Customer voices wall (with theme filter)
   =========================================================================== */
function CustomerVoicesWall({ limit }) {
  const all = CUSTOMERS.quotes;
  const shown = limit ? all.slice(0, limit) : all;
  return (
    <section className="py-20 lg:py-28 bg-white" aria-labelledby="voices-h">
      <div className="max-w-container mx-auto px-5 sm:px-8">
        <SectionHeading eyebrow="Customer voices" h2="What our customers say." intro="Real quotes from named contacts at named UK social landlords." id="voices-h" />
        <div className="mt-10 grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {shown.map((q, i) => (
            <QuoteCard key={q.slug + i} quote={q.quote} name={q.name} role={q.role} org={q.org} tag={q.tag} logo={q.logo} />
          ))}
        </div>
        {limit && all.length > limit && (
          <div className="mt-10 text-center reveal">
            <TextLinkCTA href="Customer-voices.html">Read every customer quote</TextLinkCTA>
          </div>
        )}
      </div>
    </section>
  );
}

/* ===========================================================================
   Reusable: Case study shelf (six tiles)
   =========================================================================== */
function CaseStudyShelf({ heading = 'Customer stories.', sub = 'The work, in their words.' }) {
  return (
    <section className="py-20 lg:py-28 bg-slate-50 border-y border-slate-200" aria-labelledby="cases-h">
      <div className="max-w-container mx-auto px-5 sm:px-8">
        <SectionHeading eyebrow="Customer stories" h2={heading} intro={sub} id="cases-h" />
        <div className="mt-12 grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {CUSTOMERS.caseStudies.slice(0, 6).map((c, i) => (
            <a
              key={c.slug}
              href={`Customers.html#${c.slug}`}
              className="group rounded-xl border border-slate-200 bg-white p-7 hover:border-blue-300 hover:shadow-card transition reveal flex flex-col"
              style={{ transitionDelay: `${i * 60}ms` }}
            >
              <div className="text-[12px] uppercase tracking-wider font-semibold text-slate-500 mb-3">{c.tags.join(' · ')}</div>
              <div className="text-[15px] text-slate-500 mb-2">{c.org}</div>
              <div className="text-[22px] font-bold text-slate-900 leading-snug tracking-tight mb-3">{c.headline}</div>
              <p className="text-[15px] text-slate-600 leading-relaxed mb-5">{c.summary}</p>
              <span className="mt-auto inline-flex items-center gap-1.5 text-blue-600 font-semibold text-[14px]">
                Read the story <IconArrowRight size={16} className="transition-transform group-hover:translate-x-1" />
              </span>
            </a>
          ))}
        </div>
        <div className="mt-12 text-center reveal">
          <TextLinkCTA href="Customers.html">All customer stories</TextLinkCTA>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  Header, Footer, PageHero, SectionHeading,
  QuoteCard, StatTile, PainAnswerCard, FeatureCard,
  LeadForm, Field, TextareaField, FinalCTA,
  BuiltForHousingStrip, ClosingTheLoopDiagram,
  CustomerVoicesWall, CaseStudyShelf,
  useReveal, Wordmark, BtnPrimary, BtnSecondary, TextLinkCTA, ImagePlaceholder,
  CUSTOMERS,
});
