// scenes.jsx — Catchflow "System Quest" themed todo list animation
// Vertical 9:16 mobile format, 1080x1920 stage

// ─── Theme ──────────────────────────────────────────────────────────────────
const THEME = {
  bg: '#03060d',
  bgDeep: '#000208',
  cyan: '#7DEBFF',
  cyanDim: '#3AA0BF',
  blue: '#4F8DFF',
  violet: '#9B7BFF',
  ink: '#E8F4FF',
  ash: '#7A8CA0',
  warn: '#FFB347',
  green: '#7CFFB2',
  red: '#FF6B8A',
  panel: 'rgba(20, 36, 64, 0.55)',
  panelEdge: 'rgba(125, 235, 255, 0.55)',
  font: '"Rajdhani", "Orbitron", system-ui, sans-serif',
  mono: '"JetBrains Mono", ui-monospace, monospace',
};

// ─── Reusable atoms ─────────────────────────────────────────────────────────

// Bracketed corner frame: angular sci-fi panel with cut corners and glow
function Bracket({ x, y, width, height, opacity = 1, glow = 1, cut = 18, edgeColor }) {
  const c = edgeColor || THEME.panelEdge;
  const path = `polygon(
    ${cut}px 0,
    calc(100% - ${cut}px) 0,
    100% ${cut}px,
    100% calc(100% - ${cut}px),
    calc(100% - ${cut}px) 100%,
    ${cut}px 100%,
    0 calc(100% - ${cut}px),
    0 ${cut}px
  )`;
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width, height, opacity,
      filter: `drop-shadow(0 0 ${12 * glow}px ${THEME.cyan})`,
    }}>
      {/* Outer hex edge */}
      <div style={{
        position: 'absolute', inset: 0,
        background: c,
        clipPath: path,
      }}/>
      {/* Inner fill (slightly inset) */}
      <div style={{
        position: 'absolute', inset: 1.5,
        background: 'linear-gradient(160deg, rgba(8,18,40,0.92) 0%, rgba(4,10,24,0.95) 100%)',
        clipPath: path,
      }}/>
      {/* Scanline overlay */}
      <div style={{
        position: 'absolute', inset: 1.5,
        background: 'repeating-linear-gradient(0deg, transparent 0 3px, rgba(125,235,255,0.04) 3px 4px)',
        clipPath: path,
        pointerEvents: 'none',
      }}/>
    </div>
  );
}

// Angular L-corner brackets (floating, no panel fill)
function CornerMarks({ x, y, width, height, size = 28, color, opacity = 1, thickness = 3 }) {
  const c = color || THEME.cyan;
  const s = size;
  const t = thickness;
  const corner = (top, left, hFlip, vFlip) => (
    <div style={{
      position: 'absolute',
      top: top, left: left,
      width: s, height: s,
      transform: `scale(${hFlip ? -1 : 1}, ${vFlip ? -1 : 1})`,
      transformOrigin: 'top left',
    }}>
      <div style={{ position: 'absolute', top: 0, left: 0, width: s, height: t, background: c, boxShadow: `0 0 8px ${c}` }}/>
      <div style={{ position: 'absolute', top: 0, left: 0, width: t, height: s, background: c, boxShadow: `0 0 8px ${c}` }}/>
    </div>
  );
  return (
    <div style={{ position: 'absolute', left: x, top: y, width, height, opacity, pointerEvents: 'none' }}>
      {corner(0, 0, false, false)}
      {corner(0, width, true, false)}
      {corner(height, 0, false, true)}
      {corner(height, width, true, true)}
    </div>
  );
}

// Animated scanline sweeping across a region
function Scanline({ x, y, width, height, time, period = 3, color }) {
  const c = color || THEME.cyan;
  const t = (time % period) / period;
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width, height,
      overflow: 'hidden', pointerEvents: 'none',
    }}>
      <div style={{
        position: 'absolute', left: 0, right: 0,
        top: `${t * 100}%`,
        height: 60,
        background: `linear-gradient(180deg, transparent 0%, ${c}33 40%, ${c}88 50%, ${c}33 60%, transparent 100%)`,
        opacity: 0.6,
      }}/>
    </div>
  );
}

