// Reusable video primitives extending the Huggie wireframe vocabulary.
// All sized for a 1920x1080 stage.

const V = {
  ink:  '#1a1a1a',
  ink2: '#4a4a4a',
  ink3: '#8a8a8a',
  paper: '#fafaf7',
  paper2: '#f3f1ea',
  accent: '#ff6b4a',
  accent2: '#ffd6b8',
  green: '#15a36a',
  red: '#c0392b',
  dark: '#1a1a1a',
};

const fontHand  = "'Kalam', cursive";
const fontMono  = "'JetBrains Mono', ui-monospace, monospace";
const fontHead  = "'Space Grotesk', 'Inter', system-ui, sans-serif";
// Brand fonts — match the live huggie.ai website (app/layout.tsx):
//   font-brand    → Fredoka  (the "huggie" wordmark)
//   font-display  → Cormorant Garamond  (italic editorial accent)
const fontBrand = "'Fredoka', 'Nunito', system-ui, sans-serif";
const fontSerif = "'Cormorant Garamond', 'Cormorant', Georgia, serif";

// ── Big phone shell (1080-class) ─────────────────────────────
function VPhone({ children, width = 440, height = 900, dark = false, status = '9:41', style }) {
  const bg = dark ? V.dark : V.paper;
  const ink = dark ? V.paper : V.ink;
  return (
    <div style={{
      width, height,
      background: bg,
      border: `3px solid ${V.ink}`,
      borderRadius: 56,
      boxShadow: '0 30px 60px rgba(20,15,5,0.18), 8px 12px 0 rgba(0,0,0,0.06)',
      position: 'relative',
      overflow: 'hidden',
      fontFamily: fontHand,
      color: ink,
      ...style,
    }}>
      {/* notch */}
      <div style={{
        position: 'absolute', top: 14, left: '50%', transform: 'translateX(-50%)',
        width: 130, height: 28, background: bg,
        border: `2px solid ${ink}`, borderTop: 'none',
        borderRadius: '0 0 22px 22px', zIndex: 6,
      }} />
      {/* status bar */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '14px 36px 0', fontSize: 17, fontFamily: fontMono, color: ink, opacity: 0.75,
        position: 'relative', zIndex: 2,
      }}>
        <span>{status}</span>
        <span>▮▮▮ ▮</span>
      </div>
      {/* content area */}
      <div style={{ position: 'absolute', inset: '50px 0 34px 0' }}>
        {children}
      </div>
      {/* home indicator */}
      <div style={{
        position: 'absolute', bottom: 12, left: '50%', transform: 'translateX(-50%)',
        width: 140, height: 5, background: ink, opacity: 0.45, borderRadius: 4,
      }} />
    </div>
  );
}

// ── Big avatar (orange peach) ─────────────────────────────
function VAvatar({ size = 140, label, color, ring, style }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: color || V.accent2,
      border: `3px solid ${V.ink}`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: fontHand, fontWeight: 700, fontSize: size * 0.42,
      color: V.ink, flexShrink: 0,
      boxShadow: ring ? `0 0 0 8px ${V.paper2}, 0 0 0 11px ${V.accent}` : 'none',
      ...style,
    }}>{label}</div>
  );
}

// ── Lang chip ─────────────────────────────
function VLang({ code, color, size = 48, style }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: color || V.accent2,
      border: `2px solid ${V.ink}`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: fontMono, fontSize: size * 0.36, fontWeight: 700, color: V.ink,
      flexShrink: 0,
      ...style,
    }}>{code}</div>
  );
}

// ── Hand-drawn underline ─────────────────────────────
function VUnderline({ w = 200, color = V.accent, thick = 5, style }) {
  return (
    <svg width={w} height={14} style={{ display: 'block', ...style }}>
      <path d={`M 3 8 Q ${w/3} 14, ${w/2} 7 T ${w-3} 8`}
            stroke={color} strokeWidth={thick} fill="none" strokeLinecap="round" />
    </svg>
  );
}

// ── Live waveform — animates with localTime ─────────────────────────────
function VWaveform({ width = 360, height = 70, color = V.accent, bars = 28, time = 0, intensity = 1, style }) {
  const arr = Array.from({ length: bars }, (_, i) => i);
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 4,
      width, height, ...style,
    }}>
      {arr.map(i => {
        const phase = i * 0.4 + time * 6;
        const base = 0.35 + 0.65 * Math.abs(Math.sin(phase) * Math.cos(phase * 0.3 + i));
        const h = Math.max(6, base * height * intensity);
        return (
          <div key={i} style={{
            flex: 1, height: h,
            background: color, borderRadius: 4,
            transition: 'height 60ms linear',
          }} />
        );
      })}
    </div>
  );
}

