/* Hero scene — cinematic cold open:
   1. Grid + scan line ambient layer (parallaxed against scroll)
   2. BODE wordmark unfolds with a chromatic-aberration split that resolves
   3. Headline arrives word-by-word; previous word recedes as next lands
   4. Sub copy + stats fade up on a patient cadence
   5. Agent terminal completes a thought, then collapses to an inline pill */

const HERO_AGENT_THREAD = [
  { t: "Connecting to property management system…",          done: "PMS · linked" },
  { t: "Reading finance ledgers across 7 portfolios…",       done: "Finance · synced" },
  { t: "Cross-referencing energy consumption with occupancy…", done: "Energy · indexed" },
  { t: "Drafting integrated answer…",                        done: "Insight ready." },
];

function HeroAgentTerminal() {
  const [step, setStep] = React.useState(0);
  const [text, setText] = React.useState("");
  const [done, setDone] = React.useState(false);

  React.useEffect(() => {
    if (step >= HERO_AGENT_THREAD.length) {
      const t = setTimeout(() => setDone(true), 800);
      return () => clearTimeout(t);
    }
    let cancelled = false;
    const target = HERO_AGENT_THREAD[step].t;
    let i = 0;
    function tick() {
      if (cancelled) return;
      i++;
      setText(target.slice(0, i));
      if (i < target.length) setTimeout(tick, 22);
      else setTimeout(() => !cancelled && setStep((n) => n + 1), 700);
    }
    setText("");
    const initial = setTimeout(tick, 220);
    return () => { cancelled = true; clearTimeout(initial); };
  }, [step]);

  if (done) {
    return (
      <div className="hero__terminal hero__terminal--done">
        <span className="dot"></span>
        <span className="ready">Insight ready</span>
        <span className="meta">· {HERO_AGENT_THREAD.length} sources unified · 2.3s</span>
      </div>
    );
  }

  return (
    <div className="hero__terminal">
      <div className="hero__terminal-head">
        <span className="agent">AGENT · LIVE</span>
        <span>BODE.001</span>
      </div>
      <ol className="hero__terminal-thread">
        {HERO_AGENT_THREAD.slice(0, step).map((line, i) => (
          <li key={i} className="done">
            <span className="check">✓</span>
            <span>{line.done}</span>
          </li>
        ))}
        {step < HERO_AGENT_THREAD.length && (
          <li className="active">
            <span className="ind">›</span>
            <span>{text}<span className="caret"></span></span>
          </li>
        )}
      </ol>
    </div>
  );
}

function HeroLogo() {
  // Cinematic entry: corner brackets snap into place around where the logo
  // will land, then the wordmark unfolds left→right with a chromatic split
  // that resolves into focus. A coral scan line crosses during the reveal.
  return (
    <div className="hero__logo" aria-label="BODE">
      <span className="hero__logo-bracket hero__logo-bracket--tl" aria-hidden="true"></span>
      <span className="hero__logo-bracket hero__logo-bracket--tr" aria-hidden="true"></span>
      <span className="hero__logo-bracket hero__logo-bracket--bl" aria-hidden="true"></span>
      <span className="hero__logo-bracket hero__logo-bracket--br" aria-hidden="true"></span>
      <div className="hero__logo-stack">
        <BodeLogo className="hero__logo-svg" ariaLabel="BODE" />
      </div>
    </div>
  );
}

/* Type-on terminal eyebrow. Three segments stream in after the logo lands,
   each with its own caret beat — feels like an agent reporting status. */
function HeroEyebrow() {
  const SEGMENTS = [
    { type: 'status',  text: 'LAUNCHING SOON' },
    { type: 'sep',     text: '·' },
    { type: 'context', text: 'PROPERTY INTELLIGENCE' },
  ];
  // The whole eyebrow appears together via CSS animation-delay; each
  // segment also gets its own per-character reveal via inline animation-delay.
  return (
    <div className="hero__eyebrow" role="status" aria-label="Launching soon. Property Intelligence.">
      <span className="hero__eyebrow-dot" aria-hidden="true"></span>
      {SEGMENTS.map((seg, si) => (
        <span key={si} className={`hero__eyebrow-seg hero__eyebrow-seg--${seg.type}`}>
          {[...seg.text].map((ch, ci) => (
            <span
              key={ci}
              className="hero__eyebrow-ch"
              style={{ animationDelay: `${2.6 + si * 0.32 + ci * 0.018}s` }}
            >{ch === ' ' ? ' ' : ch}</span>
          ))}
        </span>
      ))}
      <span className="hero__eyebrow-caret" aria-hidden="true"></span>
    </div>
  );
}

