/* ===========================================================================
   Feature showcase — replaces the 60-second video block.
   ---------------------------------------------------------------------------
   - Three "primary" features always visible, each = left text + right product
     screenshot. The three most likely to win a demo booking.
   - Six "more" features collapsed in an accordion. Open one and the layout
     mirrors the primary blocks: tags + headline + body + CTA on the left,
     video thumbnail on the right.
   =========================================================================== */

const { useState: useStateFS } = React;

/* Pill tag — the small chips above the headline (Culture-Amp style). */
function FSTag({ label, tone = 'blue' }) {
  const styles = tone === 'amber'
    ? 'bg-amber-50  border-amber-200 text-amber-800'
    : tone === 'violet'
      ? 'bg-violet-50 border-violet-200 text-violet-800'
      : 'bg-blue-50   border-blue-200   text-blue-800';
  const dot = tone === 'amber'
    ? 'bg-amber-500'
    : tone === 'violet'
      ? 'bg-violet-500'
      : 'bg-blue-600';
  return (
    <span className={`inline-flex items-center gap-1.5 text-[13px] font-semibold rounded-full px-3 py-1.5 border ${styles}`}>
      <span className={`h-1.5 w-1.5 rounded-full ${dot}`} />
      {label}
    </span>
  );
}

/* Reusable browser-style frame around a product mock. */
function FSFrame({ children, label, className = '' }) {
  return (
    <div className={`relative h-full flex flex-col bg-white ${className}`}>
      {/* Faux top bar */}
      <div className="flex items-center gap-2 px-4 py-3 border-b border-slate-100 bg-slate-50 shrink-0">
        <span className="h-2.5 w-2.5 rounded-full bg-slate-300" />
        <span className="h-2.5 w-2.5 rounded-full bg-slate-300" />
        <span className="h-2.5 w-2.5 rounded-full bg-slate-300" />
        <span className="ml-3 text-[12px] font-medium text-slate-500 truncate">{label}</span>
      </div>
      <div className="bg-white flex-1 min-h-0 overflow-hidden">{children}</div>
    </div>
  );
}

/* ---------------------------------------------------------------------------
   Product screen mocks. Each one is a small fake UI lifted to a polished
   layout. No real screenshots; everything is hand-rolled HTML.
   --------------------------------------------------------------------------- */

/* Each showcase lives in its own file under /showcases. They register their
   ScreenX function as a global; we resolve them by name at render time so
   load-order between this file and the showcase files doesn't matter. */
const SCREEN_GLOBALS = {
  concern: 'ScreenConcern',
  survey: 'ScreenSurvey',
  reporting: 'ScreenReporting',
  messaging: 'ScreenMessaging',
  exit: 'ScreenExitTrigger',
  library: 'ScreenLibrary',
  integration: 'ScreenIntegration',
  onboarding: 'ScreenOnboarding',
  benchmarks: 'ScreenBenchmarks',
};

function ProductScreen({ kind, playing }) {
  const name = SCREEN_GLOBALS[kind] || SCREEN_GLOBALS.survey;
  const C = window[name];
  if (!C) return null;
  return (
    <div className="h-[440px] overflow-hidden rounded-2xl border border-slate-200 shadow-cardlg bg-white">
      <div className="w-full h-full">
        <C playing={playing} />
      </div>
    </div>
  );
}

/* Video thumbnail used inside the accordion panels. The "thumbnail" is the
   product screen behind a tinted overlay with a play button. Not autoplaying;
   click toggles a faux pause state. */
function VideoThumb({ kind }) {
  return (
    <div className="relative rounded-2xl overflow-hidden">
      <ProductScreen kind={kind} playing={true} />
    </div>
  );
}

/* ---------------------------------------------------------------------------
   Primary row — always expanded
   --------------------------------------------------------------------------- */
