// FastFix AI — 20-second hero explainer
// Story arc:
//   0.0 – 4.5s   CHAOS    : 7 disconnected tools jittering around a stressed phone — the problem
//   4.5 – 7.5s   PROBLEMS : three indictments flash (lost calls, dead ads, invisible site)
//   7.5 – 10.5s  COLLAPSE : everything sucks into the FastFix mark — the fix
//   10.5 – 16s   STACK    : 7 services bloom out as labeled orbits around the FF mark
//   16 – 20s     PROMISE  : final tagline + CTA, hold beat

const FFV_CREAM   = '#F7F2E8';
const FFV_CREAM_2 = '#F1ECDF';
const FFV_CREAM_3 = '#FAF6EC';
const FFV_INK     = '#1B1814';
const FFV_INK_2   = '#5B544A';
const FFV_INK_3   = '#8A8275';
const FFV_GOLD    = '#C7A24A';
const FFV_GOLD_DK = '#A88431';
const FFV_GOLD_BG = '#FBF3DA';
const FFV_GOLD_SOFT = '#F4E6BE';
const FFV_RED     = '#C84B3C';
const FFV_RED_BG  = '#FBE3DF';
const FFV_BORDER  = '#E8E0CC';

const FFV_SERIF = "'Instrument Serif', Georgia, serif";
const FFV_SANS  = "'Inter', -apple-system, BlinkMacSystemFont, sans-serif";

// ── Small helpers ───────────────────────────────────────────────────────────
const ffvLerp = (a, b, t) => a + (b - a) * t;

// Jitter: deterministic per-seed wobble, used to make floating tools shake
function ffvJitter(seed, time, amp = 4, speed = 1.6) {
  const a = Math.sin(time * speed + seed * 1.3) * amp;
  const b = Math.cos(time * (speed * 0.8) + seed * 2.1) * amp;
  return { x: a, y: b };
}

// ── A floating "tool card" — the problem state ─────────────────────────────
function FFVToolCard({ x, y, label, glyph, color, bg, seed, fadeOut = 0, collapseTo = null }) {
  const t = useTime();
  const j = ffvJitter(seed, t, 5, 1.4);

  // Collapse animation — pulls toward FF mark when scene 3 fires
  let cx = x, cy = y, scale = 1, opacity = 1 - fadeOut;
  if (collapseTo) {
    const { tx, ty, progress } = collapseTo;
    const e = window.Easing.easeInQuart(progress);
    cx = ffvLerp(x, tx, e);
    cy = ffvLerp(y, ty, e);
    scale = 1 - 0.6 * e;
    opacity = (1 - fadeOut) * (1 - e * 0.8);
  }

  return (
    <div style={{
      position: 'absolute',
      left: cx + j.x, top: cy + j.y,
      width: 168, padding: '12px 14px',
      background: '#fff',
      border: `1px solid ${FFV_BORDER}`,
      borderRadius: 12,
      boxShadow: '0 14px 28px rgba(40,30,10,0.10)',
      display: 'flex', alignItems: 'center', gap: 10,
      transform: `scale(${scale})`,
      transformOrigin: 'center',
      opacity,
      fontFamily: FFV_SANS,
      willChange: 'transform, opacity',
    }}>
      <div style={{
        width: 30, height: 30, borderRadius: 8,
        background: bg, color, fontWeight: 700, fontSize: 13,
        display: 'grid', placeItems: 'center', flexShrink: 0,
      }}>{glyph}</div>
      <div style={{ fontSize: 12.5, fontWeight: 600, color: FFV_INK }}>{label}</div>
    </div>
  );
}

// ── FastFix brand mark (the house ".ai" glyph) ──────────────────────────────
function FFVMonogram({ x, y, size, ringPulse = 0 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      width: size, height: size,
      transform: 'translate(-50%, -50%)',
    }}>
      {ringPulse > 0 && (
        <div style={{
          position: 'absolute', inset: -size * 0.3 * ringPulse,
          borderRadius: '50%',
          border: `2px solid ${FFV_GOLD}`,
          opacity: (1 - ringPulse) * 0.6,
        }}/>
      )}
      <img
        src="logo-mark-dark.png"
        alt=""
        style={{
          width: '100%', height: '100%',
          objectFit: 'contain',
          filter: 'drop-shadow(0 14px 28px rgba(167,131,49,0.35))',
        }}
      />
    </div>
  );
}

