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

/* ═══════════════════════════════════════════════════════════════
   7a  Phone Monitor  (105 frames ≈ 3.5 s)
   ═══════════════════════════════════════════════════════════════ */
const PhoneMonitor: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

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

  /* ── audio-style waveform bars ── */
  const BAR_COUNT = 35;
  const bars = Array.from({ length: BAR_COUNT }, (_, i) => {
    const phase = i * 0.4;
    const h =
      20 +
      Math.sin(i * 0.3) * 10 +
      Math.sin(frame * 0.12 + phase) * 25 +
      Math.cos(frame * 0.08 + phase * 1.3) * 15;
    return Math.max(4, h);
  });

  /* ── transcript lines ── */
  const lines = [
    { speaker: 'Customer', text: '"I need to cancel my subscription…"', isAI: false },
    { speaker: 'AI Agent', text: '"I understand. Let me check options…"', isAI: true },
    { speaker: 'Customer', text: '"The price is just too high."', isAI: false },
    { speaker: 'AI Agent', text: '"I can offer a 30 % loyalty discount…"', isAI: true },
    { speaker: 'Customer', text: '"That actually sounds great!"', isAI: false },
  ];

  /* ── pulsing glow ring ── */
  const glowPulse = 0.8 + Math.sin(frame * 0.1) * 0.2;
  const glowSize = 130 + Math.sin(frame * 0.08) * 10;

  /* ── INTERRUPT button ── */
  const buttonScale = 1 + Math.sin(frame * 0.12) * 0.06;
  const buttonEntry = spring({ frame: frame - 50, fps, config: SPRING.bouncy });

  return (
    <div style={{ width: 1920, height: 1080, position: 'relative', overflow: 'hidden', fontFamily: FONT }}>
      <MeshBackground color1={COLORS.primary} color2="#ff8a65" intensity={0.2} />

      {/* title */}
      <div style={{ position: 'absolute', top: 45, width: '100%', textAlign: 'center' }}>
        <KineticText
          text="Live call monitoring with human override"
          highlightWords={['human', 'override']}
          highlightColor={COLORS.primary}
          fontSize={38}
          animationType="slideUp"
        />
      </div>

      {/* phone icon + glow ring */}
      <div
        style={{
          position: 'absolute',
          left: 180,
          top: 250,
          width: 120,
          height: 120,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          transform: `scale(${entryScale})`,
        }}
      >
        <div
          style={{
            position: 'absolute',
            width: glowSize,
            height: glowSize,
            borderRadius: '50%',
            border: `2px solid ${COLORS.primary}`,
            boxShadow: `0 0 30px ${COLORS.primary}40, inset 0 0 20px ${COLORS.primary}20`,
            opacity: glowPulse,
          }}
        />
        <div
          style={{
            width: 90,
            height: 90,
            borderRadius: '50%',
            background: `linear-gradient(135deg, ${COLORS.primary}, ${COLORS.primary}cc)`,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: 40,
            boxShadow: `0 0 40px ${COLORS.primary}50`,
          }}
        >
          📞
        </div>
      </div>

      {/* waveform */}
      <div
        style={{
          position: 'absolute',
          left: 120,
          top: 430,
          display: 'flex',
          alignItems: 'center',
          gap: 4,
          height: 80,
          transform: `scale(${entryScale})`,
        }}
      >
        {bars.map((h, i) => {
          const barEntry = spring({ frame: frame - i * 1, fps, config: SPRING.snappy });
          return (
            <div
              key={i}
              style={{
                width: 8,
                height: h * barEntry,
                borderRadius: 4,
                background: `linear-gradient(180deg, ${COLORS.primary}, ${COLORS.primary}40)`,
                boxShadow: `0 0 6px ${COLORS.primary}30`,
              }}
            />
          );
        })}
      </div>

      {/* transcript card */}
      <div style={{ position: 'absolute', right: 100, top: 180, width: 560 }}>
        <GlassCard delay={10} glowColor={COLORS.primary} padding={28} animateFrom="right">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {lines.map((l, i) => {
              const op = interpolate(frame, [15 + i * 14, 25 + i * 14], [0, 1], {
                extrapolateLeft: 'clamp',
                extrapolateRight: 'clamp',
              });
              const ty = interpolate(frame, [15 + i * 14, 25 + i * 14], [12, 0], {
                extrapolateLeft: 'clamp',
                extrapolateRight: 'clamp',
              });
              return (
                <div key={i} style={{ opacity: op, transform: `translateY(${ty}px)` }}>
                  <div
                    style={{
                      fontSize: 11,
                      fontWeight: 600,
                      color: l.isAI ? COLORS.primary : COLORS.gray,
                      marginBottom: 2,
                    }}
                  >
                    {l.speaker}
                  </div>
                  <div style={{ fontSize: 15, color: COLORS.white, lineHeight: 1.4 }}>{l.text}</div>
                </div>
              );
            })}
          </div>
        </GlassCard>
      </div>

      {/* INTERRUPT button */}
      <div
        style={{
          position: 'absolute',
          bottom: 80,
          left: '50%',
          marginLeft: -130,
          transform: `scale(${buttonScale * buttonEntry})`,
          opacity: buttonEntry,
        }}
      >
        <AnimatedGlowBorder color1={COLORS.primary} color2={COLORS.red} borderRadius={32} speed={2}>
          <div
            style={{
              padding: '16px 48px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 10,
              fontSize: 22,
              fontWeight: 700,
              color: COLORS.white,
            }}
          >
            ⚡ INTERRUPT
          </div>
        </AnimatedGlowBorder>
      </div>

      <ParticleField count={25} color={COLORS.primary} drift="up" />
    </div>
  );
};

