// video-scenes-3.jsx
// Equiti+ explainer video — dashboard scene + impact + close. LANDSCAPE 1920×1080.

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 6 — AGENT DASHBOARD  (52.2 – 80.2s — 28s tour)
// Dashboard shown inside a macOS browser window (landscape, wide).
// Slow pan + zoom between panel regions. Focus ring snaps instantly, no trailing.
// ═══════════════════════════════════════════════════════════════════════════

const DASH_W = 1920, DASH_H = 1815;

const PANELS = {
  overview: { x: 0,    y: 0,    w: 1920, h: 1815, label: 'The agent cockpit',
              detail: 'One operating picture — health, queue, context, conversation.',
              color: '#00B4B0' },
  health:   { x: 284,  y: 145,  w: 1108, h: 420,  label: 'Platform health',
              detail: 'Sees degraded services before clients ask.',
              color: '#F59E0B' },
  ai:       { x: 1412, y: 145,  w: 484,  h: 420,  label: 'AI performance',
              detail: '58% deflected · 4.2s median resolve.',
              color: '#00B4B0' },
  queue:    { x: 284,  y: 585,  w: 605,  h: 618,  label: 'Escalation queue',
              detail: 'Ranked by risk — Ahmed\u2019s margin jumps the line.',
              color: '#EF4444' },
  context:  { x: 909,  y: 585,  w: 484,  h: 618,  label: 'Client context',
              detail: 'Everything the AI already learned — zero re-asking.',
              color: '#22C55E' },
  convo:    { x: 284,  y: 1223, w: 1108, h: 568,  label: 'Live conversation',
              detail: 'Full transcript + tool calls handed to the human agent.',
              color: '#2E90FA' },
};

// Tour — 28 second tour (scene-local times). Convo extended to fill remainder
// since the final "overview again" recap was removed.
const TOUR = [
  { start: 0.0,  end: 3.5,  target: 'overview' },
  { start: 3.5,  end: 7.5,  target: 'health' },
  { start: 7.5,  end: 11.5, target: 'ai' },
  { start: 11.5, end: 15.5, target: 'queue' },
  { start: 15.5, end: 19.5, target: 'context' },
  { start: 19.5, end: 27.8, target: 'convo' },
];

// Smooth transition between panels — no snap, no double-settle.
const TOUR_TRANS = 0.7;

function currentTourTarget(localT) {
  for (let i = 0; i < TOUR.length; i++) {
    const seg = TOUR[i];
    if (localT >= seg.start && localT < seg.end) {
      const next = TOUR[i + 1];
      const segDur = seg.end - seg.start;
      const tInSeg = localT - seg.start;
      if (next && tInSeg > segDur - TOUR_TRANS) {
        const raw = clamp((tInSeg - (segDur - TOUR_TRANS)) / TOUR_TRANS, 0, 1);
        const p = Easing.easeInOutCubic(raw);
        return { from: PANELS[seg.target], to: PANELS[next.target], p, rawP: raw, idx: i, tInSeg, segDur };
      }
      return { from: PANELS[seg.target], to: PANELS[seg.target], p: 0, rawP: 0, idx: i, tInSeg, segDur };
    }
  }
  const last = TOUR[TOUR.length - 1];
  return { from: PANELS[last.target], to: PANELS[last.target], p: 0, rawP: 0, idx: TOUR.length - 1, tInSeg: 0, segDur: 0 };
}

function lerp(a, b, t) { return a + (b - a) * t; }
function lerpRect(a, b, p) {
  return {
    x: lerp(a.x, b.x, p),
    y: lerp(a.y, b.y, p),
    w: lerp(a.w, b.w, p),
    h: lerp(a.h, b.h, p),
  };
}