// Wordmark (full "FastFix.ai") — used in the promise scene
function FFVWordmark({ x, y, width }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      width, transform: 'translate(-50%, -50%)',
    }}>
      <img src="logo-dark.png" alt="FastFix.ai" style={{ width: '100%', display: 'block' }}/>
    </div>
  );
}

// ── A "service" satellite — the solution state ──────────────────────────────
function FFVServiceOrbit({ centerX, centerY, angle, distance, label, glyph, appearAt }) {
  const t = useTime();
  const localT = Math.max(0, t - appearAt);
  const eased = window.Easing.easeOutBack(window.clamp(localT / 0.55, 0, 1));

  const r = distance * eased;
  const px = centerX + Math.cos(angle) * r;
  const py = centerY + Math.sin(angle) * r;

  return (
    <>
      {/* Connector line from FF to chip */}
      <svg style={{
        position: 'absolute', left: 0, top: 0,
        width: '100%', height: '100%',
        pointerEvents: 'none', opacity: eased * 0.5,
      }}>
        <line x1={centerX} y1={centerY} x2={px} y2={py}
              stroke={FFV_GOLD_DK} strokeWidth="1" strokeDasharray="3 5"/>
      </svg>
      <div style={{
        position: 'absolute',
        left: px, top: py,
        transform: `translate(-50%, -50%) scale(${eased})`,
        opacity: eased,
        background: '#fff',
        border: `1px solid ${FFV_BORDER}`,
        borderRadius: 999,
        padding: '8px 14px 8px 8px',
        display: 'flex', alignItems: 'center', gap: 8,
        boxShadow: '0 10px 24px rgba(40,30,10,0.10)',
        fontFamily: FFV_SANS,
        whiteSpace: 'nowrap',
        willChange: 'transform, opacity',
      }}>
        <div style={{
          width: 22, height: 22, borderRadius: 7,
          background: FFV_GOLD_BG, color: FFV_GOLD_DK,
          display: 'grid', placeItems: 'center',
          fontSize: 11,
        }}>{glyph}</div>
        <span style={{ fontSize: 13, fontWeight: 600, color: FFV_INK }}>{label}</span>
      </div>
    </>
  );
}

