import React from 'react';
import {
  AbsoluteFill,
  Sequence,
  useCurrentFrame,
  useVideoConfig,
  interpolate,
  spring,
  Img,
  staticFile,
  Easing,
} from 'remotion';

// Colors
const BRAND_BLUE = '#0ea5e9';
const BRAND_PURPLE = '#8b5cf6';
const DARK_BG = '#0a0a0a';

// Screenshot data with zoom targets (5 screenshots now)
// Zoom target coordinates are relative to CENTER of phone mockup
// x: negative = left, positive = right
// y: negative = up, positive = down
const screenshots = [
  {
    file: 'screenshots/step1-command.png',
    title: 'Give the Command',
    subtitle: 'Start a call with a simple message',
    // Zoom to the !call command and Buba response (lower middle of image)
    zoomTarget: { x: 0, y: 0.15, scale: 2.0 },
  },
  {
    file: 'screenshots/step2-call-started.png',
    title: 'Call Connects',
    subtitle: 'See the call status in real-time',
    // Zoom to the green "Call Started" embed (upper portion)
    zoomTarget: { x: 0, y: -0.18, scale: 2.2 },
  },
  {
    file: 'screenshots/step3-live-chat.png', 
    title: 'Watch Live',
    subtitle: 'Real-time transcription as it happens',
    // Zoom to "Ask who his cats are" prompt (upper-middle area)
    zoomTarget: { x: 0, y: -0.12, scale: 2.0 },
  },
  {
    file: 'screenshots/step4-user-prompt.png',
    title: 'Guide the AI',
    subtitle: 'Send prompts mid-conversation',
    // Zoom to "Ask why he's so awesome" prompt (middle area)
    zoomTarget: { x: 0, y: 0.05, scale: 2.2 },
  },
  {
    file: 'screenshots/step5-transcript.png',
    title: 'Get the Transcript',
    subtitle: 'Full record when the call ends',
    // Zoom to the Full Transcript and Call Ended embed (lower area)
    zoomTarget: { x: 0, y: 0.22, scale: 1.9 },
  },
];

// Timing constants (in frames at 30fps)
const FRAMES_PER_SCREENSHOT = 150; // 5 seconds each
const ZOOM_IN_DURATION = 40; // 1.33s to zoom in
const ZOOM_HOLD_DURATION = 70; // 2.33s hold
const ZOOM_OUT_DURATION = 40; // 1.33s to zoom out
const OUTRO_START = screenshots.length * FRAMES_PER_SCREENSHOT;
const OUTRO_DURATION = 150; // 5 seconds
const TOTAL_DURATION = OUTRO_START + OUTRO_DURATION;

