// home.jsx — Editorial homepage (Insurify focus).
//
// Visual language follows the measured reference (spacious ivory bands, large
// serif display type, sparse navigation, quiet scroll reveals), carried into
// CriterionMD's forest-green identity. Styles live in styles.css under the
// "Editorial homepage" section (classes prefixed `ed-`).
//
// Content rules (see delivery notes): no invented metrics, payers, scores,
// integrations, or outcomes. The product demonstration is labelled as an
// illustrative example and its findings match the note it displays.

// ── Scroll reveal ────────────────────────────────────────────────────────────
// Adds `is-in` once an element enters the viewport. Content is never hidden
// without JS support for IntersectionObserver, and reduced-motion users get no
// transform (handled in CSS).
function useReveal() {
  React.useEffect(() => {
    const els = Array.from(document.querySelectorAll('.ed-reveal:not(.is-in)'));
    if (!('IntersectionObserver' in window)) {
      els.forEach((el) => el.classList.add('is-in'));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { e.target.classList.add('is-in'); io.unobserve(e.target); }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.08 });
    els.forEach((el) => io.observe(el));
    // Safety net: never leave content invisible if observation stalls.
    const t = setTimeout(() => els.forEach((el) => el.classList.add('is-in')), 4000);
    return () => { io.disconnect(); clearTimeout(t); };
  }, []);
}

// Button with the vertical "label roll" hover (label slides up, a copy slides
// in from below). Pure CSS; reduced motion falls back to a colour change.
function EdButton({ children, onClick, href, variant = 'dark', size = 'md', className = '', label }) {
  const cls = 'ed-btn ed-btn-' + variant + ' ed-btn-' + size + (className ? ' ' + className : '');
  const inner = (
    <span className="ed-btn-roll" data-label={typeof children === 'string' ? children : label}>
      <span className="ed-btn-text">{children}</span>
    </span>
  );
  if (href) {
    return <a className={cls} href={href} onClick={onClick}>{inner}</a>;
  }
  return <button type="button" className={cls} onClick={onClick}>{inner}</button>;
}