// ── Scene 1: CHAOS ──────────────────────────────────────────────────────────
function FFVChaosScene() {
  const t = useTime();
  const { progress } = window.useSprite();

  // collapse trigger fires at the very end of scene 1 → handled separately
  // here we just float and jitter
  const tools = [
    { x: 200, y: 140, label: 'Gmail',     glyph: '@', color: '#1976D2', bg: '#E3ECF5', seed: 1 },
    { x: 920, y: 110, label: 'Mailchimp', glyph: '🐵', color: '#FFE01A', bg: '#FFFAE0', seed: 2 },
    { x: 1040, y: 320, label: 'Wix site', glyph: 'W', color: '#FF6B6B', bg: '#FFE6E5', seed: 3 },
    { x: 880, y: 520, label: 'Square',    glyph: '◼', color: FFV_INK, bg: FFV_CREAM_2, seed: 4 },
    { x: 240, y: 540, label: 'Slack DMs', glyph: '#', color: '#4A154B', bg: '#EFE0F0', seed: 5 },
    { x: 100, y: 340, label: 'Spreadsheet', glyph: 'XL', color: '#0F7B3C', bg: '#E1F0E5', seed: 6 },
    { x: 540, y: 90,  label: 'Voicemail',  glyph: '☎', color: FFV_RED, bg: FFV_RED_BG, seed: 7 },
  ];

  return (
    <>
      {/* Center: stressed phone */}
      <div style={{
        position: 'absolute', left: 640, top: 360,
        transform: `translate(-50%, -50%) rotate(${Math.sin(t * 4) * 3}deg)`,
        width: 200, height: 200,
      }}>
        <div style={{
          width: 160, height: 240, margin: '0 auto',
          background: FFV_INK, borderRadius: 28, padding: 7,
          boxShadow: '0 18px 40px rgba(0,0,0,0.25)',
          position: 'relative',
        }}>
          <div style={{
            background: FFV_CREAM_3, borderRadius: 22,
            width: '100%', height: '100%',
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            color: FFV_RED, fontFamily: FFV_SANS, fontWeight: 700,
          }}>
            <div style={{ fontSize: 38 }}>☎</div>
            <div style={{ fontSize: 13, marginTop: 6 }}>14 missed</div>
            <div style={{ fontSize: 10, color: FFV_INK_3, marginTop: 4 }}>since 6am</div>
          </div>
          {/* Pulsing ring */}
          <div style={{
            position: 'absolute', inset: -10,
            border: `3px solid ${FFV_RED}`, borderRadius: 36,
            opacity: 0.4 + Math.sin(t * 6) * 0.3,
          }}/>
        </div>
      </div>

      {tools.map((tool, i) => (
        <FFVToolCard key={i} {...tool} fadeOut={Math.max(0, progress - 0.85) * 6}/>
      ))}
    </>
  );
}

// ── Scene 2: PROBLEMS (3 indictments) ───────────────────────────────────────
function FFVProblemsScene() {
  const t = useTime();
  const localT = t - 4.5;

  const lines = [
    { text: '92% of calls', sub: 'go to voicemail.',     start: 0.0 },
    { text: '$30 / day',    sub: 'on ads. Zero funnel.', start: 0.95 },
    { text: 'Your site',    sub: 'invisible to ChatGPT.', start: 1.9 },
  ];

  return (
    <>
      {/* dimmer */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'rgba(27,24,20,0.04)',
      }}/>
      {lines.map((line, i) => {
        const lt = localT - line.start;
        if (lt < 0) return null;
        const opacity = window.clamp(lt * 4, 0, 1) * window.clamp(1 - (lt - 0.7) * 2, 0, 1);
        const y = 200 + i * 130;
        return (
          <div key={i} style={{
            position: 'absolute',
            left: '50%', top: y,
            transform: `translate(-50%, ${(1 - window.clamp(lt * 3, 0, 1)) * 14}px)`,
            opacity,
            display: 'flex', alignItems: 'baseline', gap: 18,
            fontFamily: FFV_SERIF, fontStyle: 'italic',
            color: FFV_INK, whiteSpace: 'nowrap',
          }}>
            <span style={{
              fontSize: 96, lineHeight: 1, color: FFV_RED,
              letterSpacing: '-0.01em',
            }}>{line.text}</span>
            <span style={{
              fontSize: 36, fontStyle: 'normal', fontFamily: FFV_SANS,
              fontWeight: 500, color: FFV_INK_2,
            }}>{line.sub}</span>
          </div>
        );
      })}
    </>
  );
}