function DesktopBg() {
  // Screen-Studio-style mockup desktop: colorful gradient wallpaper + macOS menu bar.
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
      {/* Base wallpaper */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(135deg, #0B1733 0%, #1A2A5E 35%, #0D4C5F 70%, #0B3746 100%)',
      }} />
      {/* Atmospheric blobs */}
      <div style={{
        position: 'absolute', left: '-8%', top: '-15%',
        width: 1100, height: 1100, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(0,180,176,0.42), transparent 62%)',
        filter: 'blur(70px)',
      }} />
      <div style={{
        position: 'absolute', right: '-10%', bottom: '-20%',
        width: 1200, height: 1200, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(124,58,237,0.38), transparent 62%)',
        filter: 'blur(90px)',
      }} />
      <div style={{
        position: 'absolute', right: '25%', top: '30%',
        width: 600, height: 600, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(236,72,153,0.18), transparent 60%)',
        filter: 'blur(110px)',
      }} />
      {/* Subtle vignette */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at center, transparent 55%, rgba(0,0,0,0.45) 100%)',
      }} />

      {/* macOS menu bar */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 28,
        background: 'rgba(16,20,32,0.55)',
        backdropFilter: 'blur(40px)',
        WebkitBackdropFilter: 'blur(40px)',
        borderBottom: '1px solid rgba(255,255,255,0.06)',
        display: 'flex', alignItems: 'center', padding: '0 18px',
        fontFamily: FONTS.body, fontSize: 13, color: 'rgba(255,255,255,0.88)',
        gap: 22, zIndex: 2,
      }}>
        <span style={{
          display: 'inline-block', width: 14, height: 14,
          background: '#fff', borderRadius: '50%', opacity: 0.95,
        }} />
        <span style={{ fontWeight: 700 }}>Chrome</span>
        <span style={{ opacity: 0.78 }}>File</span>
        <span style={{ opacity: 0.78 }}>Edit</span>
        <span style={{ opacity: 0.78 }}>View</span>
        <span style={{ opacity: 0.78 }}>Window</span>
        <span style={{ opacity: 0.78 }}>Help</span>
        <span style={{ marginLeft: 'auto', opacity: 0.9, fontSize: 12,
          display: 'flex', gap: 14, alignItems: 'center' }}>
          <span>⌘</span>
          <span>◐</span>
          <span>Tue 14 Apr · 9:41 AM</span>
        </span>
      </div>
    </div>
  );
}

function Scene6_Dashboard() {
  const tourEnabled = typeof window !== 'undefined' ? window.__dashTourEnabled !== false : true;

  return (
    <Sprite start={52.2} end={80.2}>
      <VerticalSlide>
        <SceneBg color={BRAND.bg}>
          <DesktopBg />
        </SceneBg>

        {/* Section heading — positioned above the desktop wallpaper's menu bar zone */}
        <Sprite start={52.2} end={80.2}>
          <FadeText x={100} y={55} size={18} weight={700}
            font={FONTS.mono} color={BRAND.teal}
            letterSpacing="0.18em" style={{ textTransform: 'uppercase',
              textShadow: '0 2px 10px rgba(0,0,0,0.55)' }}>
            And when a human takes over
          </FadeText>
        </Sprite>
        <Sprite start={52.4} end={80.2}>
          <FadeText x={100} y={93} width={1720} size={44} weight={700}
            font={FONTS.display} color={BRAND.white}
            letterSpacing="-0.02em" lineHeight={1.1}
            style={{ textShadow: '0 4px 20px rgba(0,0,0,0.6)' }}>
            The agent cockpit — <span style={{ color: BRAND.teal }}>one operating picture.</span>
          </FadeText>
        </Sprite>

        <DashboardTour start={52.2} tourEnabled={tourEnabled} />
      </VerticalSlide>
    </Sprite>
  );
}