/* ═══════════════════════════════════════════════════════════════
   7b  Batch Generation  (105 frames ≈ 3.5 s)
   ═══════════════════════════════════════════════════════════════ */
const BatchGeneration: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

  const funnels = [
    { name: 'ServiceTitan', img: 'funnel-servicetitan.png' },
    { name: 'Jobber', img: 'funnel-jobber.png' },
    { name: 'CloseCRM', img: 'funnel-closecrm.png' },
    { name: 'Rippling', img: 'funnel-rippling.png' },
    { name: 'FreshBooks', img: 'funnel-freshbooks.png' },
    { name: 'HouseCall Pro', img: 'funnel-housecallpro.png' },
    { name: 'TouchBistro', img: 'funnel-touchbistro.png' },
    { name: 'Wave', img: 'funnel-wave.png' },
    { name: 'BambooHR', img: 'funnel-bamboohr.png' },
    { name: 'Lightspeed', img: 'funnel-lightspeed.png' },
    { name: 'FieldEdge', img: 'funnel-fieldedge.png' },
    { name: 'Clover', img: 'funnel-clover.png' },
  ];

  const totalTarget = 30;
  const completed = Math.min(
    totalTarget,
    Math.floor(
      interpolate(frame, [15, 90], [0, 30], {
        extrapolateLeft: 'clamp',
        extrapolateRight: 'clamp',
      }),
    ),
  );
  const progressPct = interpolate(frame, [15, 90], [0, 100], {
    extrapolateLeft: 'clamp',
    extrapolateRight: 'clamp',
  });

  return (
    <div style={{ width: 1920, height: 1080, position: 'relative', overflow: 'hidden', fontFamily: FONT }}>
      <MeshBackground color1={COLORS.primary} color2={COLORS.green} intensity={0.18} />

      {/* title */}
      <div style={{ position: 'absolute', top: 35, width: '100%', textAlign: 'center' }}>
        <KineticText
          text="Generate 30 funnels in one command"
          highlightWords={['30', 'funnels']}
          highlightColor={COLORS.primary}
          fontSize={36}
          animationType="fadeScale"
        />
      </div>

      {/* funnel card grid (4 × 3) */}
      <div
        style={{
          position: 'absolute',
          top: 120,
          left: 200,
          right: 200,
          display: 'grid',
          gridTemplateColumns: 'repeat(4, 1fr)',
          gap: 16,
        }}
      >
        {funnels.map((funnel, i) => {
          const row = Math.floor(i / 4);
          const col = i % 4;
          const delay = 8 + (row + col) * 4;
          const cardProg = spring({ frame: frame - delay, fps, config: SPRING.snappy });
          const isDone = frame > delay + 20;
          const checkOp = interpolate(frame, [delay + 20, delay + 30], [0, 1], {
            extrapolateLeft: 'clamp',
            extrapolateRight: 'clamp',
          });

          return (
            <div
              key={i}
              style={{
                transform: `scale(${interpolate(cardProg, [0, 1], [0.5, 1])})`,
                opacity: cardProg,
              }}
            >
              <GlassCard
                delay={0}
                padding={0}
                animateFrom="none"
                borderColor={isDone ? `${COLORS.green}60` : COLORS.cardBorder}
                glowColor={isDone ? COLORS.green : undefined}
                style={{ overflow: 'hidden' }}
              >
                <div
                  style={{
                    height: 160,
                    position: 'relative',
                    overflow: 'hidden',
                  }}
                >
                  {/* Real funnel screenshot */}
                  <Img
                    src={staticFile(`funnels/${funnel.img}`)}
                    style={{
                      width: '100%',
                      height: '100%',
                      objectFit: 'cover',
                      objectPosition: 'top center',
                    }}
                  />
                  {/* Dark overlay with name */}
                  <div
                    style={{
                      position: 'absolute',
                      bottom: 0,
                      left: 0,
                      right: 0,
                      padding: '20px 8px 8px',
                      background: 'linear-gradient(transparent, rgba(0,0,0,0.85))',
                    }}
                  >
                    <div style={{ fontSize: 12, fontWeight: 700, color: COLORS.white, textAlign: 'center' }}>
                      {funnel.name}
                    </div>
                  </div>

                  {/* green checkmark overlay */}
                  {isDone && (
                    <div
                      style={{
                        position: 'absolute',
                        top: 8,
                        right: 8,
                        width: 24,
                        height: 24,
                        borderRadius: '50%',
                        background: COLORS.green,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        opacity: checkOp,
                        transform: `scale(${interpolate(checkOp, [0, 1], [0.5, 1])})`,
                        fontSize: 14,
                        color: COLORS.white,
                        boxShadow: `0 0 12px ${COLORS.green}60`,
                      }}
                    >
                      ✓
                    </div>
                  )}
                </div>
              </GlassCard>
            </div>
          );
        })}
      </div>

      {/* progress bar */}
      <div style={{ position: 'absolute', bottom: 70, left: 200, right: 200 }}>
        <div
          style={{
            height: 12,
            borderRadius: 6,
            background: 'rgba(255,255,255,0.06)',
            overflow: 'hidden',
            border: '1px solid rgba(255,255,255,0.04)',
          }}
        >
          <div
            style={{
              height: '100%',
              width: `${progressPct}%`,
              borderRadius: 6,
              background: `linear-gradient(90deg, ${COLORS.green}, ${COLORS.primary})`,
              boxShadow: `0 0 20px ${COLORS.green}40`,
            }}
          />
        </div>
        <div
          style={{
            textAlign: 'center',
            marginTop: 12,
            fontSize: 28,
            fontWeight: 700,
            color: COLORS.white,
          }}
        >
          {completed}/{totalTarget}{' '}
          <span style={{ color: COLORS.green }}>Complete</span>
        </div>
      </div>

      <ParticleField count={20} color={COLORS.green} drift="up" seed={99} />
    </div>
  );
};