function HeroHeadline() {
  // Three words landing in sequence. Each word "recedes" (lower opacity, soft
  // blur, slight scale) shortly after it has been read, so the eye is led
  // forward through the line.
  const words = ["Instant", "Integrated", "Intelligence"];
  const baseDelay = 1.55;
  const wordGap = 0.42;
  return (
    <h1 className="hero__headline">
      {words.map((w, wi) => {
        const wordStart = baseDelay + wi * wordGap;
        const recedeDelay = wordStart + 0.65;
        return (
          <span
            className={`word ${wi === words.length - 1 ? 'word--final' : ''}`}
            key={wi}
            style={{ '--recede-delay': `${recedeDelay}s` }}
          >
            {[...w].map((c, ci) => {
              const delay = wordStart + ci * 0.035;
              return (
                <span className="ch" key={ci} style={{ animationDelay: `${delay}s` }}>{c}</span>
              );
            })}
          </span>
        );
      })}
      <span className="stop"></span>
    </h1>
  );
}

function HeroAmbient() {
  return (
    <div className="hero__ambient" aria-hidden="true">
      <div className="hero__bg-grid"></div>
      <div className="hero__scan"></div>
      <div className="hero__vignette"></div>
    </div>
  );
}

function Hero() {
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    if (!ref.current) return;
    const grid = ref.current.querySelector('.hero__bg-grid');
    const vignette = ref.current.querySelector('.hero__vignette');
    const t = gsap.to([grid, vignette], {
      yPercent: 12,
      ease: 'none',
      scrollTrigger: {
        trigger: ref.current,
        start: 'top top',
        end: 'bottom top',
        scrub: true,
        invalidateOnRefresh: true,
      },
    });
    return () => {
      if (t.scrollTrigger) t.scrollTrigger.kill();
      t.kill();
    };
  }, []);

  return (
    <section
      ref={ref}
      id="hero"
      className="hero hero--cinematic"
      data-screen-label="01 Hero"
    >
      <HeroAmbient />

      {/* COLD OPEN — first viewport: just the BODE wordmark, vertically
          centered, with the cinematic entry sequence and the type-on eyebrow.
          Headline and supporting copy live below the fold. */}
      <div className="hero__cold-open">
        <HeroLogo />
        <HeroEyebrow />
        <div className="scroll-cue scroll-cue--cold">
          <span>Scroll to continue</span>
          <span className="line"></span>
        </div>
      </div>

      {/* BELOW THE FOLD — the kinetic headline + supporting copy + stats. */}
      <div className="hero__below">
        <div className="hero__content">
          <HeroHeadline />
          <div className="hero__sub">
            <p>The property sector is drowning in data but starving for insight. Owners and operators currently juggle 7 or 8 disconnected systems to understand their business, with no single source of truth.</p>
            <p>BODE is the transformational AI middleware platform that sits above your existing tools and delivers integrated intelligence across all your data sources, in one shot.</p>
          </div>
          <div className="hero__stats">
            <div className="hero__stat">
              <div className="hero__stat-num"><CountUp to={8} suffix="" prefix="7–" /></div>
              <div className="hero__stat-label">Systems unified</div>
            </div>
            <div className="hero__stat">
              <div className="hero__stat-num">01</div>
              <div className="hero__stat-label">Intelligence layer</div>
            </div>
            <div className="hero__stat">
              <div className="hero__stat-num coral">∞</div>
              <div className="hero__stat-label">Clarity unlocked</div>
            </div>
          </div>
        </div>
        <HeroAgentTerminal />
      </div>
    </section>
  );
}

function CountUp({ to, prefix = "", suffix = "" }) {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    let raf, start;
    const dur = 1400;
    function step(t) {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      setN(Math.round(eased * to));
      if (p < 1) raf = requestAnimationFrame(step);
    }
    const id = setTimeout(() => { raf = requestAnimationFrame(step); }, 1900);
    return () => { cancelAnimationFrame(raf); clearTimeout(id); };
  }, [to]);
  return <span>{prefix}{n}{suffix}</span>;
}

window.Hero = Hero;