function DashboardTour({ start, tourEnabled }) {
  const t = useTime();
  const localT = t - start;

  const entryDur = 0.7;
  const sceneDur = 28;
  const exitStart = sceneDur - 0.5;
  const entryT = Easing.easeOutCubic(clamp(localT / entryDur, 0, 1));
  let opacity = clamp(localT / 0.4, 0, 1);
  if (localT > exitStart) {
    opacity *= 1 - clamp((localT - exitStart) / 0.5, 0, 1);
  }

  const tourT = Math.max(0, localT - 0.3);
  const tourInfo = tourEnabled
    ? currentTourTarget(tourT)
    : { from: PANELS.overview, to: PANELS.overview, p: 0, rawP: 0, idx: 0, tInSeg: 0, segDur: 0 };
  const { from, to, p, rawP, idx, tInSeg } = tourInfo;
  const target = lerpRect(from, to, p);

  // Landscape browser window geometry on 1920×1080 stage
  const winX = 120, winY = 170, winW = 1680, winH = 780;
  const chromeH = 48;
  const vpW = winW, vpH = winH - chromeH;

  const scaleX = vpW / target.w;
  const scaleY = vpH / target.h;
  const scale = Math.min(scaleX, scaleY) * 0.94;

  const scaledW = target.w * scale;
  const scaledH = target.h * scale;
  const centerOffsetX = (vpW - scaledW) / 2;
  const centerOffsetY = (vpH - scaledH) / 2;
  const tx = -target.x * scale + centerOffsetX;
  const ty = -target.y * scale + centerOffsetY;

  const activeTarget = p > 0.5 ? to : from;
  const onOverview = activeTarget === PANELS.overview;

  // Subtle motion blur during the pan — no arrival pulse, no snap.
  const velocity = (rawP > 0 && rawP < 1) ? Math.sin(rawP * Math.PI) : 0;
  const contentBlur = velocity * 1.2;
  const ringBlur = velocity * 2.5;

  return (
    <>
      {/* macOS browser window */}
      <div style={{
        position: 'absolute',
        left: winX, top: winY, width: winW, height: winH,
        borderRadius: 14,
        overflow: 'hidden',
        background: '#1C1F26',
        boxShadow: '0 60px 140px -30px rgba(0,0,0,0.9), 0 0 0 1px rgba(255,255,255,0.06)',
        opacity,
        transform: `scale(${0.97 + 0.03 * entryT})`,
        transformOrigin: 'center 40%',
      }}>
        {/* Chrome bar */}
        <div style={{
          height: chromeH,
          background: '#1C1F26',
          display: 'flex', alignItems: 'center', gap: 14,
          padding: '0 18px',
          borderBottom: '1px solid rgba(255,255,255,0.04)',
        }}>
          <div style={{ display: 'flex', gap: 8 }}>
            <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#FF5F57' }} />
            <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#FEBC2E' }} />
            <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#28C840' }} />
          </div>
          <div style={{
            flex: 1,
            margin: '0 20px',
            height: 28,
            borderRadius: 8,
            background: '#0B0F17',
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '0 14px',
            fontFamily: FONTS.body, fontSize: 12,
            color: 'rgba(255,255,255,0.6)',
            border: '1px solid rgba(255,255,255,0.05)',
          }}>
            <span style={{ color: BRAND.success, fontSize: 11 }}>●</span>
            <span style={{ letterSpacing: '0.02em' }}>agent.equiti.plus</span>
          </div>
          <div style={{
            fontFamily: FONTS.mono, fontSize: 11, fontWeight: 700,
            color: BRAND.teal, letterSpacing: '0.14em',
            padding: '4px 10px',
            background: 'rgba(0,180,176,0.12)',
            borderRadius: 6,
            textTransform: 'uppercase',
          }}>
            Internal · Live
          </div>
        </div>

        {/* Dashboard viewport */}
        <div style={{
          position: 'relative',
          width: vpW, height: vpH,
          overflow: 'hidden',
          background: '#070B13',
        }}>
          <div style={{
            position: 'absolute',
            top: 0, left: 0,
            width: DASH_W, height: DASH_H,
            transform: `translate(${tx}px, ${ty}px) scale(${scale})`,
            transformOrigin: 'top left',
            filter: contentBlur > 0.05 ? `blur(${contentBlur.toFixed(2)}px)` : undefined,
            willChange: 'transform, filter',
          }}>
            <iframe src="dashboard.html" style={{
              position: 'absolute',
              top: 0, left: 0,
              width: DASH_W, height: DASH_H,
              border: 0,
              pointerEvents: 'none',
            }} scrolling="no" />
          </div>

          {/* Focus ring — traces the camera; hidden only while overview is active */}
          {tourEnabled && !onOverview && (
            <FocusRing
              x={tx + target.x * scale}
              y={ty + target.y * scale}
              w={target.w * scale}
              h={target.h * scale}
              color={activeTarget.color}
              blur={ringBlur}
            />
          )}
        </div>
      </div>

      {/* Floating caption card — below the browser window */}
      {tourEnabled && (
        <TourCaption idx={idx} target={activeTarget} opacity={opacity} />
      )}
    </>
  );
}

function FocusRing({ x, y, w, h, color, blur = 0, scale = 1 }) {
  return (
    <div style={{
      position: 'absolute',
      left: x - 6, top: y - 6,
      width: w + 12, height: h + 12,
      borderRadius: 14,
      border: `2px solid ${color}`,
      boxShadow: `0 0 0 6px ${color}22, 0 0 40px -2px ${color}, inset 0 0 40px -12px ${color}`,
      pointerEvents: 'none',
      transform: scale !== 1 ? `scale(${scale})` : undefined,
      transformOrigin: 'center center',
      filter: blur > 0.1 ? `blur(${blur.toFixed(2)}px)` : undefined,
      willChange: 'transform, filter',
    }} />
  );
}

