import React from 'react';
import {
  useCurrentFrame,
  interpolate,
  spring,
  useVideoConfig,
} 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, FlipCounter } from '../components/KineticText';

/* ── Kanban column data ──────────────────────────────────────── */
const columns = [
  {
    title: 'Queued',
    color: COLORS.gray,
    cards: [
      { name: 'Toast POS MCP', tag: '54 tools' },
      { name: 'Wave MCP', tag: '38 tools' },
      { name: 'Gusto HR MCP', tag: '42 tools' },
    ],
  },
  {
    title: 'Building',
    color: COLORS.accent,
    cards: [
      { name: 'Pipedrive MCP', tag: '46 tools' },
      { name: 'Zendesk MCP', tag: '62 tools' },
    ],
  },
  {
    title: 'Testing',
    color: COLORS.secondary,
    cards: [
      { name: 'ServiceTitan MCP', tag: '71 tools' },
      { name: 'Jobber MCP', tag: '58 tools' },
    ],
  },
  {
    title: 'Shipped',
    color: COLORS.green,
    cards: [
      { name: 'GoHighLevel MCP', tag: '240+ tools' },
      { name: 'Twilio MCP', tag: '54 tools' },
      { name: 'CloseBot MCP', tag: '119 tools' },
      { name: 'Meta Ads MCP', tag: '55 tools' },
    ],
  },
];

/* ── AI agent icons ──────────────────────────────────────────── */
const agentEmojis = ['🤖', '⚡', '🧠', '🔧'];

