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 { AnimatedGlowBorder } from '../components/GlassCard';
import { KineticText } from '../components/KineticText';
import {
  DiscordIcon,
  TelegramIcon,
  SlackIcon,
  WhatsAppIcon,
  MessageIcon,
  WebIcon,
  SmsIcon,
} from '../components/ChannelIcons';

/* ─── Channel data ─── */
const channels = [
  { name: 'Discord', color: '#5865f2', Icon: DiscordIcon },
  { name: 'iMessage', color: '#34c759', Icon: MessageIcon },
  { name: 'Telegram', color: '#26a5e4', Icon: TelegramIcon },
  { name: 'Slack', color: '#e01e5a', Icon: SlackIcon },
  { name: 'WhatsApp', color: '#25d366', Icon: WhatsAppIcon },
  { name: 'SMS', color: '#ff6d5a', Icon: SmsIcon },
  { name: 'Web', color: '#7c3aed', Icon: WebIcon },
];

const chatBubbles = [
  { channelIdx: 0, text: '"Schedule all meetings for next week"', offsetX: 130, offsetY: -50 },
  { channelIdx: 2, text: '"Send Q4 report to the team"', offsetX: -200, offsetY: 35 },
  { channelIdx: 4, text: '"Update CRM with new leads"', offsetX: 140, offsetY: 30 },
];

const CX = 960;
const CY = 490;
const RADIUS = 300;

/* ─── Data packets: glowing dots traveling along connection lines ─── */
const DataPackets: React.FC = () => {
  const frame = useCurrentFrame();
  const packetStart = 90;

  if (frame < packetStart) return null;

  return (
    <>
      {channels.map((ch, i) => {
        const angle = (i / channels.length) * Math.PI * 2 - Math.PI / 2;
        const tx = CX + Math.cos(angle) * RADIUS;
        const ty = CY + Math.sin(angle) * RADIUS;

        // Multiple packets per line, offset in time
        return [0, 30, 60].map((offset, j) => {
          const packetFrame = frame - packetStart - i * 6 - offset;
          const cycle = 50; // frames per full trip
          const t = ((packetFrame % cycle) + cycle) % cycle;
          const progress = t / cycle;

          const px = tx + (CX - tx) * progress;
          const py = ty + (CY - ty) * progress;

          const packetOpacity =
            packetFrame > 0
              ? interpolate(progress, [0, 0.1, 0.9, 1], [0, 0.8, 0.8, 0], {
                  extrapolateLeft: 'clamp',
                  extrapolateRight: 'clamp',
                })
              : 0;

          return (
            <div
              key={`${i}-${j}`}
              style={{
                position: 'absolute',
                left: px - 3,
                top: py - 3,
                width: 6,
                height: 6,
                borderRadius: '50%',
                background: ch.color,
                opacity: packetOpacity,
                boxShadow: `0 0 10px ${ch.color}, 0 0 20px ${ch.color}80`,
                pointerEvents: 'none',
              }}
            />
          );
        });
      })}
    </>
  );
};