// ── Caption bubble (Huggie call card style) ─────────────────────────────
function VCaption({ children, original, who, lang, time = 0, progress = 1, width = 540, accent, dark, style }) {
  // typewriter feel: clip translated text
  const txt = typeof children === 'string' ? children : '';
  const clipChars = Math.max(0, Math.floor(progress * txt.length));
  const shown = txt ? txt.slice(0, clipChars) : children;

  return (
    <div style={{
      width,
      background: dark ? 'rgba(20,20,20,0.85)' : V.paper,
      border: `2.5px solid ${dark ? 'rgba(255,255,255,0.4)' : V.ink}`,
      borderRadius: 22,
      padding: '18px 22px',
      fontFamily: fontHand,
      color: dark ? '#fff' : V.ink,
      boxShadow: dark ? 'none' : '4px 6px 0 rgba(0,0,0,0.08)',
      ...style,
    }}>
      {who && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6,
          fontFamily: fontMono, fontSize: 13, letterSpacing: 1.2,
          color: dark ? 'rgba(255,255,255,0.7)' : V.ink3,
        }}>
          <span style={{ width: 9, height: 9, borderRadius: 5, background: V.accent }} />
          {who} · LIVE {lang || ''}
        </div>
      )}
      <div style={{ fontSize: 30, fontWeight: 700, lineHeight: 1.25 }}>
        {shown}
        {clipChars < txt.length && txt.length > 0 && (
          <span style={{ opacity: 0.55, animation: 'vBlink 0.6s steps(2) infinite' }}>▍</span>
        )}
      </div>
      {original && (
        <div style={{
          marginTop: 8,
          fontFamily: fontMono, fontSize: 18, fontStyle: 'italic',
          color: dark ? V.accent2 : V.ink3, opacity: 0.85,
        }}>
          {original}
        </div>
      )}
    </div>
  );
}

// ── Latency pill ─────────────────────────────
function VLatency({ ms = 400, time = 0, style }) {
  // tiny live jitter
  const ticking = (ms + Math.floor(Math.sin(time * 5) * 30)) / 1000;
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      padding: '10px 18px',
      border: `2px solid ${V.ink}`,
      borderRadius: 999,
      background: V.paper,
      fontFamily: fontMono, fontSize: 18, fontWeight: 700, color: V.ink,
      boxShadow: '3px 4px 0 rgba(0,0,0,0.08)',
      ...style,
    }}>
      <span style={{
        width: 12, height: 12, borderRadius: 6, background: V.green,
        boxShadow: `0 0 0 0 ${V.green}`,
        animation: 'vPulseDot 1.2s ease-out infinite',
      }} />
      <span style={{ fontVariantNumeric: 'tabular-nums' }}>{ticking.toFixed(2)}s</span>
      <span style={{ color: V.ink3, fontSize: 14 }}>latency</span>
    </div>
  );
}

// ── Big hand title (bold modern sans + handwriting accent) ─────────────────────────────
function VTitle({ text, x = '50%', y = '50%', size = 120, color = V.ink, weight = 700, font = fontHead, align = 'center', style }) {
  const tx = align === 'center' ? '-50%' : align === 'right' ? '-100%' : '0';
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      transform: `translate(${tx}, -50%)`,
      fontFamily: font, fontSize: size, fontWeight: weight, color,
      letterSpacing: '-0.03em', lineHeight: 1.0, whiteSpace: 'pre',
      ...style,
    }}>{text}</div>
  );
}

// ── Subtle paper texture overlay ─────────────────────────────
function VPaperTexture() {
  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none', opacity: 0.4,
      backgroundImage: `radial-gradient(circle at 30% 20%, rgba(255,107,74,0.04), transparent 50%),
                        radial-gradient(circle at 70% 80%, rgba(255,214,184,0.08), transparent 55%)`,
    }} />
  );
}

// ── Wave packet morphing between two languages (single hero element) ─────────────────────────────
function VLangSwap({ from = 'JP', to = 'EN', progress = 0, x = 0, y = 0 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      display: 'flex', alignItems: 'center', gap: 18,
    }}>
      <VLang code={from} color={V.accent2} size={64} />
      <svg width="80" height="32" viewBox="0 0 80 32" style={{ flexShrink: 0 }}>
        <path d="M 5 16 Q 20 4, 40 16 T 75 16"
              stroke={V.accent} strokeWidth="3" fill="none" strokeLinecap="round" strokeDasharray="100" strokeDashoffset={100 - progress * 100} />
        <path d="M 65 8 L 75 16 L 65 24"
              stroke={V.accent} strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round"
              opacity={progress > 0.6 ? 1 : 0} />
      </svg>
      <VLang code={to} color={V.accent} size={64}
        style={{ background: V.accent, color: '#fff', opacity: progress > 0.5 ? 1 : 0.3 }} />
    </div>
  );
}