/* ── Scene 6: AI Factory + Kanban ────────────────────────────── */
export const Scene6ProductTour: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

  // Board entry
  const boardEntry = spring({ frame: frame - 30, fps, config: SPRING.smooth });

  // Stats counters
  const projectCount = Math.min(30, Math.floor(
    interpolate(frame, [60, 150], [0, 30], {
      extrapolateLeft: 'clamp',
      extrapolateRight: 'clamp',
    })
  ));

  const toolCount = Math.min(643, Math.floor(
    interpolate(frame, [80, 180], [0, 643], {
      extrapolateLeft: 'clamp',
      extrapolateRight: 'clamp',
    })
  ));

  // Conveyor animation — cards shift right over time
  const conveyorShift = interpolate(frame, [200, 380], [0, 1], {
    extrapolateLeft: 'clamp',
    extrapolateRight: 'clamp',
  });

  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} />

      {/* ── Title ──────────────────────────────────────── */}
      <div style={{ position: 'absolute', top: 25, width: '100%', textAlign: 'center', zIndex: 5 }}>
        <KineticText
          text="The AI Factory — Mass-Producing MCP Projects"
          highlightWords={['AI', 'Factory']}
          highlightColor={COLORS.primary}
          fontSize={38}
          animationType="slideUp"
          staggerFrames={3}
        />
      </div>

      {/* ── Stats bar ──────────────────────────────────── */}
      <div
        style={{
          position: 'absolute',
          top: 90,
          width: '100%',
          display: 'flex',
          justifyContent: 'center',
          gap: 80,
          zIndex: 5,
        }}
      >
        {[
          { label: 'MCP Servers Built', val: projectCount, suffix: '+', color: COLORS.primary },
          { label: 'Total Tools', val: toolCount, suffix: '', color: COLORS.secondary },
          { label: 'AI Agents Active', val: 4, suffix: '', color: COLORS.accent },
        ].map((stat, i) => {
          const op = interpolate(frame, [40 + i * 10, 55 + i * 10], [0, 1], {
            extrapolateLeft: 'clamp',
            extrapolateRight: 'clamp',
          });
          return (
            <div key={i} style={{ textAlign: 'center', opacity: op }}>
              <div style={{ fontSize: 36, fontWeight: 800, color: stat.color, fontVariantNumeric: 'tabular-nums' }}>
                {stat.val.toLocaleString()}{stat.suffix}
              </div>
              <div style={{ fontSize: 13, color: COLORS.gray, marginTop: 2 }}>{stat.label}</div>
            </div>
          );
        })}
      </div>

      {/* ── Kanban Board ───────────────────────────────── */}
      <div
        style={{
          position: 'absolute',
          top: 175,
          left: 60,
          right: 60,
          bottom: 80,
          display: 'flex',
          gap: 20,
          opacity: boardEntry,
          transform: `translateY(${interpolate(boardEntry, [0, 1], [40, 0])}px)`,
          zIndex: 3,
        }}
      >
        {columns.map((col, ci) => {
          const colDelay = 40 + ci * 12;
          const colEntry = spring({ frame: frame - colDelay, fps, config: SPRING.smooth });

          // For "Shipped" column, cards slide in during conveyor phase
          const isShipped = ci === 3;

          return (
            <div
              key={ci}
              style={{
                flex: 1,
                display: 'flex',
                flexDirection: 'column',
                gap: 12,
                opacity: colEntry,
                transform: `translateY(${interpolate(colEntry, [0, 1], [30, 0])}px)`,
              }}
            >
              {/* Column header */}
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  padding: '10px 16px',
                  borderRadius: 12,
                  background: `${col.color}15`,
                  border: `1px solid ${col.color}30`,
                }}
              >
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div
                    style={{
                      width: 10,
                      height: 10,
                      borderRadius: '50%',
                      background: col.color,
                      boxShadow: `0 0 8px ${col.color}60`,
                    }}
                  />
                  <span style={{ fontSize: 15, fontWeight: 700, color: COLORS.white }}>{col.title}</span>
                </div>
                <span style={{ fontSize: 13, fontWeight: 600, color: col.color }}>{col.cards.length}</span>
              </div>

              {/* AI agent indicator for "Building" column */}
              {ci === 1 && (
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'center',
                    gap: 6,
                    padding: '4px 0',
                  }}
                >
                  {agentEmojis.map((emoji, ai) => {
                    const pulse = 0.85 + Math.sin(frame * 0.15 + ai * 1.5) * 0.15;
                    const agentOp = interpolate(frame, [80 + ai * 8, 90 + ai * 8], [0, 1], {
                      extrapolateLeft: 'clamp',
                      extrapolateRight: 'clamp',
                    });
                    return (
                      <div
                        key={ai}
                        style={{
                          fontSize: 18,
                          transform: `scale(${pulse})`,
                          opacity: agentOp,
                        }}
                      >
                        {emoji}
                      </div>
                    );
                  })}
                </div>
              )}

              {/* Cards */}
              {col.cards.map((card, ki) => {
                const cardDelay = colDelay + 15 + ki * 8;
                const cardEntry = spring({ frame: frame - cardDelay, fps, config: SPRING.snappy });

                // Card slide effect for conveyor
                const slideX = isShipped && ki >= 2
                  ? interpolate(conveyorShift, [0, 0.3 + ki * 0.15, 0.5 + ki * 0.15], [80, 80, 0], {
                      extrapolateLeft: 'clamp',
                      extrapolateRight: 'clamp',
                    })
                  : 0;
                const slideOp = isShipped && ki >= 2
                  ? interpolate(conveyorShift, [0.3 + ki * 0.1, 0.5 + ki * 0.1], [0, 1], {
                      extrapolateLeft: 'clamp',
                      extrapolateRight: 'clamp',
                    })
                  : 1;

                // Checkmark for shipped items
                const isComplete = isShipped;
                const checkOp = isComplete ? interpolate(frame, [cardDelay + 20, cardDelay + 28], [0, 1], {
                  extrapolateLeft: 'clamp',
                  extrapolateRight: 'clamp',
                }) : 0;

                // Breathing glow for building items
                const isBuilding = ci === 1;
                const buildGlow = isBuilding ? 0.3 + Math.sin(frame * 0.1 + ki * 2) * 0.2 : 0;

                return (
                  <div
                    key={ki}
                    style={{
                      transform: `scale(${interpolate(cardEntry, [0, 1], [0.85, 1])}) translateX(${slideX}px)`,
                      opacity: cardEntry * slideOp,
                    }}
                  >
                    <GlassCard
                      delay={0}
                      padding="14px 16px"
                      animateFrom="none"
                      borderColor={`${col.color}${isComplete ? '50' : '20'}`}
                      glowColor={isBuilding ? COLORS.accent : isComplete ? COLORS.green : undefined}
                      style={{
                        borderRadius: 14,
                        boxShadow: isBuilding
                          ? `0 0 ${20 + buildGlow * 30}px ${COLORS.accent}${Math.round(buildGlow * 100).toString(16).padStart(2, '0')}`
                          : undefined,
                      }}
                    >
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <div>
                          <div style={{ fontSize: 14, fontWeight: 600, color: COLORS.white }}>{card.name}</div>
                          <div style={{ fontSize: 11, color: col.color, marginTop: 3, fontWeight: 500 }}>{card.tag}</div>
                        </div>
                        {isComplete && checkOp > 0 && (
                          <div
                            style={{
                              width: 22,
                              height: 22,
                              borderRadius: '50%',
                              background: COLORS.green,
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              fontSize: 12,
                              color: COLORS.white,
                              opacity: checkOp,
                              transform: `scale(${interpolate(checkOp, [0, 1], [0.5, 1])})`,
                              boxShadow: `0 0 10px ${COLORS.green}50`,
                              flexShrink: 0,
                            }}
                          >
                            ✓
                          </div>
                        )}
                        {isBuilding && (
                          <div style={{ fontSize: 16, flexShrink: 0 }}>
                            {agentEmojis[ki % agentEmojis.length]}
                          </div>
                        )}
                      </div>
                    </GlassCard>
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>

      {/* ── Progress conveyor line at bottom ────────────── */}
      <div
        style={{
          position: 'absolute',
          bottom: 30,
          left: 60,
          right: 60,
          height: 3,
          background: `${COLORS.cardBorder}`,
          borderRadius: 2,
          zIndex: 4,
        }}
      >
        <div
          style={{
            height: '100%',
            width: `${interpolate(frame, [60, 380], [5, 100], {
              extrapolateLeft: 'clamp',
              extrapolateRight: 'clamp',
            })}%`,
            background: `linear-gradient(90deg, ${COLORS.primary}, ${COLORS.green})`,
            borderRadius: 2,
            boxShadow: `0 0 12px ${COLORS.primary}40`,
          }}
        />
        {/* Traveling dot on conveyor */}
        <div
          style={{
            position: 'absolute',
            top: -4,
            left: `${interpolate(frame, [60, 380], [5, 100], {
              extrapolateLeft: 'clamp',
              extrapolateRight: 'clamp',
            })}%`,
            width: 10,
            height: 10,
            borderRadius: '50%',
            background: COLORS.primary,
            boxShadow: `0 0 15px ${COLORS.primary}80`,
            transform: 'translateX(-50%)',
          }}
        />
      </div>

      <ParticleField count={25} color={`${COLORS.accent}50`} drift="up" seed={42} />
    </div>
  );
};
