import { interpolate } from 'remotion';
import { C } from '../lib/colors';
import { springIn, softSpring, clampLerp, rand } from '../lib/easings';

// Phase 3 (frames 255–366 global → localFrame 0..111): the server card pulls
// back / scales down and multiplies into a 3×2 grid of template cards.
//
// New beat in v5: as the hero card joins the grid, the lock icon next to its
// NOTION_API_KEY slot DETACHES and fades upward — the slot then reads
// `NOTION_API_KEY = ?`, communicating that the published template carries
// the recipe but not the secret value. A caption below the grid reinforces:
//   "templates carry code, not credentials."

const GRID_COLS = 3;
const GRID_ROWS = 2;
// Cards enlarged in v10 — the previous 340×180 grid felt cramped on a
// 1080p canvas. New 400×220 with 36 px gap spreads the library across
// more of the available width (now grid spans x 252–1668) so each
// template card reads at a glance.
const CARD_W = 400;
const CARD_H = 220;
const GAP = 36;

const CARDS = [
  { name: 'github-issues',  toolCount: 3, highlighted: false },
  { name: 'notion-search',  toolCount: 2, highlighted: true  }, // hero
  { name: 'slack-digest',   toolCount: 4, highlighted: false },
  { name: 'linear-tasks',   toolCount: 5, highlighted: false },
  { name: 'gmail-triage',   toolCount: 3, highlighted: true  },
  { name: 'jira-sprint',    toolCount: 6, highlighted: false },
];

// Timing inside Phase 3
const LOCK_DETACH_START = 36; // when hero is settled into the grid
const LOCK_DETACH_END = 56;
const SUB_CAPTION_START = 56;
const SUB_CAPTION_END = 70;
// New: "export source ↓" chip on the hero card. Pulses once around frame 110.
const EXPORT_CHIP_START = 95;
const EXPORT_CHIP_END = 145;