// ── Scene 3: COLLAPSE — tools suck into the FF mark ─────────────────────────
function FFVCollapseScene() {
  const { progress } = window.useSprite();
  // We'll feed each tool a collapseTo target
  const target = { tx: 640 - 84, ty: 360 - 24, progress };

  const tools = [
    { x: 200, y: 140, label: 'Gmail',     glyph: '@', color: '#1976D2', bg: '#E3ECF5', seed: 1 },
    { x: 920, y: 110, label: 'Mailchimp', glyph: '🐵', color: '#FFE01A', bg: '#FFFAE0', seed: 2 },
    { x: 1040, y: 320, label: 'Wix site', glyph: 'W', color: '#FF6B6B', bg: '#FFE6E5', seed: 3 },
    { x: 880, y: 520, label: 'Square',    glyph: '◼', color: FFV_INK, bg: FFV_CREAM_2, seed: 4 },
    { x: 240, y: 540, label: 'Slack DMs', glyph: '#', color: '#4A154B', bg: '#EFE0F0', seed: 5 },
    { x: 100, y: 340, label: 'Spreadsheet', glyph: 'XL', color: '#0F7B3C', bg: '#E1F0E5', seed: 6 },
    { x: 540, y: 90,  label: 'Voicemail',  glyph: '☎', color: FFV_RED, bg: FFV_RED_BG, seed: 7 },
  ];

  // ring pulses on impact
  const ringPulse = progress > 0.6 ? (progress - 0.6) / 0.4 : 0;
  const monoScale = window.Easing.easeOutBack(window.clamp(progress * 1.4, 0, 1));

  return (
    <>
      {tools.map((tool, i) => (
        <FFVToolCard key={i} {...tool} collapseTo={target}/>
      ))}
      <div style={{
        position: 'absolute', left: 640, top: 360,
        transform: `translate(-50%, -50%) scale(${monoScale})`,
      }}>
        <FFVMonogram x={0} y={0} size={168} ringPulse={ringPulse}/>
      </div>
    </>
  );
}

// ── Scene 4: STACK — 7 services orbit out ───────────────────────────────────
function FFVStackScene() {
  const { progress } = window.useSprite();
  const cx = 640, cy = 360;

  // Settle the monogram slightly smaller as orbits appear
  const monoSize = ffvLerp(168, 130, window.clamp(progress * 3, 0, 1));

  const services = [
    { label: 'SEO + AEO Website', glyph: '🌐', angle: -Math.PI / 2 },
    { label: 'Industry CRM',      glyph: '▦', angle: -Math.PI / 2 + (Math.PI * 2) / 7 },
    { label: 'Ads + Funnel',      glyph: '▼', angle: -Math.PI / 2 + (Math.PI * 2 * 2) / 7 },
    { label: 'Social Autopilot',  glyph: '◉', angle: -Math.PI / 2 + (Math.PI * 2 * 3) / 7 },
    { label: 'AI Receptionist',   glyph: '☏', angle: -Math.PI / 2 + (Math.PI * 2 * 4) / 7 },
    { label: 'Comms Center',      glyph: '✉', angle: -Math.PI / 2 + (Math.PI * 2 * 5) / 7 },
    { label: 'Employee App',      glyph: '▢', angle: -Math.PI / 2 + (Math.PI * 2 * 6) / 7 },
  ];

  // Stagger each chip's appearance: scene runs 10.5 → 16s = 5.5s window
  // Each chip needs ~0.18s gap + 0.6s entry animation
  const sceneStart = 10.5;
  const chipGap = 0.18;

  return (
    <>
      <FFVMonogram x={cx} y={cy} size={monoSize}/>
      {services.map((s, i) => (
        <FFVServiceOrbit
          key={i}
          centerX={cx} centerY={cy}
          angle={s.angle}
          distance={240}
          label={s.label}
          glyph={s.glyph}
          appearAt={sceneStart + 0.4 + i * chipGap}
        />
      ))}
    </>
  );
}

