import React from 'react';
import { useCurrentFrame, spring, useVideoConfig, interpolate } from 'remotion';
import { COLORS, FONT, GLASS_CARD, SPRING } from '../styles/theme';
import { MeshBackground } from '../components/MeshBackground';
import { ParticleField } from '../components/ParticleField';
import { GlassCard } from '../components/GlassCard';
import { KineticText } from '../components/KineticText';

/* ─── App definitions with inline SVG icon renderers ─── */
interface AppDef {
  name: string;
  color: string;
  badge: string;
  icon: (size: number, color: string) => React.ReactNode;
}

const apps: AppDef[] = [
  {
    name: 'Email',
    color: '#4285f4',
    badge: '+47',
    icon: (s, c) => (
      <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
        <rect x="2" y="4" width="20" height="16" rx="3" stroke={c} strokeWidth="1.8" />
        <path d="M2 7l10 6 10-6" stroke={c} strokeWidth="1.8" strokeLinecap="round" />
      </svg>
    ),
  },
  {
    name: 'CRM',
    color: '#ff6d5a',
    badge: '+128',
    icon: (s, c) => (
      <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
        <circle cx="12" cy="8" r="4" stroke={c} strokeWidth="1.8" />
        <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7" stroke={c} strokeWidth="1.8" strokeLinecap="round" />
      </svg>
    ),
  },
  {
    name: 'Sheets',
    color: '#34a853',
    badge: '+23',
    icon: (s, c) => (
      <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
        <rect x="3" y="3" width="18" height="18" rx="2" stroke={c} strokeWidth="1.8" />
        <line x1="3" y1="9" x2="21" y2="9" stroke={c} strokeWidth="1.2" />
        <line x1="3" y1="15" x2="21" y2="15" stroke={c} strokeWidth="1.2" />
        <line x1="9" y1="3" x2="9" y2="21" stroke={c} strokeWidth="1.2" />
        <line x1="15" y1="3" x2="15" y2="21" stroke={c} strokeWidth="1.2" />
      </svg>
    ),
  },
  {
    name: 'Calendar',
    color: '#fbbc04',
    badge: 'MISSED',
    icon: (s, c) => (
      <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
        <rect x="3" y="4" width="18" height="17" rx="2" stroke={c} strokeWidth="1.8" />
        <line x1="3" y1="10" x2="21" y2="10" stroke={c} strokeWidth="1.5" />
        <line x1="8" y1="2" x2="8" y2="6" stroke={c} strokeWidth="1.8" strokeLinecap="round" />
        <line x1="16" y1="2" x2="16" y2="6" stroke={c} strokeWidth="1.8" strokeLinecap="round" />
      </svg>
    ),
  },
  {
    name: 'Slack',
    color: '#e01e5a',
    badge: '+89',
    icon: (s, c) => (
      <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
        <path d="M6 15a2 2 0 1 1-2-2h2v2zM7 15a2 2 0 1 1 2 2H7v-2z" fill={c} />
        <path d="M18 9a2 2 0 1 1 2 2h-2V9zM17 9a2 2 0 1 1-2-2h2v2z" fill={c} />
        <path d="M9 18a2 2 0 1 1 2 2v-2H9zM9 17a2 2 0 1 1-2-2v2h2z" fill={c} />
        <path d="M15 6a2 2 0 1 1-2-2v2h2zM15 7a2 2 0 1 1 2 2v-2h-2z" fill={c} />
      </svg>
    ),
  },
  {
    name: 'Phone',
    color: '#7c3aed',
    badge: '5 MISSED',
    icon: (s, c) => (
      <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
        <path
          d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"
          stroke={c}
          strokeWidth="1.8"
          strokeLinecap="round"
        />
      </svg>
    ),
  },
  {
    name: 'Analytics',
    color: '#26a5e4',
    badge: 'UPDATE',
    icon: (s, c) => (
      <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
        <rect x="3" y="14" width="4" height="7" rx="1" fill={c} opacity={0.5} />
        <rect x="10" y="9" width="4" height="12" rx="1" fill={c} opacity={0.7} />
        <rect x="17" y="4" width="4" height="17" rx="1" fill={c} />
      </svg>
    ),
  },
  {
    name: 'Social',
    color: '#ff4500',
    badge: '+312',
    icon: (s, c) => (
      <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
        <circle cx="12" cy="12" r="9" stroke={c} strokeWidth="1.8" />
        <circle cx="9" cy="10" r="1.5" fill={c} />
        <circle cx="15" cy="10" r="1.5" fill={c} />
        <path d="M8 14s1.5 2 4 2 4-2 4-2" stroke={c} strokeWidth="1.5" strokeLinecap="round" />
      </svg>
    ),
  },
];