/* ═══════════════════════════════════════════════════════════════
   7c  Agent Factory  (105 frames ≈ 3.5 s)
   ═══════════════════════════════════════════════════════════════ */
const AgentFactory: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

  const agents = [
    { name: 'Research', icon: '🔍' },
    { name: 'Writer', icon: '✍️' },
    { name: 'Coder', icon: '💻' },
    { name: 'Analyst', icon: '📊' },
    { name: 'Designer', icon: '🎨' },
    { name: 'QA', icon: '🧪' },
  ];

  const cx = 960;
  const cy = 500;
  const orbit = 250;

  const coreEntry = spring({ frame, fps, config: SPRING.bouncy });
  const corePulse = 1 + Math.sin(frame * 0.08) * 0.03;

  return (
    <div style={{ width: 1920, height: 1080, position: 'relative', overflow: 'hidden', fontFamily: FONT }}>
      <MeshBackground color1={COLORS.secondary} color2="#9333ea" intensity={0.22} />

      {/* title */}
      <div style={{ position: 'absolute', top: 40, width: '100%', textAlign: 'center' }}>
        <KineticText
          text="Parallel AI agents for complex tasks"
          highlightWords={['Parallel', 'agents']}
          highlightColor={COLORS.secondary}
          fontSize={36}
          animationType="slideUp"
        />
      </div>

      {/* connection lines + flowing dots */}
      <svg
        style={{ position: 'absolute', top: 0, left: 0, width: 1920, height: 1080, pointerEvents: 'none' }}
      >
        {agents.map((_, i) => {
          const angle = (i / agents.length) * Math.PI * 2 - Math.PI / 2 + frame * 0.008;
          const ax = cx + Math.cos(angle) * orbit;
          const ay = cy + Math.sin(angle) * orbit * 0.55;
          const lineOp = spring({ frame: frame - 15, fps, config: SPRING.gentle });

          const dotPhase = ((frame * 0.025 + i * 0.167) % 1);
          const dx = cx + (ax - cx) * dotPhase;
          const dy = cy + (ay - cy) * dotPhase;

          return (
            <g key={i} opacity={lineOp}>
              <line
                x1={cx}
                y1={cy}
                x2={ax}
                y2={ay}
                stroke={`${COLORS.secondary}40`}
                strokeWidth={1.5}
                strokeDasharray="4 6"
              />
              <circle cx={dx} cy={dy} r={3} fill={COLORS.secondary} opacity={0.9} />
            </g>
          );
        })}
      </svg>

      {/* centre Core node */}
      <div
        style={{
          position: 'absolute',
          left: cx - 60,
          top: cy - 60,
          transform: `scale(${coreEntry * corePulse})`,
          zIndex: 5,
        }}
      >
        <AnimatedGlowBorder color1={COLORS.secondary} color2={COLORS.accent} borderRadius={60} speed={1.5}>
          <div
            style={{
              width: 118,
              height: 118,
              borderRadius: 59,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              flexDirection: 'column',
              gap: 2,
            }}
          >
            <div style={{ fontSize: 24 }}>🧠</div>
            <div style={{ fontSize: 14, fontWeight: 700, color: COLORS.white }}>Core</div>
          </div>
        </AnimatedGlowBorder>
      </div>

      {/* orbiting agent nodes */}
      {agents.map((a, i) => {
        const angle = (i / agents.length) * Math.PI * 2 - Math.PI / 2 + frame * 0.008;
        const ax = cx + Math.cos(angle) * orbit;
        const ay = cy + Math.sin(angle) * orbit * 0.55;
        const depth = Math.sin(angle + Math.PI / 2);
        const nodeScale = 0.75 + depth * 0.25;
        const zIdx = depth > 0 ? 10 : 1;

        const nodeEntry = spring({ frame: frame - 15 - i * 8, fps, config: SPRING.bouncy });
        const checkEntry = spring({ frame: frame - 55 - i * 7, fps, config: SPRING.snappy });
        const ringOff = (frame * 2 + i * 60) % 283;

        return (
          <div
            key={i}
            style={{
              position: 'absolute',
              left: ax - 45,
              top: ay - 45,
              width: 90,
              height: 90,
              transform: `scale(${nodeScale * nodeEntry})`,
              opacity: nodeEntry,
              zIndex: zIdx,
            }}
          >
            {/* spinning ring */}
            <svg
              style={{
                position: 'absolute',
                left: -8,
                top: -8,
                width: 106,
                height: 106,
                pointerEvents: 'none',
              }}
            >
              <circle
                cx={53}
                cy={53}
                r={48}
                fill="none"
                stroke={COLORS.secondary}
                strokeWidth={1.5}
                strokeDasharray="25 70"
                strokeDashoffset={ringOff}
                opacity={0.5}
              />
            </svg>

            {/* node pill */}
            <GlassCard
              padding={0}
              delay={0}
              animateFrom="none"
              borderColor={`${COLORS.secondary}50`}
              style={{
                width: 90,
                height: 90,
                borderRadius: 45,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                flexDirection: 'column',
              }}
            >
              <div style={{ fontSize: 20 }}>{a.icon}</div>
              <div style={{ fontSize: 10, fontWeight: 600, color: COLORS.white, marginTop: 2 }}>
                {a.name}
              </div>
              {checkEntry > 0.1 && (
                <div
                  style={{ fontSize: 14, color: COLORS.green, transform: `scale(${checkEntry})`, marginTop: 1 }}
                >
                  ✓
                </div>
              )}
            </GlassCard>
          </div>
        );
      })}

      <ParticleField count={25} color={COLORS.secondary} drift="up" seed={77} />
    </div>
  );
};