// ── Hand-drawn arrow ─────────────────────────────
function VArrow({ from, to, color = V.accent, thick = 4, curve = 0.3 }) {
  const dx = to.x - from.x, dy = to.y - from.y;
  const mx = (from.x + to.x) / 2 - dy * curve;
  const my = (from.y + to.y) / 2 + dx * curve;
  return (
    <svg style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }} width="100%" height="100%">
      <path d={`M ${from.x} ${from.y} Q ${mx} ${my}, ${to.x} ${to.y}`}
            stroke={color} strokeWidth={thick} fill="none" strokeLinecap="round" />
    </svg>
  );
}

// ── Official huggie wordmark ─────────────────────────────
// Ported from the live website's Navbar.tsx:
//   hu | <span relative>gg + heart-svg(absolute, centred on gg)</span> | ie
// Heart sized at 0.78× font, top offset -0.27× font (matches the
// website's h-6/h-7 + -top-2/-top-2.5 on text-3xl/4xl).
// Pass noHeart for cases where another heart in the same scene
// would compete (e.g. Scene 6 logo reveal with the big merged heart).
function HuggieLogo({ size = 80, color = V.ink, heartColor = V.accent, noHeart = false, style }) {
  const baseStyle = {
    fontFamily: fontBrand, fontWeight: 700, fontSize: size,
    color, letterSpacing: '-0.025em', lineHeight: 1,
    display: 'inline-flex', alignItems: 'baseline',
    whiteSpace: 'nowrap',
  };
  if (noHeart) {
    return <span style={{ ...baseStyle, ...style }}>huggie</span>;
  }
  return (
    <span style={{ ...baseStyle, ...style }}>
      <span>hu</span>
      <span style={{ position: 'relative', display: 'inline-block' }}>
        gg
        <svg viewBox="0 0 24 24"
             width={size * 0.60} height={size * 0.60}
             style={{
               position: 'absolute',
               left: '50%', top: `-${size * 0.35}px`,
               transform: 'translateX(-50%)',
               display: 'block',
               fill: heartColor,
             }}>
          {/* Sits ~0.05·font above the letter tops at all sizes:
              ~13px gap at size 220 (Scene 2), ~17px at size 320
              (would-be Scene 6), ~1.5px at navbar size 30.
              Midway between the navbar's slight-overlap ratios
              and my earlier over-corrected floating heart. */}
          <path d="M12 21s-7.5-4.7-7.5-10.25A4.25 4.25 0 0 1 12 7.6a4.25 4.25 0 0 1 7.5 3.15C19.5 16.3 12 21 12 21Z" />
        </svg>
      </span>
      <span>ie</span>
    </span>
  );
}

// ── Compact "huggie ai" lockup with green dot pill (call-bug style) ──
function HuggieBug({ size = 26, color = V.ink, heartColor = V.accent, label, style }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      padding: label ? '6px 14px' : 0,
      border: label ? `1.5px solid rgba(255,255,255,0.2)` : 'none',
      borderRadius: 999,
      background: label ? 'rgba(20,20,20,0.6)' : 'transparent',
      ...style,
    }}>
      {label && <span style={{ width: 8, height: 8, borderRadius: 4, background: V.green, boxShadow: `0 0 0 0 ${V.green}` }} />}
      <HuggieLogo size={size} color={color} heartColor={heartColor} />
      {label && (
        <span style={{
          fontFamily: fontHead, fontSize: size * 0.55, fontWeight: 500,
          color: color === V.ink ? V.ink2 : 'rgba(255,255,255,0.75)',
          letterSpacing: '-0.01em',
        }}>{label}</span>
      )}
    </span>
  );
}