/* ─── Card positions in a 4×2 scattered grid ─── */
const positions = [
  { x: 210, y: 200 },
  { x: 560, y: 160 },
  { x: 910, y: 210 },
  { x: 1260, y: 170 },
  { x: 290, y: 510 },
  { x: 640, y: 490 },
  { x: 990, y: 520 },
  { x: 1340, y: 500 },
];

/* ─── Explode angles for cards scattering outward ─── */
const explodeAngles = [
  -135, -100, -60, -30, 150, 120, 70, 40,
];

export const Scene2Problem: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

  /* ─── Timing constants ─── */
  const SHAKE_START = 120;
  const SHAKE_END = 140;
  const EXPLODE_START = 138;
  const EXPLODE_DURATION = 35;

  const isShaking = frame >= SHAKE_START && frame < SHAKE_END;

  /* ─── Screen shake ─── */
  const shakeX = isShaking
    ? Math.sin(frame * 2.5) * interpolate(frame, [SHAKE_START, SHAKE_END], [14, 0], {
        extrapolateLeft: 'clamp',
        extrapolateRight: 'clamp',
      })
    : 0;
  const shakeY = isShaking
    ? Math.cos(frame * 3.1) * interpolate(frame, [SHAKE_START, SHAKE_END], [10, 0], {
        extrapolateLeft: 'clamp',
        extrapolateRight: 'clamp',
      })
    : 0;

  /* ─── Blur flash on shake ─── */
  const blurAmount = isShaking
    ? interpolate(frame, [SHAKE_START, SHAKE_START + 5, SHAKE_END], [0, 3, 0], {
        extrapolateLeft: 'clamp',
        extrapolateRight: 'clamp',
      })
    : 0;

  /* ─── Red flash overlay ─── */
  const flashOpacity = isShaking
    ? interpolate(frame, [SHAKE_START, SHAKE_START + 3, SHAKE_START + 10], [0, 0.15, 0], {
        extrapolateLeft: 'clamp',
        extrapolateRight: 'clamp',
      })
    : 0;

  /* ─── Title ─── */
  const titleOpacity = interpolate(frame, [0, 20], [0, 1], {
    extrapolateLeft: 'clamp',
    extrapolateRight: 'clamp',
  });

  return (
    <div
      style={{
        width: 1920,
        height: 1080,
        fontFamily: FONT,
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      {/* Mesh background – red shifted for "problem" mood */}
      <MeshBackground
        color1="#ef4444"
        color2="#991b1b"
        color3={COLORS.secondary}
        intensity={0.18}
        speed={0.8}
      />

      <ParticleField count={35} color="#ff444444" drift="up" seed={77} />

      {/* Shakeable content wrapper */}
      <div
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: 1920,
          height: 1080,
          transform: `translate(${shakeX}px, ${shakeY}px)`,
          filter: blurAmount > 0 ? `blur(${blurAmount}px)` : undefined,
        }}
      >
        {/* Title */}
        <div
          style={{
            position: 'absolute',
            top: 50,
            width: '100%',
            textAlign: 'center',
            fontSize: 38,
            fontWeight: 600,
            color: COLORS.gray,
            opacity: titleOpacity,
          }}
        >
          Your daily reality:
        </div>

        {/* App cards */}
        {apps.map((app, i) => {
          const entryDelay = 5 + i * 7;

          const entryScale = spring({
            frame: frame - entryDelay,
            fps,
            config: SPRING.bouncy,
          });

          /* Floating parallax */
          const floatX = Math.sin(frame * 0.03 + i * 1.2) * 6;
          const floatY = Math.cos(frame * 0.025 + i * 0.9) * 4;

          /* Badge pop */
          const badgeDelay = entryDelay + 18;
          const badgeScale = spring({
            frame: frame - badgeDelay,
            fps,
            config: SPRING.bouncy,
          });

          /* Second badge pile-up */
          const badge2Delay = badgeDelay + 20 + i * 3;
          const badge2Scale = spring({
            frame: frame - badge2Delay,
            fps,
            config: SPRING.bouncy,
          });
          const badge2Value = i % 3 === 0 ? '+3' : i % 3 === 1 ? '!' : '+1';

          /* Explode outward */
          const explodeProgress = interpolate(
            frame - EXPLODE_START,
            [0, EXPLODE_DURATION],
            [0, 1],
            { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' }
          );
          const angle = (explodeAngles[i] * Math.PI) / 180;
          const explodeDist = explodeProgress * 800;
          const explodeX = Math.cos(angle) * explodeDist;
          const explodeY = Math.sin(angle) * explodeDist;
          const explodeOpacity = interpolate(explodeProgress, [0, 0.3, 1], [1, 1, 0], {
            extrapolateLeft: 'clamp',
            extrapolateRight: 'clamp',
          });
          const explodeRotate = explodeProgress * (i % 2 === 0 ? 25 : -25);

          return (
            <div
              key={i}
              style={{
                position: 'absolute',
                left: positions[i].x + floatX + explodeX,
                top: positions[i].y + floatY + explodeY,
                transform: `scale(${entryScale}) rotate(${explodeRotate}deg)`,
                opacity: entryScale * explodeOpacity,
              }}
            >
              {/* Glass card */}
              <div
                style={{
                  ...GLASS_CARD,
                  width: 210,
                  height: 170,
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: 10,
                  borderColor: `${app.color}30`,
                }}
              >
                {/* Icon */}
                <div style={{ opacity: 0.9 }}>
                  {app.icon(42, app.color)}
                </div>
                <span
                  style={{
                    color: COLORS.white,
                    fontSize: 17,
                    fontWeight: 600,
                  }}
                >
                  {app.name}
                </span>
              </div>

              {/* Primary notification badge */}
              <div
                style={{
                  position: 'absolute',
                  top: -10,
                  right: -10,
                  background: COLORS.red,
                  color: COLORS.white,
                  fontSize: 13,
                  fontWeight: 700,
                  padding: '5px 11px',
                  borderRadius: 20,
                  transform: `scale(${badgeScale})`,
                  whiteSpace: 'nowrap',
                  boxShadow: `0 2px 8px ${COLORS.red}80`,
                }}
              >
                {app.badge}
              </div>

              {/* Stacked second badge */}
              <div
                style={{
                  position: 'absolute',
                  top: -10,
                  right: 50,
                  background: '#f97316',
                  color: COLORS.white,
                  fontSize: 11,
                  fontWeight: 700,
                  padding: '3px 8px',
                  borderRadius: 14,
                  transform: `scale(${badge2Scale})`,
                  whiteSpace: 'nowrap',
                  opacity: badge2Scale,
                }}
              >
                {badge2Value}
              </div>
            </div>
          );
        })}
      </div>

      {/* Red flash overlay */}
      <div
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: 1920,
          height: 1080,
          background: COLORS.red,
          opacity: flashOpacity,
          pointerEvents: 'none',
        }}
      />

      {/* Bottom text: KineticText stagger */}
      <div
        style={{
          position: 'absolute',
          bottom: 70,
          width: '100%',
          display: 'flex',
          justifyContent: 'center',
        }}
      >
        <KineticText
          text="12 tools. 47 tabs. 0 sanity."
          fontSize={44}
          fontWeight={700}
          color={COLORS.white}
          highlightWords={['12', '47', '0']}
          highlightColor={COLORS.primary}
          startDelay={70}
          staggerFrames={6}
          animationType="fadeScale"
        />
      </div>
    </div>
  );
};
