/* Hero intro animation — auto-looping sprite banner that introduces BrokerStudio */

/* Dark theme tokens for the animation surface */
const HERO_BG = '#1a1814';            // deep warm near-black
const HERO_INK = '#f6f4ef';           // bone white
const HERO_MUTED = 'rgba(246,244,239,0.55)';
const HERO_LINE = 'rgba(246,244,239,0.12)';
const HERO_LINE_STRONG = 'rgba(246,244,239,0.22)';
const HERO_CARD = 'rgba(246,244,239,0.04)';
const HERO_ACCENT = 'oklch(70% 0.15 38)'; // brand terracotta, slightly brighter for dark bg

/* ── Mini Stage: autoplay, looping, no chrome, fits container ── */
const HeroStageContext = React.createContext({ time: 0, duration: 14 });

const HeroStage = ({ width = 1280, height = 520, duration = 14, background = 'var(--bg)', children }) => {
  const [time, setTime] = React.useState(0);
  const wrapRef = React.useRef(null);
  const [scale, setScale] = React.useState(1);

  React.useEffect(() => {
    let raf, last;
    const step = (ts) => {
      if (last == null) last = ts;
      const dt = (ts - last) / 1000;
      last = ts;
      setTime(t => (t + dt) % duration);
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [duration]);

  React.useEffect(() => {
    if (!wrapRef.current) return;
    const measure = () => {
      const w = wrapRef.current.clientWidth;
      setScale(Math.min(1, w / width));
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(wrapRef.current);
    return () => ro.disconnect();
  }, [width]);

  return (
    <div ref={wrapRef} style={{ width:'100%', height: height * scale, position:'relative' }}>
      <div style={{
        width, height, background, position:'absolute',
        top:0, left:'50%',
        transform: `translateX(-50%) scale(${scale})`,
        transformOrigin: 'top center',
        overflow:'hidden',
        borderRadius: 14,
        border: `1px solid ${HERO_LINE}`,
        color: HERO_INK,
      }}>
        <HeroStageContext.Provider value={{ time, duration }}>
          {children}
        </HeroStageContext.Provider>
      </div>
    </div>
  );
};

const useHeroTime = () => React.useContext(HeroStageContext).time;

const HeroSprite = ({ start = 0, end = 999, fade = 0.5, children }) => {
  const time = useHeroTime();
  const inWin = time >= (start - fade) && time <= (end + fade);
  if (!inWin) return null;
  const local = time - start;
  const dur = end - start;
  // Crossfade in over `fade`s before start, out over `fade`s after end
  let opacity = 1;
  if (time < start) {
    opacity = clamp((time - (start - fade)) / fade, 0, 1);
  } else if (time > end) {
    opacity = clamp(1 - (time - end) / fade, 0, 1);
  }
  const eased = Easing.easeInOutCubic(opacity);
  return (
    <div style={{position:'absolute', inset:0, opacity: eased}}>
      {typeof children === 'function' ? children({ local, dur, progress: clamp(local/dur,0,1) }) : children}
    </div>
  );
};

/* ── Reusable text/visual primitives ── */
const FadeIn = ({ delay = 0, children, dur = 0.5, y = 14 }) => {
  const time = useHeroTime();
  const t = clamp((time - delay) / dur, 0, 1);
  const eased = Easing.easeOutCubic(t);
  return (
    <div style={{
      opacity: eased,
      transform: `translateY(${(1 - eased) * y}px)`,
      transition: 'none',
    }}>{children}</div>
  );
};

const Counter = ({ from = 0, to = 100, dur = 1.2, delay = 0, suffix = '', prefix = '', start = 0 }) => {
  const time = useHeroTime();
  const t = clamp((time - start - delay) / dur, 0, 1);
  const eased = Easing.easeOutCubic(t);
  const v = from + (to - from) * eased;
  const n = Number.isInteger(to) ? Math.round(v) : v.toFixed(1);
  return <span>{prefix}{n}{suffix}</span>;
};

/* ── Beat layouts (each one is one "scene") ── */

/* Beat 1 — identity */
const BeatIdentity = () => (
  <div style={{position:'absolute', inset:0, display:'flex', flexDirection:'column', justifyContent:'center', padding:'0 80px'}}>
    <FadeIn delay={0}>
      <div className="mono caps" style={{fontSize:13, color:HERO_MUTED, letterSpacing:'0.18em', display:'flex', alignItems:'center', gap:14, marginBottom:24}}>
        <span style={{width:36, height:1, background:HERO_LINE_STRONG}}/> WHO WE ARE
      </div>
    </FadeIn>
    <FadeIn delay={0.4} y={20}>
      <div style={{fontSize:84, fontWeight:600, letterSpacing:'-0.04em', lineHeight:0.95, color: HERO_INK}}>
        Built by brokers,<br/>
        <em style={{fontStyle:'normal', color:HERO_ACCENT}}>for brokers.</em>
      </div>
    </FadeIn>
    <FadeIn delay={1.0} y={12}>
      <div style={{fontSize:18, color:HERO_MUTED, marginTop:24, maxWidth:560, lineHeight:1.5}}>
        We've sat in the broker's seat. We've felt the friction. BrokerStudio is what we wished we had.
      </div>
    </FadeIn>
  </div>
);

/* Beat 2 — work faster */
const BeatFaster = () => {
  const time = useHeroTime();
  const local = time - 7;
  return (
    <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', padding:'0 80px', gap:64}}>
      <div style={{flex:'0 0 auto'}}>
        <FadeIn delay={0}>
          <div className="mono caps" style={{fontSize:13, color:HERO_MUTED, letterSpacing:'0.18em', marginBottom:18}}>WORK FASTER</div>
        </FadeIn>
        <FadeIn delay={0.3} y={16}>
          <div style={{fontSize:72, fontWeight:600, letterSpacing:'-0.03em', lineHeight:1, marginBottom:18, color:HERO_INK}}>
            Quote comparisons in <em style={{fontStyle:'normal', color:HERO_ACCENT}}>minutes,</em><br/>not hours.
          </div>
        </FadeIn>
        <FadeIn delay={0.8} y={10}>
          <div style={{fontSize:17, color:HERO_MUTED, maxWidth:520, lineHeight:1.5}}>
          </div>
        </FadeIn>
      </div>
      <div style={{flex:'1', display:'flex', justifyContent:'flex-end'}}>
        <FadeIn delay={0.6} y={20}>
          <div style={{display:'flex', gap:20, alignItems:'flex-end'}}>
            {[
              { l:'Before', val: 2, unit:'hrs', color:HERO_INK, h: 200, isAccent:false },
              { l:'With BrokerStudio', val: 10, unit:'min', color:HERO_ACCENT, h: 22, isAccent:true },
            ].map((b,i) => {
              const barT = clamp((local - 0.9 - i*0.2) / 1.2, 0, 1);
              const eased = Easing.easeOutCubic(barT);
              return (
                <div key={i} style={{display:'flex', flexDirection:'column', alignItems:'center', gap:12}}>
                  <div style={{fontSize:42, fontWeight:600, letterSpacing:'-0.03em', color: b.isAccent ? HERO_ACCENT : HERO_INK, fontVariantNumeric:'tabular-nums'}}>
                    <Counter from={0} to={b.val} dur={1.4} delay={1.0 + i*0.2} start={4.5} />
                    <span style={{fontSize:18, color:HERO_MUTED, marginLeft:4, fontWeight:500}}>{b.unit}</span>
                  </div>
                  <div style={{
                    width:90, height: b.h * eased,
                    background: b.color, opacity: b.isAccent ? 1 : 0.25,
                    borderRadius: 8,
                    transition:'none',
                  }}/>
                  <div className="mono caps" style={{fontSize:11, color:HERO_MUTED, letterSpacing:'0.12em'}}>{b.l}</div>
                </div>
              );
            })}
          </div>
        </FadeIn>
      </div>
    </div>
  );
};

/* Beat 3 — compliance */
const BeatCompliance = () => (
  <div style={{position:'absolute', inset:0, display:'flex', flexDirection:'column', justifyContent:'center', padding:'0 80px'}}>
    <FadeIn delay={0}>
      <div className="mono caps" style={{fontSize:13, color:HERO_MUTED, letterSpacing:'0.18em', marginBottom:18}}>STAY DEFENSIBLE</div>
    </FadeIn>
    <FadeIn delay={0.3} y={20}>
      <div style={{fontSize:72, fontWeight:600, letterSpacing:'-0.03em', lineHeight:1, marginBottom:36, maxWidth:1000, color:HERO_INK}}>
        Every endorsement, schedule and limit — <em style={{fontStyle:'normal', color:HERO_ACCENT}}>checked.</em>
      </div>
    </FadeIn>
    <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:18, maxWidth:900}}>
      {[
        { i:'check', l:'214', sub:'data points reconciled', delay: 0.7 },
        { i:'shield', l:'100%', sub:'audit trail, time-stamped', delay: 1.0 },
        { i:'doc',    l:'0', sub:'gaps slip past binding', delay: 1.3 },
      ].map((c,i) => (
        <FadeIn key={i} delay={c.delay} y={14}>
          <div style={{padding:'22px 24px', border:`1px solid ${HERO_LINE}`, background:HERO_CARD, borderRadius:12, display:'flex', alignItems:'center', gap:18}}>
            <span style={{width:42, height:42, borderRadius:10, background:`color-mix(in oklab, ${HERO_ACCENT} 18%, transparent)`, color:HERO_ACCENT, display:'grid', placeItems:'center', flexShrink:0}}>
              <Icon name={c.i} size={20}/>
            </span>
            <div>
              <div style={{fontSize:36, fontWeight:600, letterSpacing:'-0.03em', lineHeight:1, color:HERO_INK}}>{c.l}</div>
              <div style={{fontSize:13, color:HERO_MUTED, marginTop:4}}>{c.sub}</div>
            </div>
          </div>
        </FadeIn>
      ))}
    </div>
  </div>
);

/* Beat 4 — connected teams */
const BeatTeams = () => {
  const time = useHeroTime();
  const local = time - 21;
  return (
  <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', padding:'0 80px', gap:48}}>
    <div style={{flex:'0 0 50%'}}>
      <FadeIn delay={0}>
        <div className="mono caps" style={{fontSize:13, color:HERO_MUTED, letterSpacing:'0.18em', marginBottom:18}}>ONE WORKSPACE</div>
      </FadeIn>
      <FadeIn delay={0.3} y={16}>
        <div style={{fontSize:62, fontWeight:600, letterSpacing:'-0.03em', lineHeight:1, marginBottom:24, color:HERO_INK}}>
          Producers, CSRs and principals — <em style={{fontStyle:'normal', color:HERO_ACCENT}}>working in lockstep.</em>
        </div>
      </FadeIn>
      <FadeIn delay={0.8} y={10}>
        <div style={{fontSize:17, color:HERO_MUTED, maxWidth:480, lineHeight:1.5}}>
          Inbox, COIs, quotes, policies, contracts — one record, one source of truth.
        </div>
      </FadeIn>
    </div>
    <div style={{flex:1, position:'relative', height:340, display:'flex', alignItems:'center', justifyContent:'center'}}>
      {/* Center hub */}
      <FadeIn delay={0.5}>
        <div style={{
          width:104, height:104, borderRadius:22,
          background:HERO_INK,
          display:'grid', placeItems:'center',
          position:'relative', zIndex:2,
          boxShadow:'0 12px 40px rgba(0,0,0,0.4)',
          /* Override the stack mark's internal vars so it reads on a white tile inside a dark scene */
          ['--bg']: HERO_BG,
        }}>
          <StackMark size={64} bg={HERO_INK}/>
        </div>
      </FadeIn>
      {/* Orbiting roles */}
      {[
        { label:'Producer', x: -160, y: -120, delay: 0.8 },
        { label:'CSR',      x:  170, y: -110, delay: 1.05 },
        { label:'Principal',x:  180, y:  100, delay: 1.3 },
        { label:'Outlook',  x: -170, y:  110, delay: 1.55 },
      ].map((n,i) => {
        const t = clamp((local - n.delay) / 0.8, 0, 1);
        const eased = Easing.easeOutCubic(t);
        return (
          <React.Fragment key={i}>
            {/* line */}
            <svg style={{position:'absolute', inset:0, pointerEvents:'none', zIndex:1}} width="100%" height="100%">
              <line
                x1="50%" y1="50%"
                x2={`calc(50% + ${n.x * eased}px)`}
                y2={`calc(50% + ${n.y * eased}px)`}
                stroke={HERO_LINE_STRONG} strokeWidth="1" strokeDasharray="3 4"
                opacity={eased}
              />
            </svg>
            <div style={{
              position:'absolute',
              left:`calc(50% + ${n.x * eased}px)`,
              top:`calc(50% + ${n.y * eased}px)`,
              transform:'translate(-50%, -50%)',
              padding:'8px 14px',
              borderRadius:999,
              background:HERO_CARD,
              border:`1px solid ${HERO_LINE_STRONG}`,
              color: HERO_INK,
              fontSize:13, fontWeight:500,
              opacity: eased, zIndex:3,
              whiteSpace:'nowrap',
              backdropFilter:'blur(6px)',
            }}>
              {n.label}
            </div>
          </React.Fragment>
        );
      })}
    </div>
  </div>
  );
};

/* Beat 5 — tools roll-call */
const BeatTools = () => {
  const time = useHeroTime();
  const local = time - 28;
  const tools = [
    'COI Issuance', 'Quote Comparisons', 'Policy Checks',
    'Contract Review', 'Email Integration', 'Renewal Tracking',
  ];
  return (
    <div style={{position:'absolute', inset:0, display:'flex', flexDirection:'column', justifyContent:'center', padding:'0 80px'}}>
      <FadeIn delay={0}>
        <div className="mono caps" style={{fontSize:13, color:HERO_MUTED, letterSpacing:'0.18em', marginBottom:18}}>WHAT'S INSIDE</div>
      </FadeIn>
      <FadeIn delay={0.3} y={16}>
        <div style={{fontSize:64, fontWeight:600, letterSpacing:'-0.03em', lineHeight:1, marginBottom:36, color:HERO_INK}}>
          A toolkit your brokerage <em style={{fontStyle:'normal', color:HERO_ACCENT}}>actually uses.</em>
        </div>
      </FadeIn>
      <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:14, maxWidth:1000}}>
        {tools.map((t, i) => {
          const tT = clamp((local - 0.7 - i*0.14) / 0.7, 0, 1);
          const eased = Easing.easeOutCubic(tT);
          return (
            <div key={i} style={{
              padding:'18px 22px',
              border:`1px solid ${HERO_LINE}`,
              borderRadius:10,
              background:HERO_CARD,
              color:HERO_INK,
              display:'flex', alignItems:'center', gap:12,
              opacity: eased,
              transform:`translateY(${(1-eased)*12}px)`,
            }}>
              <span style={{width:6, height:6, borderRadius:3, background:HERO_ACCENT}}/>
              <span style={{fontSize:17, fontWeight:500, letterSpacing:'-0.01em'}}>{t}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
};

/* Progress dots — show beat position */
const BeatProgress = ({ beats, total }) => {
  const time = useHeroTime();
  return (
    <div style={{position:'absolute', bottom:24, left:'50%', transform:'translateX(-50%)', display:'flex', gap:10, zIndex:10}}>
      {beats.map((b,i) => {
        const active = time >= b.start && time < b.end;
        return (
          <div key={i} style={{
            width: active ? 32 : 6,
            height:6, borderRadius:3,
            background: active ? HERO_ACCENT : HERO_LINE_STRONG,
            transition: 'width 320ms ease, background 320ms ease',
          }}/>
        );
      })}
    </div>
  );
};

/* ── Main composition ── */
const HeroIntroAnimation = () => {
  // Each beat ~7s, with 0.6s crossfade overlap handled by HeroSprite
  const beats = [
    { start: 0,    end: 7,    Component: BeatIdentity },
    { start: 7,    end: 14,   Component: BeatFaster },
    { start: 14,   end: 21,   Component: BeatCompliance },
    { start: 21,   end: 28,   Component: BeatTeams },
    { start: 28,   end: 35,   Component: BeatTools },
  ];
  const TOTAL = 35;
  return (
    <HeroStage width={1320} height={560} duration={TOTAL} background={HERO_BG}>
      {beats.map((b, i) => (
        <HeroSprite key={i} start={b.start} end={b.end} fade={0.6}>
          <b.Component />
        </HeroSprite>
      ))}
      <BeatProgress beats={beats} total={TOTAL} />
    </HeroStage>
  );
};

Object.assign(window, { HeroIntroAnimation });