function HomePage({ go }) {
  useReveal();
  // Title animations run ~3s; if the animation timeline never advances
  // (some headless/preview contexts), force the settled state after 4.5s.
  React.useEffect(() => {
    const t = setTimeout(() => document.documentElement.classList.add('ed-settled'), 4500);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className="ed-home" data-screen-label="01 Home">
      <EdHero />
    </div>
  );
}

// ── Hero ─────────────────────────────────────────────────────────────────────
function EdHero() {
  // Clip playhead (seconds): drives the visit panel and the loop-transition cover
  const t = useClipTime();
  return (
    <section className="ed-hero ed-hero-emerald" aria-labelledby="ed-hero-title">
      {/* Bottom fade: blends the emerald field into the ivory page below */}
      <div className="ed-hero-fade" aria-hidden="true" />
      <div className="ed-container">
        <h1 id="ed-hero-title" className="ed-display ed-hero-title">
          {/* One line: first phrase drops in from the top; second fades in left → right over 2s */}
          <span className="ed-line ed-line-drop">Your clinic note.</span>{' '}
          <span className="ed-line ed-line-wipe">The payer’s criteria.</span>
        </h1>
        <p className="ed-hero-sub ed-enter" style={{ '--d': '1500ms' }}>
          Document insurance-specific medical necessity<br />requirements <span className="ed-hero-accent">before you sign</span>.
        </p>
      </div>
      <div className="ed-hero-stage home-ed-stage">
        <div className="ed-hero-demo ed-enter" style={{ '--d': '1700ms' }}>
          <InsurifyLaptopDemo />
        </div>
        <EdVisitFlow t={t} />
      </div>
    </section>
  );
}

// ── Laptop product demonstration ─────────────────────────────────────────────
// Silver laptop that starts closed, swings open, and plays the Insurify promo
// clip on its screen — the same clip (cropped to the app screen) used on the
// Insurify page. The clip is mounted from the start so it is loaded by the time
// the lid opens; it is hidden until then.
function InsurifyLaptopDemo() {
  const reduced = React.useMemo(() =>
    typeof window !== 'undefined' && window.matchMedia &&
    window.matchMedia('(prefers-reduced-motion: reduce)').matches, []);
  const [stage, setStage] = React.useState(reduced ? 'open' : 'closed');
  // The clip remembers its playhead in localStorage ('animstage:t'). Start it
  // at 4.6s — its inner laptop is already open there, so the screen crop
  // locks on immediately and the lid opens onto the "point-of-care" title
  // card, then the app. Runs before the iframe mounts.
  React.useState(() => {
    try { window.localStorage.setItem('animstage:t', '4.6'); } catch (e) { /* storage blocked */ }
    return true;
  });

  React.useEffect(() => {
    if (reduced || stage !== 'closed') return;
    const t = setTimeout(() => setStage('open'), 3100);
    return () => clearTimeout(t);
  }, [stage, reduced]);

  return (
    <figure className={'ed-laptop is-' + stage} aria-label="Insurify product demonstration">
      <div className="ed-laptop-rig">
        <div className="ed-laptop-lid">
          <div className="ed-laptop-screen">
            {typeof window !== 'undefined' && window.InsurifyAppClip
              ? React.createElement(window.InsurifyAppClip)
              : null}
          </div>
        </div>
        <div className="ed-laptop-base" aria-hidden="true"><span /></div>
      </div>
    </figure>
  );
}

// ── Bare clip (no laptop) ────────────────────────────────────────────────────
// The same cropped promo clip, framed as a plain rounded screen. Reuses the
// laptop's screen classes so useClipStep() can read it and the loop-transition
// cover still applies.
function InsurifyClipDemo() {
  React.useState(() => {
    try { window.localStorage.setItem('animstage:t', '4.6'); } catch (e) { /* storage blocked */ }
    return true;
  });
  return (
    <figure className="ed-laptop ed-clip is-open" aria-label="Insurify product demonstration">
      <div className="ed-laptop-screen ed-clip-screen">
        {typeof window !== 'undefined' && window.InsurifyAppClip
          ? React.createElement(window.InsurifyAppClip)
          : null}
      </div>
    </figure>
  );
}

// ── Clinician affiliation strip ──────────────────────────────────────────────
const ED_AFFILIATIONS = [
  { name: 'Insight Health Systems', logo: 'assets/logos/insight.png', key: 'orgInsight' },
  { name: 'UMKC School of Medicine', logo: 'assets/logos/umkc.png', key: 'orgUmkc' },
  { name: 'University of Kansas Health', logo: 'assets/logos/ku-health.png', key: 'orgKu' },
  { name: 'Saint Luke’s Hospital, Kansas City', logo: 'assets/logos/saint-lukes.png', key: 'orgStLukes' },
  { name: 'College Park Family Care', logo: 'assets/logos/college-park.png', key: 'orgCollegePark' },
  { name: 'Detroit Medical Center', logo: 'assets/logos/dmc.png', key: 'orgDmc' }
];

function EdAffiliations() {
  const R = (typeof window !== 'undefined' && window.__resources) || {};
  const logo = (o, hidden) => (
    <li key={o.name + (hidden ? '-dup' : '')} className="ed-aff-item" aria-hidden={hidden ? 'true' : undefined}>
      <img src={R[o.key] || o.logo} alt={hidden ? '' : o.name} loading="lazy" decoding="async" />
    </li>
  );
  return (
    <section className="ed-aff" aria-labelledby="ed-aff-title">
      <div className="ed-container">
        <h2 id="ed-aff-title" className="ed-aff-title">Built with clinicians at<span aria-hidden="true">*</span></h2>
        <div className="ed-aff-marquee">
          <ul className="ed-aff-track">
            {ED_AFFILIATIONS.map((o) => logo(o, false))}
            {ED_AFFILIATIONS.map((o) => logo(o, true))}
          </ul>
        </div>
        <p className="ed-aff-note">
          *Where our physician design partners practice. Listing does not imply institutional endorsement.
        </p>
      </div>
    </section>
  );
}

// ── How it works (beside the laptop, synced to the clip) ─────────────────────
// Step windows are seconds on the promo clip's 20-second loop, measured from
// what the clip shows: 9–11.6s the note is loaded ("Analyze note"); 11.6–15.8s
// it reads the note, matches the payer policy and flags a gap; 15.8–17.5s the
// note gains addenda and all criteria are met. Before 9s is the intro; from
// 17.5s an outro logo card, then (18.9s → loop → 3.3s) the clip's own laptop
// closes and reopens, which the screen hides behind a plain dark frame.
const ED_STEPS = [
  { n: '1', t: 'Start with the note', s: 'Paste the draft clinic note for the planned procedure.', from: 9.0, to: 11.6 },
  { n: '2', t: 'See what’s missing', s: 'Insurify compares the note with the applicable payer criteria and lists documentation that is missing or insufficient.', from: 11.6, to: 15.8 },
  { n: '3', t: 'Verify and refine', s: 'Check each finding against the chart, then edit the note where it is clinically accurate. The judgment stays with you.', from: 15.8, to: 17.5 }
];

// Reads the clip's playback time (seconds) from its same-origin iframe, and
// keeps the loop-transition cover in sync. Returns null until it can read it.
function useClipTime() {
  const [time, setTime] = React.useState(null);
  React.useEffect(() => {
    const read = () => {
      const f = document.querySelector('.ed-laptop-screen iframe');
      let d; try { d = f && f.contentDocument; } catch (e) { return; }
      if (!d || !d.body) return;
      const el = [...d.querySelectorAll('div,span')].find((e) =>
        e.children.length === 0 && /^\d:\d\d\.\d\d$/.test(e.textContent.trim()));
      if (!el) return;
      const [m, sec] = el.textContent.trim().split(':');
      const t = Number(m) * 60 + Number(sec);
      setTime(t);
      const lap = document.querySelector('.ed-laptop');
      if (lap) lap.classList.toggle('is-clip-gap', t >= 18.9 || t < 3.3);
    };
    const id = setInterval(read, 250);
    return () => clearInterval(id);
  }, []);
  return time;
}

// Index of the step whose window contains the playhead, or -1 (intro/outro).
const clipStepAt = (t, steps = ED_STEPS) =>
  t == null ? -1 : steps.findIndex((x) => t >= x.from && t < x.to);

function useClipStep() {
  return clipStepAt(useClipTime());
}

function EdFlowSteps({ active }) {
  return (
    <div id="how-it-works" className="ed-flow ed-enter" style={{ '--d': '2100ms' }} aria-labelledby="ed-flow-title">
      <h2 id="ed-flow-title" className="ed-sr">How it works</h2>
      <ol className="ed-flow-list">
        {ED_STEPS.map((x, i) => (
          <li key={x.n} className={'ed-flow-step' + (i === active ? ' is-active' : '') + (active > i ? ' is-done' : '')}
            aria-current={i === active ? 'step' : undefined}>
            <span className="ed-flow-n" aria-hidden="true">{x.n}</span>
            <div>
              <h3 className="ed-flow-t">{x.t}</h3>
              <p className="ed-flow-s">{x.s}</p>
            </div>
          </li>
        ))}
      </ol>
    </div>
  );
}

// ── Homepage: the visit, beside the laptop (synced to the clip) ─────────────
// The Insurify page's four steps, shown as a visit timeline rather than a
// numbered list. Step windows follow the clip: the note is loaded (9–10.4s),
// procedure and payer are selected (10.4–11.6s), criteria are checked and a
// gap flagged (11.6–15.8s), then the note is strengthened (15.8–17.5s).
const ED_VISIT = [
  { t: 'Write or paste the note', s: 'Document in your own words. No templates.', from: 9.0, to: 10.4,
    icon: ['M6 3h8l4 4v14H6z', 'M14 3v4h4', 'M9 12h6', 'M9 16h4'] },
  { t: 'Select procedure & payer', s: 'Choose the planned procedure and the patient\u2019s payer.', from: 10.4, to: 11.6,
    icon: ['M3 6.5a1.5 1.5 0 0 1 1.5-1.5h15A1.5 1.5 0 0 1 21 6.5v11a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 17.5z', 'M7 10.5a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0-3 0', 'M13 10h5', 'M13 14h3.5', 'M6.5 15.5h4.5'] },
  { t: 'See criteria & gaps', s: 'The payer\u2019s policy, checked line by line.', from: 11.6, to: 15.8,
    icon: ['M4 6.5l1.3 1.3L7.8 5.3', 'M4 12l1.3 1.3 2.5-2.5', 'M5.8 16.5v1.6', 'M5.8 20.2v.1', 'M11 7h9', 'M11 12.5h9', 'M11 18h6'] },
  { t: 'Strengthen & submit', s: 'Close gaps while the patient is still in the room.', from: 15.8, to: 17.5,
    icon: ['M3 18c1.6-3.6 3.4-3.6 3.6-.6.2 2.6 2.2 1.4 3.2-.9.8-1.8 2.2-1.6 2.4.6', 'M3 21h12', 'M15 8.5l2.2 2.2L21.5 6.4'] }
];

function EdVisitFlow({ t }) {
  const active = clipStepAt(t, ED_VISIT);
  const end = ED_VISIT[ED_VISIT.length - 1].to;
  // Each connector fills gold while its step plays (0 → 1)
  const fill = (x) => t == null || t < x.from || t >= 18.9 ? 0 : Math.min(1, (t - x.from) / (x.to - x.from));
  const done = t != null && t >= end && t < 18.9;
  return (
    <aside className={'ed-visit ed-enter' + (done ? ' is-complete' : '')} style={{ '--d': '2100ms' }}
      aria-labelledby="ed-visit-title">
      <h2 id="ed-visit-title" className="ed-sr">How it works</h2>
      <div className="ed-visit-body">
        <ol className="ed-visit-list">
          {ED_VISIT.map((x, i) => {
            const state = i === active ? ' is-active' : (done || active > i ? ' is-done' : '');
            return (
              <li key={x.t} className={'ed-visit-step' + state} style={{ '--f': fill(x) }} aria-current={i === active ? 'step' : undefined}>
                <span className="ed-visit-ic" aria-hidden="true">
                  <svg viewBox="0 0 24 24">
                    {x.icon.map((d) => <path key={d} d={d} pathLength="1" />)}
                  </svg>
                </span>
                <div>
                  <h3 className="ed-visit-t">{x.t}</h3>
                  <p className="ed-visit-s">{x.s}</p>
                </div>
              </li>
            );
          })}
        </ol>
      </div>
    </aside>
  );
}

Object.assign(window, { HomePage, EdButton, InsurifyLaptopDemo, InsurifyClipDemo, EdAffiliations, EdFlowSteps, EdVisitFlow, useClipStep, useClipTime });