export function LibraryScene({ localFrame, fps }: { localFrame: number; fps: number }) {
  const captionIn = clampLerp(localFrame, 20, 36);
  const heroProgress = softSpring(localFrame, fps, 0, 30);
  const lockDetach = clampLerp(localFrame, LOCK_DETACH_START, LOCK_DETACH_END);
  const subCaptionIn = clampLerp(localFrame, SUB_CAPTION_START, SUB_CAPTION_END);
  // Export chip: rises in then pulses out.
  const exportIn = clampLerp(localFrame, EXPORT_CHIP_START, EXPORT_CHIP_START + 10);
  const exportOut = 1 - clampLerp(localFrame, EXPORT_CHIP_END - 10, EXPORT_CHIP_END);
  const exportOpacity = Math.min(exportIn, exportOut);
  // Pulse modulation:
  const exportPulse =
    exportOpacity > 0.1
      ? 0.6 + 0.4 * Math.sin(((localFrame - EXPORT_CHIP_START) / 16) * Math.PI * 2)
      : 0;

  const gridW = GRID_COLS * CARD_W + (GRID_COLS - 1) * GAP;
  const gridH = GRID_ROWS * CARD_H + (GRID_ROWS - 1) * GAP;
  const gridLeft = (1920 - gridW) / 2;
  const gridTop = (1080 - gridH) / 2 + 30;

  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      {/* Section caption */}
      <div
        style={{
          position: 'absolute',
          top: gridTop - 80,
          left: 0,
          right: 0,
          textAlign: 'center',
          fontFamily: 'ui-monospace, SF Mono, Menlo, monospace',
          fontSize: 16,
          letterSpacing: 5,
          textTransform: 'uppercase',
          color: C.fgSubtle,
          opacity: captionIn,
          transform: `translateY(${interpolate(captionIn, [0, 1], [10, 0])}px)`,
        }}
      >
        template library
      </div>

      {CARDS.map((card, i) => {
        const col = i % GRID_COLS;
        const row = Math.floor(i / GRID_COLS);
        const targetX = gridLeft + col * (CARD_W + GAP);
        const targetY = gridTop + row * (CARD_H + GAP);
        const isHero = i === 1;

        if (isHero) {
          const startW = 540;
          const startH = 240;
          const startX = (1920 - startW) / 2;
          const startY = (1080 - startH) / 2 + 90;
          const w = interpolate(heroProgress, [0, 1], [startW, CARD_W]);
          const h = interpolate(heroProgress, [0, 1], [startH, CARD_H]);
          const x = interpolate(heroProgress, [0, 1], [startX, targetX]);
          const y = interpolate(heroProgress, [0, 1], [startY, targetY]);
          return (
            <div
              key={i}
              style={{
                position: 'absolute',
                left: x,
                top: y,
                width: w,
                height: h,
              }}
            >
              <TemplateCardInner
                card={card}
                w={w}
                h={h}
                lockDetach={lockDetach}
                isHero
              />
            </div>
          );
        }

        // Sibling cards fade in staggered.
        const delay = 16 + i * 3;
        const sib = springIn(localFrame, fps, delay);
        const opacity = clampLerp(localFrame, delay, delay + 14);
        const scale = interpolate(sib, [0, 1], [0.92, 1]);
        const drift = (rand(i + 7) - 0.5) * 14;
        return (
          <div
            key={i}
            style={{
              position: 'absolute',
              left: targetX,
              top: targetY + drift * (1 - sib),
              width: CARD_W,
              height: CARD_H,
              opacity,
              transform: `scale(${scale})`,
              transformOrigin: 'center center',
            }}
          >
            <TemplateCardInner card={card} w={CARD_W} h={CARD_H} lockDetach={0} isHero={false} />
          </div>
        );
      })}

      {/* Export-source chip — floats above the hero card */}
      {exportOpacity > 0.02 && (() => {
        // Hero card position (col 1, row 0) — recompute here for clarity
        const heroX = gridLeft + 1 * (CARD_W + GAP);
        const heroY = gridTop + 0 * (CARD_H + GAP);
        return (
          <div
            style={{
              position: 'absolute',
              left: heroX + CARD_W / 2,
              top: heroY - 28,
              transform: `translate(-50%, -100%) scale(${0.9 + exportPulse * 0.1})`,
              opacity: exportOpacity,
              fontFamily: 'ui-monospace, SF Mono, Menlo, monospace',
              fontSize: 11,
              letterSpacing: 2,
              textTransform: 'uppercase',
              color: C.accent,
              backgroundColor: 'rgba(99,102,241,0.18)',
              border: `1px solid ${C.accent}`,
              borderRadius: 999,
              padding: '6px 12px',
              boxShadow: `0 0 ${10 + exportPulse * 14}px rgba(99,102,241,${0.30 + exportPulse * 0.20})`,
              whiteSpace: 'nowrap',
              display: 'flex',
              alignItems: 'center',
              gap: 6,
            }}
          >
            export source <span style={{ fontSize: 13 }}>↓</span>
          </div>
        );
      })()}

      {/* Sub-caption was pulled — the voice-over already says the same
          thing and the on-screen line read as "on-the-nose marketing".
          The detached lock + empty slot pill on the hero card carries
          the story visually now. */}
    </div>
  );
}