function FeaturePrimary({ f, idx }) {
  const flip = idx % 2 === 1;
  // Mobile: scale the mock to fit a consistent 240px-tall framed box (same pattern as the home carousel).
  const mobileScale = 240 / 440; // ProductScreen wrapper is 440px tall
  const mobileInner = {
    transform: `scale(${mobileScale})`,
    transformOrigin: 'top left',
    width: `${100 / mobileScale}%`,
  };
  return (
    <div id={f.preview} className="grid lg:grid-cols-12 gap-6 sm:gap-10 lg:gap-16 items-center reveal scroll-mt-28">
      <style>{`
        @media (max-width: 639px) {
          .feat-mock-outer { height: 240px; overflow: hidden; border-radius: 1rem; border: 1px solid #e2e8f0; background: #ffffff; }
          .feat-mock-inner > div,
          .feat-mock-inner > div > div:first-child,
          .feat-mock-inner > div > div:first-child > div:first-child,
          .feat-mock-inner > div > div:first-child > div:first-child > div:first-child {
            border-color: transparent !important;
            box-shadow: none !important;
          }
        }
        @media (min-width: 640px) {
          .feat-mock-inner { transform: none !important; width: 100% !important; }
        }
      `}</style>
      <div className={`order-2 lg:col-span-7 ${flip ? 'lg:order-1' : 'lg:order-2'} feat-mock-outer`}>
        <div className="feat-mock-inner" style={mobileInner}>
          <ProductScreen kind={f.preview} playing={true} />
        </div>
      </div>
      <div className={`order-1 lg:col-span-5 ${flip ? 'lg:order-2' : 'lg:order-1'}`}>
        <div className="flex flex-wrap gap-2 mb-4 sm:mb-5">
          {f.tags.map((t, i) => <FSTag key={t.label || t} label={t.label || t} tone={t.tone} />)}
        </div>
        <h3 className="text-[24px] sm:text-[38px] lg:text-[42px] leading-[1.12] sm:leading-[1.08] font-bold text-slate-900 tracking-tight">{f.title}</h3>
        <p className="mt-3 sm:mt-5 text-[15px] sm:text-[19px] leading-relaxed text-slate-600 max-w-[52ch]">{f.body}</p>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------------------
   Accordion row — collapsed by default; opens to show full content + video
   --------------------------------------------------------------------------- */
function FeatureAccordion({ f }) {
  const [open, setOpen] = useStateFS(false);
  return (
    <div className="bg-white">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        aria-expanded={open}
        className={`w-full px-6 lg:px-8 py-6 flex items-center justify-between gap-6 text-left transition-colors ${open ? 'bg-slate-50' : 'hover:bg-slate-50'}`}
      >
        <span className="text-[18px] sm:text-[20px] font-semibold text-slate-900 leading-snug">{f.title}</span>
        <span
          className={`shrink-0 inline-flex items-center justify-center h-10 w-10 rounded-full border transition-all ${open
            ? 'bg-blue-600 border-blue-600 text-white rotate-45'
            : 'bg-white border-slate-300 text-slate-700'}`}
          aria-hidden="true"
        >
          <IconPlus size={18} />
        </span>
      </button>
      {open && (
        <div className="px-6 lg:px-8 pb-10 pt-6 bg-slate-50">
          <div className="grid lg:grid-cols-12 gap-10 lg:gap-16 items-center">
            <div className="order-2 lg:order-2 lg:col-span-7">
              <ProductScreen kind={f.preview} playing={true} />
            </div>
            <div className="order-1 lg:order-1 lg:col-span-5">
              <div className="flex flex-wrap gap-2 mb-5">
                {f.tags.map((t) => <FSTag key={t.label || t} label={t.label || t} tone={t.tone} />)}
              </div>
              <h3 className="text-[32px] sm:text-[38px] lg:text-[42px] leading-[1.08] font-bold text-slate-900 tracking-tight">{f.title}</h3>
              <p className="mt-5 body-lg max-w-[52ch]">{f.body}</p>
              {f.bullets && (
                <ul className="mt-5 space-y-2.5">
                  {f.bullets.map((b) => (
                    <li key={b} className="flex items-start gap-2.5 text-[15px] leading-snug text-slate-700">
                      <span className="mt-1 inline-flex items-center justify-center h-4 w-4 shrink-0 rounded-full bg-blue-600 text-white">
                        <IconCheck size={12} strokeWidth={3} />
                      </span>
                      <span>{b}</span>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------------------------------------------------------------------------
   The section
   --------------------------------------------------------------------------- */
function FeatureShowcase() {
  const primary = [
    {
      tags: [{ label: 'AI Critical Concern', tone: 'amber' }, { label: 'Safeguarding' }],
      title: "Critical Concern: an AI safeguard on every open-text answer.",
      body: "A safeguarding model scans every free-text response as it lands, flagging harassment, bullying and mental health risks against criteria tuned for the housing sector. Users are alerted within minutes, the response is in front of them already routed, and the audit trail is written for you. The work happens between submission and morning coffee, not in an exit interview six months later.",
      ctaText: 'Explore Critical Concern',
      ctaHref: 'Book a demo.html',
      preview: 'concern',
    },
    {
      tags: [{ label: 'Surveys' }, { label: 'Response rate' }],
      title: 'Surveys staff trust enough to answer honestly.',
      body: "Invitations come from a colleaguepulse.co.uk address, hosted outside your organisation and your domain. The anonymity claim holds because the platform is genuinely outside the building. Staff fill in the survey because the reply lands with us, not with the line manager.",
      ctaText: 'Explore the survey builder',
      ctaHref: 'Book a demo.html',
      preview: 'survey',
    },
    {
      tags: [{ label: 'Messaging' }, { label: 'Frontline reach' }],
      title: 'Four-channel messaging with an audience builder behind it.',
      body: 'Compose once, send across work email, work SMS, personal email and personal SMS. Build the audience from any employee attribute (role, department, contract type, length of service, patch), and the platform handles the channel mix per recipient. The repairs operative in a van gets an SMS; the office team gets the email; everyone receives the same content.',
      ctaText: 'Explore targeted messaging',
      ctaHref: 'Book a demo.html',
      preview: 'messaging',
    },
  ];

  const more = [
    {
      title: 'Customisable dashboards, and board-ready packs generated for you.',
      tags: [{ label: 'Reporting' }, { label: 'Dashboards' }, { label: 'AI summary' }],
      body: 'Build the dashboards you actually look at with drag-and-drop charts: filter by team, site, contract type or any HR attribute. Then build a separate report on top: the AI reads every open-text response and writes a plain-English summary by theme, with quotes attached, exported to Word or PDF in your house style, with your logo, colours and fonts, ready to drop straight into the agenda.',
      bullets: [
        'Drag-and-drop dashboards',
        'AI summary of every open-text answer',
        'Word export in your house style',
      ],
      preview: 'reporting',
      runtime: '1:15',
    },
    {
      title: 'Exit surveys that land before the bridges are burned.',
      tags: [{ label: 'Exit surveys' }, { label: 'Automation' }],
      body: 'We trigger ten days before the leave date so respondents reply while the answers are still honest, before the post-handover wind-down sets in. The result is higher response rates and a sharper read on why people actually leave, while you can still do something about it.',
      bullets: [
        'Triggered by HR system sync, not manual',
        'Sender, timing and follow-up tuneable per audience',
        'Anonymous by default',
      ],
      preview: 'exit',
      runtime: '1:08',
    },
    {
      title: 'Every question type you need, all in one builder.',
      tags: [{ label: 'Question types' }, { label: 'Survey builder' }],
      body: 'Short text and paragraph for open responses. Single choice, multiple choice and yes/no for structured answers. Satisfaction scales, custom ratings, date pickers and other special question types when you need them, all in the same builder.',
      bullets: [
        'Text · short answer and paragraph',
        'Choice · single, multiple, yes/no',
        'Satisfaction scales and custom ratings',
        'Skip logic, dropdowns and special types built in',
      ],
      preview: 'library',
      runtime: '0:58',
    },
    {
      title: 'Plugs into the HR platform you already use.',
      tags: [{ label: 'Integration' }, { label: 'Auto-sync' }],
      body: 'Connect once and your employee data flows in continuously. New starters appear the night they\'re added, leavers and role changes update themselves. No CSV uploads, no IT ticket, no manual list-keeping.',
      bullets: [
        'Live in week one with a clean connection',
        'New joiners auto-enrolled into journeys',
        'Leavers, movers and role changes sync nightly',
      ],
      preview: 'integration',
      runtime: '1:31',
    },
    {
      title: 'Automated onboarding, exit and training journeys.',
      tags: [{ label: 'Journeys' }, { label: 'Automation' }],
      body: 'Day-one welcome message, end of week-one onboarding survey, 90-day probation survey feedback, annual feedback survey. Configure once, runs for every new starter from now on.',
      bullets: [
        'Templates for new starter, leaver, returner and internal move',
        'Editable by HR, not by IT',
        'Pause, branch and skip on any attribute',
      ],
      preview: 'onboarding',
      runtime: '1:46',
    },
  ];

  return (
    <section id="features" className="py-14 sm:py-24 lg:py-32 bg-white" aria-label="Features in detail">
      <div className="max-w-container mx-auto px-5 sm:px-8">
        <div className="space-y-12 sm:space-y-20 lg:space-y-28">
          {(() => {
            const byPreview = Object.fromEntries([...primary, ...more].map((f) => [f.preview, f]));
            const order = ['survey', 'concern', 'library', 'messaging', 'reporting', 'exit', 'integration', 'onboarding'];
            return order.map((k, i) => byPreview[k] && <FeaturePrimary key={k} f={byPreview[k]} idx={i} />);
          })()}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  FeatureShowcase, FeaturePrimary, FeatureAccordion, ProductScreen, VideoThumb,
  FSTag, FSFrame, FeatureHighlights,
});

/* ===========================================================================
   FeatureHighlights — home-page teaser. Three compact tiles + a "see all"
   call-to-action that pushes to the dedicated Features page.
   =========================================================================== */
function FeatureHighlights() {
  const items = [
    {
      tagLabel: 'AI Critical Concern',
      tagTone: 'amber',
      headline: 'Catch distress signals the day they happen.',
      body: 'AI reads every response for bullying, harassment and mental health risks, alerting you instantly so you can intervene before a resignation lands.',
      hint: 'See how it routes',
      href: 'Features.html#concern',
      mock: 'concern',
    },
    {
      tagLabel: 'Surveys',
      tagTone: 'blue',
      headline: 'A response rate that actually means something.',
      body: "Surveys go out from a Colleague Pulse address, not your employer's. Staff trust the platform because it is genuinely outside the building.",
      hint: 'See the survey experience',
      href: 'Features.html#survey',
      mock: 'survey',
    },
    {
      tagLabel: 'Targeted messaging',
      tagTone: 'emerald',
      headline: 'The right message, to the right people, in seconds.',
      body: 'Email and SMS to work and personal contact details. Build the audience from any employee attribute and send in seconds.',
      hint: 'See the messaging tool',
      href: 'Features.html#messaging',
      mock: 'messaging',
    },
  ];

  return (
    <section id="features-teaser" className="py-24 lg:py-32 bg-white" aria-labelledby="teaser-h">
      <div className="max-w-container mx-auto px-5 sm:px-8">
        <div className="max-w-[820px] reveal">
          <p className="eyebrow mb-4">What it does</p>
          <h2 id="teaser-h" className="h2">Purpose-built for UK housing associations, end to end.</h2>
          <p className="mt-5 body-lg text-slate-600">
            The screens HR Directors point at first when their CEO asks what we are paying for. More sit behind them; click through if you want the long version.
          </p>
        </div>

        <div className="mt-14 lg:mt-20 grid sm:grid-cols-2 lg:grid-cols-3 gap-6 lg:gap-7">
          {items.map((it, i) => <HighlightCard key={i} it={it} idx={i} />)}
        </div>

        <div className="mt-14 lg:mt-16 reveal">
          <a
            href="Features.html"
            className="group block rounded-2xl bg-slate-900 text-white p-8 lg:p-10 shadow-card hover:shadow-cardlg hover:-translate-y-[2px] active:translate-y-0 active:scale-[0.995] transition-[box-shadow,transform] duration-300 ease-out"
          >
            <div className="grid lg:grid-cols-12 gap-6 lg:gap-10 items-center">
              <div className="lg:col-span-8">
                <p className="text-[13px] uppercase tracking-wider font-semibold text-blue-300 mb-3">
                  Every feature, in detail
                </p>
                <h3 className="text-[26px] sm:text-[32px] leading-tight font-bold tracking-tight">
                  The features HR Directors come back for.
                </h3>
                <p className="mt-4 text-[17px] leading-relaxed text-slate-300 max-w-[60ch]">
                  Surveys, messaging, reporting, the AI safeguard, sector benchmarks, automated journeys, HR integration, the housing question library and the exit-survey trigger. Five minutes; less if you skim.
                </p>
              </div>
              <div className="lg:col-span-4 lg:flex lg:justify-end">
                <span className="inline-flex items-center justify-center gap-2 bg-blue-600 group-hover:bg-blue-500 text-white font-semibold rounded-lg px-6 py-3.5 text-[17px] transition-colors">
                  See all features
                  <IconArrowRight size={18} className="transition-transform group-hover:translate-x-1" />
                </span>
              </div>
            </div>
          </a>
        </div>
      </div>
    </section>
  );
}

function HighlightCard({ it, idx }) {
  return (
    <a
      href={it.href}
      className="reveal group flex flex-col rounded-2xl bg-white border border-slate-200 p-6 lg:p-7 shadow-card hover:shadow-cardlg hover:border-blue-200 hover:-translate-y-[2px] active:translate-y-0 active:scale-[0.99] transition-[box-shadow,border-color,transform] duration-300 ease-out"
      style={{ transitionDelay: `${idx * 80}ms` }}
    >
      {/* Compact mock */}
      <div className="rounded-xl overflow-hidden border border-slate-100 mb-5 bg-slate-50 aspect-[1.5/1] relative">
        {it.img ? (
          <img
            src={it.img}
            alt={it.headline}
            className="w-full h-full object-cover object-top"
          />
        ) : (
          <div className="absolute inset-0 origin-top-left scale-[0.52] pointer-events-none" style={{ width: '192.3%', height: '192.3%' }}>
            <ProductScreen kind={it.mock} />
          </div>
        )}
      </div>
      <div className="mb-3">
        <FSTag label={it.tagLabel} tone={it.tagTone} />
      </div>
      <h3 className="text-[20px] sm:text-[22px] leading-tight font-bold text-slate-900 tracking-tight mb-2.5">
        {it.headline}
      </h3>
      <p className="text-[15px] leading-relaxed text-slate-600 mb-5">{it.body}</p>
      <div className="mt-auto inline-flex items-center gap-1.5 text-blue-600 group-hover:text-blue-700 font-semibold text-[15px]">
        <span className="underline-offset-4 group-hover:underline">{it.hint}</span>
        <IconArrowRight size={16} className="transition-transform group-hover:translate-x-1" />
      </div>
    </a>
  );
}