/* ═══════════════════════════════════════════════════════════════
   7d  Memory System  (105 frames ≈ 3.5 s)
   ═══════════════════════════════════════════════════════════════ */
const MemorySystem: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

  const timelineLeft = 200;
  const timelineRight = 1720;
  const timelineW = timelineRight - timelineLeft;
  const timelineY = 580;

  const drawProg = interpolate(frame, [5, 60], [0, 1], {
    extrapolateLeft: 'clamp',
    extrapolateRight: 'clamp',
  });

  const nodes = [
    { pct: 0.1, label: 'Jan 15', detail: 'Client prefers email' },
    { pct: 0.3, label: 'Feb 3', detail: 'Pricing updated' },
    { pct: 0.5, label: 'Mar 12', detail: 'New workflow added' },
    { pct: 0.7, label: 'Apr 8', detail: 'Team expanded' },
    { pct: 0.9, label: 'May 1', detail: 'Revenue milestone' },
  ];

  const currentPulse = 0.8 + Math.sin(frame * 0.12) * 0.2;
  const currentScale = 1 + Math.sin(frame * 0.1) * 0.15;

  return (
    <div style={{ width: 1920, height: 1080, position: 'relative', overflow: 'hidden', fontFamily: FONT }}>
      <MeshBackground color1={COLORS.primary} color2={COLORS.accent} intensity={0.18} />

      {/* title */}
      <div style={{ position: 'absolute', top: 40, width: '100%', textAlign: 'center' }}>
        <KineticText
          text="Persistent memory. Learns over time."
          highlightWords={['memory.', 'Learns']}
          highlightColor={COLORS.primary}
          fontSize={36}
          animationType="blur"
        />
      </div>

      {/* animated gradient timeline */}
      <div
        style={{
          position: 'absolute',
          left: timelineLeft,
          top: timelineY,
          width: timelineW * drawProg,
          height: 4,
          background: `linear-gradient(90deg, ${COLORS.primary}, ${COLORS.secondary}, ${COLORS.accent})`,
          borderRadius: 2,
          boxShadow: `0 0 20px ${COLORS.primary}30`,
        }}
      />

      {/* memory node cards + dots */}
      {nodes.map((n, i) => {
        const nodeX = timelineLeft + n.pct * timelineW;
        const nodeEntry = spring({ frame: frame - 15 - i * 10, fps, config: SPRING.bouncy });
        const dotGlow = 0.6 + Math.sin(frame * 0.1 + i * 1.5) * 0.4;

        return (
          <div
            key={i}
            style={{
              position: 'absolute',
              left: nodeX - 75,
              top: timelineY - 200,
              textAlign: 'center',
            }}
          >
            {/* card */}
            <div
              style={{
                transform: `scale(${nodeEntry}) translateY(${(1 - nodeEntry) * 30}px)`,
                opacity: nodeEntry,
              }}
            >
              <GlassCard
                delay={0}
                padding={14}
                animateFrom="none"
                borderColor={`${COLORS.primary}30`}
                glowColor={COLORS.primary}
                style={{ width: 150, borderRadius: 14 }}
              >
                <div style={{ fontSize: 11, color: COLORS.gray, fontWeight: 600 }}>{n.label}</div>
                <div
                  style={{
                    fontSize: 13,
                    color: COLORS.white,
                    fontWeight: 600,
                    marginTop: 4,
                    lineHeight: 1.3,
                  }}
                >
                  {n.detail}
                </div>
              </GlassCard>
            </div>

            {/* connector line */}
            <div
              style={{
                width: 2,
                height: 30,
                background: `${COLORS.primary}40`,
                margin: '4px auto 0',
                opacity: nodeEntry,
              }}
            />

            {/* glowing dot */}
            <div
              style={{
                width: 14,
                height: 14,
                borderRadius: '50%',
                background: COLORS.primary,
                margin: '0 auto',
                boxShadow: `0 0 20px ${COLORS.primary}${Math.round(dotGlow * 255)
                  .toString(16)
                  .padStart(2, '0')}`,
                opacity: nodeEntry,
                transform: `scale(${nodeEntry})`,
              }}
            />
          </div>
        );
      })}

      {/* pulsing "current" indicator */}
      <div
        style={{
          position: 'absolute',
          left: timelineRight - 8,
          top: timelineY - 8,
          width: 16,
          height: 16,
          borderRadius: '50%',
          background: COLORS.accent,
          boxShadow: `0 0 25px ${COLORS.accent}60`,
          opacity:
            interpolate(frame, [55, 65], [0, 1], {
              extrapolateLeft: 'clamp',
              extrapolateRight: 'clamp',
            }) * currentPulse,
          transform: `scale(${currentScale})`,
        }}
      />

      <ParticleField count={20} color={COLORS.accent} drift="none" seed={55} />
    </div>
  );
};

/* ═══════════════════════════════════════════════════════════════
   Main Scene 7 wrapper (420 frames total)
   ═══════════════════════════════════════════════════════════════ */
export const Scene7PowerFeatures: React.FC = () => {
  const SUB = 105;
  return (
    <div style={{ width: 1920, height: 1080, position: 'relative' }}>
      <Sequence from={0} durationInFrames={SUB}>
        <PhoneMonitor />
      </Sequence>
      <Sequence from={SUB} durationInFrames={SUB}>
        <BatchGeneration />
      </Sequence>
      <Sequence from={SUB * 2} durationInFrames={SUB}>
        <AgentFactory />
      </Sequence>
      <Sequence from={SUB * 3} durationInFrames={SUB}>
        <MemorySystem />
      </Sequence>
    </div>
  );
};