// ── Scene 5: PROMISE ────────────────────────────────────────────────────────
function FFVPromiseScene() {
  const { localTime, duration } = window.useSprite();

  // headline entry
  const hOpacity = window.clamp(localTime / 0.5, 0, 1);
  const hY = (1 - window.Easing.easeOutCubic(window.clamp(localTime / 0.6, 0, 1))) * 18;

  // sub + CTA
  const subOpacity = window.clamp((localTime - 0.6) / 0.5, 0, 1);
  const ctaOpacity = window.clamp((localTime - 1.1) / 0.5, 0, 1);
  const ctaY = (1 - window.Easing.easeOutBack(window.clamp((localTime - 1.1) / 0.6, 0, 1))) * 14;

  return (
    <>
      <FFVWordmark x={640} y={180} width={240}/>
      <div style={{
        position: 'absolute', left: '50%', top: 250,
        transform: `translate(-50%, ${hY}px)`,
        opacity: hOpacity,
        fontFamily: FFV_SERIF, fontStyle: 'italic',
        fontSize: 96, lineHeight: 1, color: FFV_INK,
        textAlign: 'center',
        whiteSpace: 'nowrap',
        letterSpacing: '-0.015em',
      }}>
        One stack.
      </div>
      <div style={{
        position: 'absolute', left: '50%', top: 360,
        transform: 'translate(-50%, 0)',
        opacity: subOpacity,
        fontFamily: FFV_SERIF, fontStyle: 'italic',
        fontSize: 96, lineHeight: 1,
        textAlign: 'center',
        whiteSpace: 'nowrap',
        letterSpacing: '-0.015em',
      }}>
        <span style={{ color: FFV_INK }}>One team. </span>
        <span style={{ color: FFV_GOLD_DK }}>One price.</span>
      </div>

      <div style={{
        position: 'absolute', left: '50%', top: 510,
        transform: `translate(-50%, ${ctaY}px)`,
        opacity: ctaOpacity,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <div style={{
          background: FFV_INK, color: FFV_CREAM_3,
          padding: '16px 28px', borderRadius: 999,
          fontFamily: FFV_SANS, fontWeight: 600, fontSize: 18,
          boxShadow: '0 12px 24px rgba(0,0,0,0.18)',
        }}>
          Start free trial &nbsp;→
        </div>
        <div style={{
          fontFamily: FFV_SANS, fontSize: 14, color: FFV_INK_3,
        }}>
          fastfix.ai &nbsp;·&nbsp; 14-day free
        </div>
      </div>

      {/* tagline ribbon */}
      <div style={{
        position: 'absolute', left: '50%', top: 600,
        transform: 'translate(-50%, 0)',
        opacity: ctaOpacity * 0.85,
        fontFamily: FFV_SANS, fontSize: 13,
        color: FFV_INK_3, letterSpacing: '0.12em',
        textTransform: 'uppercase', fontWeight: 600,
      }}>
        Premium AI &nbsp;·&nbsp; Local business &nbsp;·&nbsp; Best price
      </div>
    </>
  );
}

// ── Caption overlay (timestamp updater for comments) ────────────────────────
function FFVTimestamp() {
  const t = useTime();
  React.useEffect(() => {
    const root = document.querySelector('[data-video-root]');
    if (root) root.setAttribute('data-screen-label', `t=${t.toFixed(1)}s`);
  }, [Math.floor(t)]);
  return null;
}

// ── Master Video ────────────────────────────────────────────────────────────
function RoofLinkerVideo() { // legacy name kept for compatibility
  return <FastFixVideo />;
}

function FastFixVideo() {
  return (
    <div data-video-root style={{ position: 'absolute', inset: 0 }}>
      <Stage
        width={1280} height={720} duration={20.5}
        background={FFV_CREAM}
        persistKey="ffv-hero"
      >
        <FFVTimestamp/>

        {/* Subtle ambient gold orb backdrop, very faint */}
        <div style={{
          position: 'absolute', left: '50%', top: '50%',
          width: 900, height: 900, borderRadius: '50%',
          background: `radial-gradient(circle at 50% 50%, ${FFV_GOLD_BG} 0%, ${FFV_CREAM} 60%)`,
          transform: 'translate(-50%, -50%)',
          opacity: 0.7,
        }}/>

        <Sprite start={0} end={4.6}>
          <FFVChaosScene/>
        </Sprite>

        <Sprite start={4.5} end={7.6}>
          <FFVProblemsScene/>
        </Sprite>

        <Sprite start={7.5} end={10.6}>
          <FFVCollapseScene/>
        </Sprite>

        <Sprite start={10.5} end={16.1}>
          <FFVStackScene/>
        </Sprite>

        <Sprite start={16} end={20.5}>
          <FFVPromiseScene/>
        </Sprite>
      </Stage>
    </div>
  );
}

Object.assign(window, { FastFixVideo, RoofLinkerVideo });