// Phone Mockup Component
const PhoneMockup: React.FC<{
  screenshot: string;
  index: number;
  isActive: boolean;
  activeProgress: number;
  zoomTarget: { x: number; y: number; scale: number };
  totalScreenshots: number;
}> = ({ screenshot, index, isActive, activeProgress, zoomTarget, totalScreenshots }) => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  
  // Calculate glow and lift based on active state
  const glowIntensity = isActive 
    ? interpolate(activeProgress, [0, 0.1, 0.9, 1], [0, 1, 1, 0], { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' })
    : 0;
  
  const lift = isActive
    ? interpolate(activeProgress, [0, 0.1, 0.9, 1], [0, -25, -25, 0], { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' })
    : 0;
  
  const scale = isActive
    ? interpolate(activeProgress, [0, 0.1, 0.9, 1], [1, 1.08, 1.08, 1], { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' })
    : 1;

  // Phone dimensions - adjusted for 5 phones
  const phoneWidth = 240;
  const phoneHeight = 500;
  const spacing = 30;
  const totalWidth = totalScreenshots * phoneWidth + (totalScreenshots - 1) * spacing;
  const startX = (1920 - totalWidth) / 2;
  const x = startX + index * (phoneWidth + spacing);
  
  return (
    <div
      style={{
        position: 'absolute',
        left: x,
        top: '50%',
        transform: `translateY(-50%) translateY(${lift}px) scale(${scale})`,
        transition: 'transform 0.1s ease-out',
      }}
    >
      {/* Glow effect */}
      <div
        style={{
          position: 'absolute',
          inset: -20,
          borderRadius: 50,
          background: `radial-gradient(ellipse at center, ${BRAND_BLUE}60 0%, transparent 70%)`,
          opacity: glowIntensity,
          filter: 'blur(20px)',
          pointerEvents: 'none',
        }}
      />
      
      {/* Phone frame */}
      <div
        style={{
          width: phoneWidth,
          height: phoneHeight,
          borderRadius: 28,
          background: '#1a1a1a',
          padding: 6,
          boxShadow: isActive 
            ? `0 20px 60px -10px rgba(0,0,0,0.8), 0 0 ${30 * glowIntensity}px ${BRAND_BLUE}50`
            : '0 10px 40px -10px rgba(0,0,0,0.5)',
          border: isActive ? `2px solid ${BRAND_BLUE}40` : '2px solid #333',
        }}
      >
        <div
          style={{
            width: '100%',
            height: '100%',
            borderRadius: 22,
            overflow: 'hidden',
            background: '#000',
          }}
        >
          <Img
            src={staticFile(screenshot)}
            style={{
              width: '100%',
              height: '100%',
              objectFit: 'cover',
            }}
          />
        </div>
      </div>
    </div>
  );
};

// Main Scene with all screenshots
const MainScene: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  
  // Determine which screenshot is active
  const activeIndex = Math.min(
    Math.floor(frame / FRAMES_PER_SCREENSHOT),
    screenshots.length - 1
  );
  
  // Progress within current screenshot (0-1)
  const progressInCurrent = (frame % FRAMES_PER_SCREENSHOT) / FRAMES_PER_SCREENSHOT;
  
  // Get zoom parameters for active screenshot
  const activeScreenshot = screenshots[activeIndex];
  const { x: zoomX, y: zoomY, scale: zoomScale } = activeScreenshot.zoomTarget;
  
  // Zoom timing within each screenshot segment
  const localFrame = frame % FRAMES_PER_SCREENSHOT;
  
  // Zoom in -> hold -> zoom out
  const zoomProgress = interpolate(
    localFrame,
    [0, ZOOM_IN_DURATION, ZOOM_IN_DURATION + ZOOM_HOLD_DURATION, FRAMES_PER_SCREENSHOT],
    [0, 1, 1, 0],
    { extrapolateLeft: 'clamp', extrapolateRight: 'clamp', easing: Easing.inOut(Easing.cubic) }
  );
  
  // Calculate camera position based on active phone position
  // Phone dimensions
  const phoneWidth = 240;
  const spacing = 30;
  const totalWidth = screenshots.length * phoneWidth + (screenshots.length - 1) * spacing;
  const startX = (1920 - totalWidth) / 2;
  const activePhoneX = startX + activeIndex * (phoneWidth + spacing) + phoneWidth / 2;
  
  // Camera offset from center of screen
  const screenCenterX = 1920 / 2;
  const targetCameraX = -(activePhoneX - screenCenterX);
  
  // Camera transform - move camera to center on active phone, then zoom into detail
  const cameraScale = interpolate(zoomProgress, [0, 1], [1, zoomScale]);
  const cameraX = interpolate(zoomProgress, [0, 1], [0, targetCameraX + zoomX * 250]);
  const cameraY = interpolate(zoomProgress, [0, 1], [0, zoomY * 350]);
  
  // Title animation
  const titleOpacity = interpolate(
    localFrame,
    [0, 20, FRAMES_PER_SCREENSHOT - 20, FRAMES_PER_SCREENSHOT],
    [0, 1, 1, 0],
    { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' }
  );
  
  const titleY = spring({
    frame: localFrame,
    fps,
    from: 30,
    to: 0,
    durationInFrames: 30,
  });

  return (
    <AbsoluteFill style={{ backgroundColor: DARK_BG }}>
      {/* Subtle gradient background */}
      <div
        style={{
          position: 'absolute',
          inset: 0,
          background: `radial-gradient(ellipse at 50% 100%, ${BRAND_BLUE}15 0%, transparent 50%)`,
        }}
      />
      
      {/* Camera container for zoom effects */}
      <div
        style={{
          position: 'absolute',
          inset: 0,
          transform: `scale(${cameraScale}) translate(${cameraX}px, ${cameraY}px)`,
          transformOrigin: 'center center',
        }}
      >
        {/* All phone mockups */}
        {screenshots.map((ss, index) => (
          <PhoneMockup
            key={index}
            screenshot={ss.file}
            index={index}
            isActive={index === activeIndex}
            activeProgress={index === activeIndex ? progressInCurrent : 0}
            zoomTarget={ss.zoomTarget}
            totalScreenshots={screenshots.length}
          />
        ))}
      </div>
      
      {/* Title overlay */}
      <div
        style={{
          position: 'absolute',
          bottom: 80,
          left: 0,
          right: 0,
          textAlign: 'center',
          opacity: titleOpacity,
          transform: `translateY(${titleY}px)`,
        }}
      >
        {/* Step indicator */}
        <div
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            gap: 10,
            marginBottom: 16,
          }}
        >
          {screenshots.map((_, i) => (
            <div
              key={i}
              style={{
                width: 32,
                height: 4,
                borderRadius: 2,
                background: i === activeIndex ? BRAND_BLUE : '#333',
                transition: 'background 0.3s',
              }}
            />
          ))}
        </div>
        
        <h2
          style={{
            fontSize: 44,
            fontWeight: 700,
            color: 'white',
            margin: 0,
            fontFamily: 'Inter, system-ui, sans-serif',
          }}
        >
          {activeScreenshot.title}
        </h2>
        <p
          style={{
            fontSize: 22,
            color: '#a1a1aa',
            margin: '10px 0 0',
            fontFamily: 'Inter, system-ui, sans-serif',
          }}
        >
          {activeScreenshot.subtitle}
        </p>
      </div>
      
      {/* Header */}
      <div
        style={{
          position: 'absolute',
          top: 40,
          left: 0,
          right: 0,
          textAlign: 'center',
        }}
      >
        <h1
          style={{
            fontSize: 32,
            fontWeight: 800,
            background: `linear-gradient(135deg, ${BRAND_BLUE}, ${BRAND_PURPLE})`,
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            margin: 0,
            fontFamily: 'Inter, system-ui, sans-serif',
          }}
        >
          ClawdBot AI Phone Calls
        </h1>
      </div>
    </AbsoluteFill>
  );
};

// Outro Scene
const OutroScene: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  
  const opacity = interpolate(frame, [0, 30], [0, 1], { extrapolateRight: 'clamp' });
  const scale = spring({ frame, fps, from: 0.9, to: 1, durationInFrames: 40 });
  const ctaOpacity = interpolate(frame, [45, 75], [0, 1], { extrapolateRight: 'clamp' });
  const ctaY = spring({ frame: Math.max(0, frame - 45), fps, from: 30, to: 0, durationInFrames: 30 });

  return (
    <AbsoluteFill style={{ backgroundColor: DARK_BG, justifyContent: 'center', alignItems: 'center' }}>
      {/* Gradient background */}
      <div
        style={{
          position: 'absolute',
          inset: 0,
          background: `linear-gradient(135deg, ${BRAND_BLUE}15 0%, ${BRAND_PURPLE}15 100%)`,
          opacity,
        }}
      />
      
      <div
        style={{
          opacity,
          transform: `scale(${scale})`,
          textAlign: 'center',
        }}
      >
        <h1
          style={{
            fontSize: 90,
            fontWeight: 800,
            background: `linear-gradient(135deg, ${BRAND_BLUE}, ${BRAND_PURPLE})`,
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            margin: 0,
            fontFamily: 'Inter, system-ui, sans-serif',
          }}
        >
          ClawdBot
        </h1>
        
        <p
          style={{
            fontSize: 32,
            color: 'white',
            marginTop: 16,
            fontFamily: 'Inter, system-ui, sans-serif',
          }}
        >
          Your AI that actually <em>does</em> things
        </p>
        
        {/* CTA */}
        <div
          style={{
            marginTop: 50,
            opacity: ctaOpacity,
            transform: `translateY(${ctaY}px)`,
          }}
        >
          <div
            style={{
              display: 'inline-block',
              padding: '20px 48px',
              background: `linear-gradient(135deg, ${BRAND_BLUE}, ${BRAND_PURPLE})`,
              borderRadius: 16,
              fontSize: 28,
              fontWeight: 600,
              color: 'white',
              fontFamily: 'Inter, system-ui, sans-serif',
            }}
          >
            Try it free at clawd.bot
          </div>
        </div>
        
        {/* Feature pills */}
        <div
          style={{
            marginTop: 40,
            display: 'flex',
            gap: 16,
            justifyContent: 'center',
            opacity: ctaOpacity,
          }}
        >
          {['📞 AI Phone Calls', '👁️ Real-Time View', '💬 Guide Mid-Call'].map((text, i) => (
            <div
              key={i}
              style={{
                padding: '10px 20px',
                background: '#1a1a1a',
                borderRadius: 20,
                border: '1px solid #333',
                fontSize: 18,
                color: '#a1a1aa',
                fontFamily: 'Inter, system-ui, sans-serif',
              }}
            >
              {text}
            </div>
          ))}
        </div>
      </div>
    </AbsoluteFill>
  );
};

// Main Composition
export const ClawdBotCalls: React.FC = () => {
  return (
    <AbsoluteFill style={{ backgroundColor: DARK_BG }}>
      {/* Main scene with all screenshots */}
      <Sequence from={0} durationInFrames={OUTRO_START}>
        <MainScene />
      </Sequence>
      
      {/* Outro */}
      <Sequence from={OUTRO_START} durationInFrames={OUTRO_DURATION}>
        <OutroScene />
      </Sequence>
    </AbsoluteFill>
  );
};