function TourCaption({ idx, target, opacity }) {
  return (
    <div key={idx} style={{
      position: 'absolute',
      left: 120, top: 980,
      width: 1680,
      display: 'flex', alignItems: 'stretch', gap: 0,
      background: 'rgba(12,17,27,0.92)',
      backdropFilter: 'blur(20px)',
      border: `1px solid rgba(255,255,255,0.08)`,
      borderRadius: 14,
      animation: 'captionIn 0.5s ease-out',
      boxShadow: `0 20px 60px -15px rgba(0,0,0,0.8)`,
      overflow: 'hidden',
      opacity: opacity,
      height: 76,
    }}>
      <style>{`
        @keyframes captionIn {
          from { opacity: 0; transform: translateY(12px); }
          to { opacity: 1; transform: translateY(0); }
        }
      `}</style>
      <div style={{ width: 5, background: target.color }} />
      <div style={{
        padding: '14px 20px',
        display: 'flex', alignItems: 'center', gap: 14,
        borderRight: '1px solid rgba(255,255,255,0.06)',
      }}>
        <div style={{
          width: 40, height: 40, borderRadius: 10,
          background: `${target.color}22`,
          color: target.color,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: FONTS.display, fontSize: 18, fontWeight: 800,
          fontVariantNumeric: 'tabular-nums',
        }}>
          {String(idx + 1).padStart(2, '0')}
        </div>
      </div>
      <div style={{
        flex: 1,
        padding: '14px 22px',
        display: 'flex', flexDirection: 'column', justifyContent: 'center',
      }}>
        <div style={{
          fontFamily: FONTS.display, fontSize: 22, fontWeight: 700,
          color: BRAND.white, letterSpacing: '-0.02em',
          lineHeight: 1.1, marginBottom: 3,
        }}>{target.label}</div>
        <div style={{
          fontFamily: FONTS.body, fontSize: 14, fontWeight: 400,
          color: BRAND.textMuted, lineHeight: 1.4,
        }}>{target.detail}</div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 7 — IMPACT  (80.2 – 89.2s)  — 4 tiles in a horizontal row
// ═══════════════════════════════════════════════════════════════════════════
function Scene7_Impact() {
  return (
    <Sprite start={80.2} end={89.2}>
      <VerticalSlide>
        <SceneBg color={BRAND.bg}>
          <TealGlow x={50} y={55} size={1200} />
        </SceneBg>

        <Sprite start={80.3} end={89.2}>
          <FadeText x={0} y={110} width={1920} size={22} weight={700}
            font={FONTS.body} color={BRAND.teal} align="center"
            letterSpacing="0.22em" style={{ textTransform: 'uppercase' }}>
            The impact
          </FadeText>
        </Sprite>

        <Sprite start={80.5} end={89.2}>
          <FadeText x={0} y={160} width={1920} size={58} weight={700}
            font={FONTS.display} color={BRAND.white} align="center"
            letterSpacing="-0.02em" lineHeight={1.12}>
            Cheaper to run. Faster for clients. <span style={{ color: BRAND.teal }}>Harder to churn.</span>
          </FadeText>
        </Sprite>

        {/* 4 tiles in a row. w=360, gap=40: 100, 540, 980, 1420 */}
        <Sprite start={81.3} end={88.8}>
          <ImpactTile x={100}  y={420} big="55" suffix="%"  label="tickets auto-resolved" sub="across seven core flows"    dir="up" good />
        </Sprite>
        <Sprite start={81.7} end={88.8}>
          <ImpactTile x={540}  y={420} big="$2.40"          label="cost per contact"      sub="vs. $11.80 Tier-1 baseline" dir="down" good />
        </Sprite>
        <Sprite start={82.1} end={88.8}>
          <ImpactTile x={980}  y={420} big="4"  suffix="s"  label="median first answer"   sub="down from 14 minutes"       dir="down" good />
        </Sprite>
        <Sprite start={82.5} end={88.8}>
          <ImpactTile x={1420} y={420} big="+18" suffix="%" label="retention lift"        sub="driven by proactive triggers" dir="up" good />
        </Sprite>

        {/* Closing kicker */}
        <Sprite start={84.0} end={89.2}>
          <FadeText x={0} y={860} width={1920} size={44} weight={700}
            font={FONTS.display} color={BRAND.white} align="center"
            letterSpacing="-0.02em" lineHeight={1.2}>
            Ready for pilot. <span style={{ color: BRAND.teal }}>Built in 48 hours.</span>
          </FadeText>
        </Sprite>
      </VerticalSlide>
    </Sprite>
  );
}

function ImpactTile({ x, y, big, suffix, label, sub, dir = 'up', good = true }) {
  const { localTime, duration } = useSprite();
  const entry = 0.5, exit = 0.4;
  const exitStart = Math.max(0, duration - exit);
  let opacity = 1, ty = 0;
  if (localTime < entry) {
    const t = Easing.easeOutCubic(clamp(localTime / entry, 0, 1));
    opacity = t;
    ty = (1 - t) * 40;
  } else if (localTime > exitStart) {
    const t = Easing.easeInCubic(clamp((localTime - exitStart) / exit, 0, 1));
    opacity = 1 - t;
  }
  const arrowColor = good ? BRAND.success : BRAND.error;
  const arrowRot = dir === 'up' ? -45 : 135; // ↗ for up, ↘ for down
  // Arrow draw-in
  const arrT = Easing.easeOutBack(clamp((localTime - 0.25) / 0.45, 0, 1));
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      width: 360, height: 340, padding: '32px 28px',
      background: 'rgba(255,255,255,0.04)',
      border: `1px solid ${BRAND.border}`,
      borderRadius: 20,
      opacity,
      transform: `translateY(${ty}px)`,
      boxSizing: 'border-box',
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* Directional arrow — top right */}
      <div style={{
        position: 'absolute', top: 22, right: 22,
        width: 52, height: 52, borderRadius: 14,
        background: `${arrowColor}1A`,
        border: `1px solid ${arrowColor}55`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: arrowColor,
        opacity: clamp((localTime - 0.25) / 0.3, 0, 1),
        transform: `scale(${0.6 + 0.4 * arrT})`,
        boxShadow: `0 0 24px -6px ${arrowColor}88`,
      }}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none"
          style={{ transform: `rotate(${arrowRot}deg)` }}>
          <path d="M5 12h14M13 5l7 7-7 7" stroke={arrowColor}
            strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </div>

      {/* Big number — white */}
      <div style={{
        fontFamily: FONTS.display, fontWeight: 800,
        fontSize: big.length > 3 ? 82 : 116,
        color: BRAND.white,
        lineHeight: 1,
        letterSpacing: '-0.04em',
        marginTop: 'auto', marginBottom: 18,
        fontVariantNumeric: 'tabular-nums',
        display: 'flex', alignItems: 'baseline', gap: 2,
      }}>
        {big}{suffix && <span style={{ color: BRAND.textMuted, fontSize: 44 }}>{suffix}</span>}
      </div>
      <div style={{
        fontFamily: FONTS.body, fontSize: 19, fontWeight: 600,
        color: BRAND.white, marginBottom: 6,
      }}>{label}</div>
      <div style={{
        fontFamily: FONTS.body, fontSize: 14, color: BRAND.textDim, lineHeight: 1.4,
      }}>{sub}</div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 8 — CLOSING  (89 – 96s)
// ═══════════════════════════════════════════════════════════════════════════
function Scene8_Close() {
  return (
    <Sprite start={89.0} end={96.0}>
      <VerticalSlide>
        <SceneBg color={BRAND.bg}>
          <GridBg opacity={0.04} size={120} />
          <TealGlow x={50} y={50} size={1200} />
        </SceneBg>

        {/* Eyebrow */}
        <Sprite start={89.2} end={96.0}>
          <FadeText x={0} y={360} width={1920} size={22} weight={700}
            font={FONTS.body} align="center" color={BRAND.teal}
            letterSpacing="0.22em" style={{ textTransform: 'uppercase' }}>
            The support layer for trading
          </FadeText>
        </Sprite>

        {/* Logo reveal — matches Scene 1 centering on 1920 stage */}
        <Sprite start={89.5} end={96.0}>
          <EquitiLogo x={658} y={440} width={600} />
        </Sprite>

        {/* Sign-off */}
        <Sprite start={91.0} end={96.0}>
          <FadeText x={0} y={680} width={1920} size={34} weight={500}
            font={FONTS.body} align="center" color={BRAND.textMuted}
            letterSpacing="0.06em">
            Thank you — let's ship it.
          </FadeText>
        </Sprite>

        {/* Hackathon mark */}
        <Sprite start={92.2} end={96.0}>
          <FadeText x={0} y={1000} width={1920} size={18} weight={600}
            font={FONTS.body} align="center" color={BRAND.textDim}
            letterSpacing="0.24em" style={{ textTransform: 'uppercase' }}>
            Equiti+ · hackathon 2026
          </FadeText>
        </Sprite>
      </VerticalSlide>
    </Sprite>
  );
}

Object.assign(window, {
  Scene6_Dashboard, Scene7_Impact, Scene8_Close,
  DesktopBg, DashboardTour, FocusRing, TourCaption, ImpactTile,
});