// ── Map-of-the-world placeholder w/ pulsing dots ─────────────────────────────
// `connections` is an array of { from, to } where from/to are indices into
// the `pulses` array — renders an arched dashed line between the two cities
// as each pair becomes alive.
function VWorld({ width = 1100, height = 540, pulses = [], connections = [], time = 0, style }) {
  return (
    <div style={{ position: 'relative', width, height, ...style }}>
      <svg viewBox="0 0 100 50" preserveAspectRatio="none" style={{ width: '100%', height: '100%' }}>
        <g fill="none" stroke={V.ink3} strokeWidth="0.15" opacity="0.4">
          {Array.from({ length: 9 }, (_, i) => (
            <line key={`h${i}`} x1="0" y1={i * 6} x2="100" y2={i * 6} />
          ))}
          {Array.from({ length: 17 }, (_, i) => (
            <line key={`v${i}`} x1={i * 6} y1="0" x2={i * 6} y2="50" />
          ))}
        </g>

      </svg>

      {/* connection arcs between cities — the background map uses a
          0-50 SVG Y-axis, while dots are CSS percentages. This overlay
          uses a 0-100 coordinate plane so arcs land on the dot centers. */}
      <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{
        position: 'absolute', inset: 0,
        width: '100%', height: '100%',
        pointerEvents: 'none', overflow: 'visible',
      }}>
        <g fill="none" stroke={V.accent}
           strokeLinecap="round" strokeDasharray="1.2 1.6">
          {connections.map((c, i) => {
            const a = pulses[c.from], b = pulses[c.to];
            if (!a || !b) return null;
            const revealAt = Math.max(a.delay || 0, b.delay || 0) + 0.4;
            if (time < revealAt) return null;
            const draw = clamp((time - revealAt) / 1.0, 0, 1);
            const midX = (a.x + b.x) / 2;
            const dist = Math.hypot(a.x - b.x, a.y - b.y);
            const midY = (a.y + b.y) / 2 - dist * 0.18;
            const arcLen = dist * 1.15;
            return (
              <path key={i}
                    d={`M ${a.x} ${a.y} Q ${midX} ${midY}, ${b.x} ${b.y}`}
                    strokeWidth={c.weight || 0.35}
                    strokeDashoffset={(1 - draw) * arcLen}
                    opacity={draw * (c.opacity || 0.75)}
                    pathLength={arcLen} />
            );
          })}
        </g>
      </svg>

      {/* pulses */}
      {pulses.map((p, i) => {
        const delay = p.delay || 0;
        const alive = time > delay;
        if (!alive) return null;
        return (
          <div key={i} style={{
            position: 'absolute',
            left: `${p.x}%`, top: `${p.y}%`,
            transform: 'translate(-50%, -50%)',
          }}>
            <div style={{
              width: p.minor ? 10 : 14,
              height: p.minor ? 10 : 14,
              borderRadius: 8,
              background: V.accent,
              border: `${p.minor ? 1.7 : 2}px solid ${V.ink}`,
            }} />
            {p.label && (
              <div style={{
                position: 'absolute',
                left: p.labelDx ?? (p.minor ? 16 : 22),
                top: p.labelDy ?? (p.minor ? -7 : -8),
                fontFamily: fontMono,
                fontSize: p.minor ? 11 : 14,
                color: V.ink,
                whiteSpace: 'nowrap',
                background: V.paper, padding: '2px 6px',
                border: `1.5px solid ${V.ink}`, borderRadius: 6,
              }}>{p.label}</div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ── Heart / sparkle accents drawn by hand ─────────────────────────────
function VHeart({ size = 40, color = V.accent, x = 0, y = 0, style }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} style={{ position: 'absolute', left: x, top: y, ...style }}>
      <path d="M12 21s-7-4.5-9.5-9.5C0.5 7 4 3 8 4c1.7 0.4 3 1.8 4 3 1-1.2 2.3-2.6 4-3 4-1 7.5 3 5.5 7.5C19 16.5 12 21 12 21z"
            fill={color} stroke={V.ink} strokeWidth="1.5" strokeLinejoin="round" />
    </svg>
  );
}

function VSparkle({ size = 28, color = V.accent, x = 0, y = 0, style }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} style={{ position: 'absolute', left: x, top: y, ...style }}>
      <path d="M12 2v8 M12 14v8 M2 12h8 M14 12h8" stroke={color} strokeWidth="2.5" strokeLinecap="round" />
    </svg>
  );
}

// ── Global keyframes (inject once) ─────────────────────────────
(function injectKeyframes() {
  if (document.getElementById('huggie-video-keyframes')) return;
  const style = document.createElement('style');
  style.id = 'huggie-video-keyframes';
  style.textContent = `
    @keyframes vBlink { 0%,100% { opacity: 1 } 50% { opacity: 0 } }
    @keyframes vPulseDot {
      0% { box-shadow: 0 0 0 0 rgba(21,163,106, 0.6); }
      100% { box-shadow: 0 0 0 14px rgba(21,163,106, 0); }
    }
    @keyframes vRing {
      0% { transform: scale(1); opacity: 0.65; }
      100% { transform: scale(2.2); opacity: 0; }
    }
    @keyframes vFloat {
      0%,100% { transform: translateY(0); }
      50% { transform: translateY(-8px); }
    }
  `;
  document.head.appendChild(style);
})();

Object.assign(window, {
  V, fontHand, fontMono, fontHead, fontBrand, fontSerif,
  VPhone, VAvatar, VLang, VUnderline, VWaveform, VCaption,
  VLatency, VTitle, VPaperTexture, VLangSwap, VArrow, VWorld,
  VHeart, VSparkle,
  HuggieLogo, HuggieBug,
});