function TemplateCardInner({
  card,
  w,
  h,
  lockDetach,
  isHero,
}: {
  card: { name: string; toolCount: number; highlighted: boolean };
  w: number;
  h: number;
  lockDetach: number;
  isHero: boolean;
}) {
  const border = card.highlighted ? C.accent : C.border;
  const shadow = card.highlighted
    ? `0 0 0 3px ${C.accentGlow}, 0 14px 40px rgba(0,0,0,0.5)`
    : `0 8px 24px rgba(0,0,0,0.35)`;

  const padX = Math.max(18, w * 0.06);
  const padY = Math.max(16, h * 0.08);

  // Show slot row only on hero card — communicates the empty-key story.
  // The lock-detach animation: lock lifts up and fades, then "?" appears.
  const lockY = -lockDetach * 30;
  const lockOpacity = 1 - lockDetach;
  const questionOpacity = clampLerp(lockDetach, 0.5, 1);

  return (
    <div
      style={{
        width: '100%',
        height: '100%',
        backgroundColor: C.bgElevated,
        border: `1.5px solid ${border}`,
        borderRadius: 14,
        padding: `${padY}px ${padX}px`,
        boxShadow: shadow,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
        position: 'relative',
        overflow: 'visible',
      }}
    >
      {/* Top: title + indicator dot */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div
          style={{
            fontFamily: 'ui-monospace, SF Mono, Menlo, monospace',
            fontSize: w > 380 ? 18 : 15,
            color: C.fg,
            letterSpacing: 0.1,
          }}
        >
          {card.name}
        </div>
        <div
          style={{
            width: 7,
            height: 7,
            borderRadius: 4,
            backgroundColor: card.highlighted ? C.success : C.fgSubtle,
            opacity: card.highlighted ? 1 : 0.5,
            boxShadow: card.highlighted ? `0 0 8px ${C.success}` : 'none',
          }}
        />
      </div>

      {/* Middle: either tool bars (default) OR the secret slot pill (hero) */}
      {isHero ? (
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 8,
            padding: '5px 10px',
            backgroundColor: 'rgba(99,102,241,0.08)',
            border: `1px solid ${C.border}`,
            borderRadius: 999,
            alignSelf: 'flex-start',
            fontFamily: 'ui-monospace, SF Mono, Menlo, monospace',
            fontSize: w > 380 ? 12 : 10,
            color: C.fgMuted,
            position: 'relative',
          }}
        >
          {/* Lock icon — detaches upward over the lockDetach window */}
          <span
            style={{
              display: 'inline-flex',
              transform: `translateY(${lockY}px)`,
              opacity: lockOpacity,
            }}
          >
            <MiniLockIcon size={w > 380 ? 11 : 9} />
          </span>
          {/* Question-mark placeholder appears as lock leaves */}
          <span
            style={{
              position: 'absolute',
              left: 10,
              top: '50%',
              transform: 'translateY(-50%)',
              color: C.fgSubtle,
              opacity: questionOpacity,
              fontSize: w > 380 ? 11 : 9,
            }}
          >
            ?
          </span>
          <span style={{ marginLeft: 4 }}>NOTION_API_KEY</span>
          <span style={{ color: C.fgSubtle }}>=</span>
          <span style={{ color: lockDetach > 0.5 ? C.fgSubtle : C.accent }}>
            {lockDetach > 0.5 ? '?' : '•••'}
          </span>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {Array.from({ length: Math.min(3, card.toolCount) }).map((_, j) => (
            <div
              key={j}
              style={{
                height: 7,
                borderRadius: 3.5,
                backgroundColor: C.bgSubtle,
                width: `${[88, 64, 76][j]}%`,
                border: `1px solid ${C.border}`,
              }}
            />
          ))}
        </div>
      )}

      {/* Bottom: tool count + status */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          fontFamily: 'ui-monospace, SF Mono, Menlo, monospace',
          fontSize: w > 380 ? 13 : 11,
          color: C.fgSubtle,
          letterSpacing: 0.5,
        }}
      >
        <span>{card.toolCount} tools</span>
        <span style={{ color: card.highlighted ? C.accent : C.fgSubtle }}>
          {card.highlighted ? '★ featured' : 'template'}
        </span>
      </div>
    </div>
  );
}

function MiniLockIcon({ size = 11 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M 5 8 L 5 6 A 3 3 0 0 1 11 6 L 11 8" stroke={C.accent} strokeWidth={1.4} fill="none" />
      <rect x="3.5" y="7.5" width="9" height="7" rx="1.5" fill="rgba(99,102,241,0.20)" stroke={C.accent} strokeWidth={1.4} />
      <circle cx="8" cy="11" r="1" fill={C.accent} />
    </svg>
  );
}