// Particle field — slowly-drifting glints
function ParticleField({ count = 60, time, width = 1080, height = 1920 }) {
  const particles = React.useMemo(() => {
    const arr = [];
    for (let i = 0; i < count; i++) {
      arr.push({
        x: Math.random() * width,
        y: Math.random() * height,
        size: 1 + Math.random() * 2.5,
        speed: 6 + Math.random() * 18,
        phase: Math.random() * Math.PI * 2,
        hue: Math.random() < 0.7 ? THEME.cyan : THEME.violet,
      });
    }
    return arr;
  }, [count, width, height]);
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      {particles.map((p, i) => {
        const yy = (p.y - time * p.speed + height) % height;
        const flicker = 0.4 + 0.6 * Math.abs(Math.sin(time * 1.2 + p.phase));
        return (
          <div key={i} style={{
            position: 'absolute',
            left: p.x, top: yy,
            width: p.size, height: p.size,
            borderRadius: '50%',
            background: p.hue,
            opacity: flicker * 0.8,
            boxShadow: `0 0 ${p.size * 3}px ${p.hue}`,
          }}/>
        );
      })}
    </div>
  );
}

// Pulse ring expanding out of a point
function PulseRing({ cx, cy, time, start, period = 1.4, maxR = 360, color, thickness = 2 }) {
  const c = color || THEME.cyan;
  const local = time - start;
  if (local < 0) return null;
  const t = (local % period) / period;
  const r = t * maxR;
  const op = (1 - t) * 0.7;
  return (
    <div style={{
      position: 'absolute',
      left: cx - r, top: cy - r,
      width: r * 2, height: r * 2,
      borderRadius: '50%',
      border: `${thickness}px solid ${c}`,
      opacity: op,
      pointerEvents: 'none',
      boxShadow: `0 0 ${20 * (1 - t)}px ${c}`,
    }}/>
  );
}

// Phone shell (bezel)
function PhoneShell({ x, y, width, height, screenChildren, opacity = 1, scale = 1 }) {
  const r = 64;
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width, height, opacity,
      transform: `scale(${scale})`, transformOrigin: 'center center',
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(160deg, #1c1f26 0%, #0a0c10 100%)',
        borderRadius: r,
        boxShadow: '0 40px 120px rgba(0, 200, 255, 0.18), inset 0 0 0 2px rgba(125,235,255,0.15)',
      }}/>
      <div style={{
        position: 'absolute', inset: 14,
        background: THEME.bgDeep,
        borderRadius: r - 14,
        overflow: 'hidden',
      }}>
        {screenChildren}
      </div>
      {/* Notch */}
      <div style={{
        position: 'absolute',
        left: '50%', top: 22,
        transform: 'translateX(-50%)',
        width: 120, height: 28,
        background: '#000',
        borderRadius: 14,
      }}/>
    </div>
  );
}

// Status bar inside phone screen
function StatusBar({ time }) {
  const hh = String(8 + Math.floor(time / 60)).padStart(2, '0');
  const mm = String(Math.floor(time * 17) % 60).padStart(2, '0');
  return (
    <div style={{
      position: 'absolute', top: 0, left: 0, right: 0, height: 64,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '24px 48px 0',
      fontFamily: THEME.mono,
      color: THEME.ink,
      fontSize: 22,
      fontWeight: 600,
      letterSpacing: '0.08em',
      zIndex: 20,
    }}>
      <span>{hh}:{mm}</span>
      <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <span style={{ display: 'inline-block', width: 18, height: 12, borderRadius: 2, background: THEME.cyan, opacity: 0.9, boxShadow: `0 0 6px ${THEME.cyan}` }}/>
        <span style={{ display: 'inline-block', width: 24, height: 12, border: `1.5px solid ${THEME.ink}`, borderRadius: 2, position: 'relative' }}>
          <span style={{ position: 'absolute', inset: 1.5, background: THEME.cyan, width: '78%', boxShadow: `0 0 6px ${THEME.cyan}` }}/>
        </span>
      </span>
    </div>
  );
}