/* ─── Main Scene ─── */
export const Scene4MultiChannel: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

  /* Center hub */
  const hubScale = spring({
    frame,
    fps,
    config: SPRING.smooth,
  });

  const pulse = 1 + Math.sin(frame * 0.08) * 0.04;

  /* Center glow ring */
  const coreGlow = 0.4 + Math.sin(frame * 0.1) * 0.2;

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

      <ParticleField count={45} color={COLORS.white} drift="up" seed={55} />

      {/* Title */}
      <div
        style={{
          position: 'absolute',
          top: 45,
          width: '100%',
          display: 'flex',
          justifyContent: 'center',
        }}
      >
        <KineticText
          text="One AI. Every Channel."
          fontSize={48}
          fontWeight={700}
          color={COLORS.white}
          highlightWords={['Every', 'Channel.']}
          highlightColor={COLORS.primary}
          startDelay={0}
          staggerFrames={5}
          animationType="slideUp"
        />
      </div>

      {/* Connection lines SVG */}
      <svg
        style={{ position: 'absolute', top: 0, left: 0, width: 1920, height: 1080 }}
      >
        {channels.map((ch, i) => {
          const angle = (i / channels.length) * Math.PI * 2 - Math.PI / 2;
          const tx = CX + Math.cos(angle) * RADIUS;
          const ty = CY + Math.sin(angle) * RADIUS;

          const lineDelay = 30 + i * 8;
          const lineLength = RADIUS;
          const lineProgress = interpolate(
            frame - lineDelay,
            [0, 30],
            [lineLength, 0],
            { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' }
          );

          const lineOpacity = interpolate(frame - lineDelay, [0, 10], [0, 0.5], {
            extrapolateLeft: 'clamp',
            extrapolateRight: 'clamp',
          });

          return (
            <line
              key={i}
              x1={CX}
              y1={CY}
              x2={tx}
              y2={ty}
              stroke={ch.color}
              strokeWidth={2}
              strokeDasharray={lineLength}
              strokeDashoffset={lineProgress}
              opacity={lineOpacity}
            />
          );
        })}
      </svg>

      {/* Center hub with animated glow border */}
      <div
        style={{
          position: 'absolute',
          left: CX - 65,
          top: CY - 65,
          width: 130,
          height: 130,
          transform: `scale(${hubScale * pulse})`,
        }}
      >
        <AnimatedGlowBorder
          color1={COLORS.primary}
          color2={COLORS.secondary}
          borderRadius={65}
          speed={1.5}
          style={{ width: 130, height: 130 }}
        >
          <div
            style={{
              width: '100%',
              height: '100%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              position: 'relative',
            }}
          >
            {/* Pulsing core glow */}
            <div
              style={{
                position: 'absolute',
                width: 60,
                height: 60,
                borderRadius: '50%',
                background: `radial-gradient(circle, ${COLORS.primary}${Math.round(coreGlow * 255).toString(16).padStart(2, '0')} 0%, transparent 70%)`,
              }}
            />
            <span
              style={{
                fontSize: 40,
                fontWeight: 800,
                color: COLORS.white,
                position: 'relative',
                zIndex: 1,
              }}
            >
              AI
            </span>
          </div>
        </AnimatedGlowBorder>
      </div>

      {/* Channel nodes */}
      {channels.map((ch, i) => {
        const angle = (i / channels.length) * Math.PI * 2 - Math.PI / 2;

        /* Floating / breathing motion */
        const breathX = Math.sin(frame * 0.025 + i * 1.3) * 8;
        const breathY = Math.cos(frame * 0.02 + i * 0.9) * 6;

        const tx = CX + Math.cos(angle) * RADIUS + breathX;
        const ty = CY + Math.sin(angle) * RADIUS + breathY;

        const nodeDelay = 15 + i * 8;
        const nodeScale = spring({
          frame: frame - nodeDelay,
          fps,
          config: SPRING.bouncy,
        });

        return (
          <div
            key={i}
            style={{
              position: 'absolute',
              left: tx - 42,
              top: ty - 42,
              width: 84,
              height: 84,
              borderRadius: '50%',
              transform: `scale(${nodeScale})`,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              background: `${ch.color}20`,
              border: `1.5px solid ${ch.color}50`,
              boxShadow: `0 0 25px ${ch.color}30, inset 0 0 15px ${ch.color}10`,
            }}
          >
            <ch.Icon size={36} color={ch.color} />
          </div>
        );
      })}

      {/* Data packets */}
      <DataPackets />

      {/* Chat bubbles */}
      {chatBubbles.map((bubble, i) => {
        const ch = channels[bubble.channelIdx];
        const angle = (bubble.channelIdx / channels.length) * Math.PI * 2 - Math.PI / 2;

        const breathX = Math.sin(frame * 0.025 + bubble.channelIdx * 1.3) * 8;
        const breathY = Math.cos(frame * 0.02 + bubble.channelIdx * 0.9) * 6;

        const bx = CX + Math.cos(angle) * RADIUS + bubble.offsetX + breathX;
        const by = CY + Math.sin(angle) * RADIUS + bubble.offsetY + breathY;

        const bubbleDelay = 120 + i * 18;
        const bubbleScale = spring({
          frame: frame - bubbleDelay,
          fps,
          config: SPRING.bouncy,
        });

        return (
          <div
            key={`bubble-${i}`}
            style={{
              position: 'absolute',
              left: bx,
              top: by,
              ...GLASS_CARD,
              padding: '10px 16px',
              fontSize: 14,
              fontWeight: 500,
              color: COLORS.white,
              borderColor: `${ch.color}30`,
              transform: `scale(${bubbleScale})`,
              opacity: bubbleScale,
              whiteSpace: 'nowrap',
              maxWidth: 300,
            }}
          >
            {bubble.text}
          </div>
        );
      })}

      {/* Bottom subtitle */}
      <div
        style={{
          position: 'absolute',
          bottom: 55,
          width: '100%',
          textAlign: 'center',
          fontSize: 26,
          fontWeight: 400,
          color: COLORS.gray,
          opacity: interpolate(frame, [160, 185], [0, 1], {
            extrapolateLeft: 'clamp',
            extrapolateRight: 'clamp',
          }),
          transform: `translateY(${interpolate(frame, [160, 185], [15, 0], {
            extrapolateLeft: 'clamp',
            extrapolateRight: 'clamp',
          })}px)`,
        }}
      >
        Same AI brain. Any platform. Instant response.
      </div>
    </div>
  );
};