// ─── Quest item card ────────────────────────────────────────────────────────
function QuestRow({ x, y, width, label, xp, status, time, completeAt, clearedText, pendingText }) {
  // status: "pending" | "complete"
  // completeAt: optional timestamp when completion fires (for flash)
  const justCompleted = completeAt != null && time >= completeAt && time < completeAt + 0.6;
  const flashT = justCompleted ? (time - completeAt) / 0.6 : 0;
  const flashOp = justCompleted ? (1 - flashT) * 0.9 : 0;

  const isDone = status === 'complete';
  const accent = isDone ? THEME.green : THEME.cyan;

  return (
    <div style={{
      position: 'absolute', left: x, top: y, width, height: 130,
    }}>
      {/* Hex panel */}
      <div style={{
        position: 'absolute', inset: 0,
        background: isDone
          ? 'linear-gradient(90deg, rgba(20,60,45,0.55) 0%, rgba(8,20,18,0.65) 100%)'
          : 'linear-gradient(90deg, rgba(12,28,56,0.65) 0%, rgba(6,12,28,0.7) 100%)',
        clipPath: 'polygon(20px 0, 100% 0, 100% calc(100% - 20px), calc(100% - 20px) 100%, 0 100%, 0 20px)',
        border: 'none',
      }}/>
      {/* Edge */}
      <div style={{
        position: 'absolute', inset: 0,
        background: accent,
        clipPath: 'polygon(20px 0, 100% 0, 100% calc(100% - 20px), calc(100% - 20px) 100%, 0 100%, 0 20px, 20px 0, 22px 2px, 2px 22px, 2px calc(100% - 2px), calc(100% - 22px) calc(100% - 2px), calc(100% - 2px) calc(100% - 22px), calc(100% - 2px) 2px, 22px 2px)',
        opacity: 0.85,
        filter: `drop-shadow(0 0 8px ${accent})`,
      }}/>

      {/* Checkbox / hex slot — SVG for clean outline */}
      <div style={{
        position: 'absolute', left: 28, top: '50%', transform: 'translateY(-50%)',
        width: 56, height: 56,
      }}>
        <svg viewBox="0 0 56 56" style={{ position: 'absolute', inset: 0, overflow: 'visible' }}>
          <polygon
            points="28,2 53,16 53,40 28,54 3,40 3,16"
            fill={isDone ? THEME.green : 'rgba(8,18,40,0.6)'}
            stroke={accent}
            strokeWidth="2.5"
            style={{ filter: `drop-shadow(0 0 8px ${accent})` }}
          />
          {isDone && (
            <path d="M14 28 L24 38 L42 18" stroke="#03060d" strokeWidth="5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          )}
        </svg>
      </div>

      {/* Label */}
      <div style={{
        position: 'absolute', left: 110, top: 26, right: 90,
        fontFamily: THEME.font,
        fontSize: 28,
        fontWeight: 600,
        color: isDone ? THEME.ash : THEME.ink,
        textDecoration: isDone ? 'line-through' : 'none',
        textDecorationColor: THEME.green,
        letterSpacing: '0.04em',
        textTransform: 'uppercase',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
      }}>{label}</div>

      {/* XP tag */}
      <div style={{
        position: 'absolute', left: 110, top: 72, right: 90,
        fontFamily: THEME.mono,
        fontSize: 18,
        color: accent,
        letterSpacing: '0.18em',
        whiteSpace: 'nowrap',
      }}>+{xp} XP · {isDone ? (clearedText || 'CLEARED') : (pendingText || 'PENDING')}</div>

      {/* Right rank tag */}
      <div style={{
        position: 'absolute', right: 28, top: '50%', transform: 'translateY(-50%)',
        fontFamily: THEME.font,
        fontSize: 38,
        fontWeight: 700,
        color: isDone ? THEME.green : THEME.cyanDim,
        letterSpacing: '0.1em',
        opacity: 0.7,
      }}>{isDone ? '✓' : 'E'}</div>

      {/* Completion flash */}
      {flashOp > 0 && (
        <div style={{
          position: 'absolute', inset: 0,
          background: `linear-gradient(90deg, transparent, ${THEME.green}, transparent)`,
          opacity: flashOp,
          clipPath: 'polygon(20px 0, 100% 0, 100% calc(100% - 20px), calc(100% - 20px) 100%, 0 100%, 0 20px)',
          mixBlendMode: 'screen',
        }}/>
      )}
    </div>
  );
}

// ─── XP Bar ─────────────────────────────────────────────────────────────────
function XPBar({ x, y, width, fill, label = 'EXP', rank = 'E' }) {
  return (
    <div style={{ position: 'absolute', left: x, top: y, width }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        fontFamily: THEME.mono, fontSize: 18, color: THEME.cyan,
        letterSpacing: '0.16em', marginBottom: 10,
        whiteSpace: 'nowrap',
      }}>
        <span>{label}</span>
        <span style={{ color: THEME.ink, fontVariantNumeric: 'tabular-nums' }}>{Math.round(fill * 100)}%</span>
      </div>
      <div style={{
        position: 'relative', width: '100%', height: 18,
        background: 'rgba(125,235,255,0.08)',
        clipPath: 'polygon(0 0, 100% 0, calc(100% - 8px) 100%, 8px 100%)',
        border: `1px solid ${THEME.cyanDim}`,
      }}>
        <div style={{
          position: 'absolute', left: 0, top: 0, bottom: 0,
          width: `${fill * 100}%`,
          background: `linear-gradient(90deg, ${THEME.blue} 0%, ${THEME.cyan} 100%)`,
          clipPath: 'polygon(0 0, 100% 0, calc(100% - 8px) 100%, 8px 100%)',
          boxShadow: `0 0 18px ${THEME.cyan}`,
          transition: 'width 0.1s linear',
        }}/>
        {/* Tick marks */}
        {[0.25, 0.5, 0.75].map((p, i) => (
          <div key={i} style={{
            position: 'absolute', left: `${p * 100}%`, top: 0, bottom: 0,
            width: 1, background: 'rgba(0,0,0,0.5)',
          }}/>
        ))}
      </div>
    </div>
  );
}

// ─── Cursor ─────────────────────────────────────────────────────────────────
function Cursor({ x, y, opacity = 1, tap = 0 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      transform: `translate(-50%, -50%) scale(${1 - tap * 0.15})`,
      opacity,
      pointerEvents: 'none',
      zIndex: 50,
    }}>
      {/* Cursor dot */}
      <div style={{
        width: 60, height: 60,
        borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(125,235,255,0.7) 0%, rgba(125,235,255,0.15) 60%, transparent 100%)',
        boxShadow: `0 0 24px ${THEME.cyan}`,
      }}/>
      <div style={{
        position: 'absolute', inset: '50%',
        width: 14, height: 14,
        marginLeft: -7, marginTop: -7,
        background: '#fff',
        borderRadius: '50%',
        boxShadow: `0 0 12px ${THEME.cyan}`,
      }}/>
      {/* Tap rings */}
      {tap > 0 && (
        <>
          <div style={{
            position: 'absolute', inset: '50%',
            width: 80 + tap * 80, height: 80 + tap * 80,
            marginLeft: -(40 + tap * 40), marginTop: -(40 + tap * 40),
            borderRadius: '50%',
            border: `2px solid ${THEME.cyan}`,
            opacity: 1 - tap,
          }}/>
        </>
      )}
    </div>
  );
}

Object.assign(window, {
  THEME, Bracket, CornerMarks, Scanline, ParticleField, PulseRing,
  PhoneShell, StatusBar, QuestRow, XPBar, Cursor,
});
