import React from 'react';
import {
  AbsoluteFill,
  useCurrentFrame,
  useVideoConfig,
  interpolate,
  Easing,
} from 'remotion';

// ============ CONFIG ============
const USER_QUESTION = "What patterns do you see in my transaction data?";
const AI_RESPONSE = "Let me analyze your Stripe data and find insights...";

// ============ COLORS ============
const COLORS = {
  bg: '#0f0f1a',
  window: '#1a1a2e',
  titlebar: '#252540',
  border: '#2a2a4a',
  inputBg: '#12121f',
  text: '#e2e2f0',
  textMuted: '#8888aa',
  purple: '#6366f1',
  purpleEnd: '#8b5cf6',
  aiBubble: '#2a2a4a',
};

// ============ CANVAS DIMENSIONS ============
// The "world" is larger than viewport - camera moves across it
const CANVAS = {
  width: 2400,   // Large canvas
  height: 1600,
};

const VIEWPORT = {
  width: 1920,
  height: 1080,
};

// ============ POSITIONS ON CANVAS ============
// Where elements are located on the large canvas
const POSITIONS = {
  inputField: { x: 600, y: 1200 },      // Input field position
  userMessage: { x: 1400, y: 400 },     // User message (right side)
  aiMessage: { x: 200, y: 550 },        // AI message (left side)
  embed: { x: 600, y: 850 },            // Embed position (center-ish)
};

// ============ TIMING (30fps) ============
const T = {
  // Camera starts focused on input
  start: 0,
  
  // User starts typing
  userTypeStart: 15,
  userTypeEnd: 90,       // ~2.5s of typing
  
  // Zoom out to show sent message
  zoomOutStart: 100,
  zoomOutEnd: 130,
  
  // AI typing indicator
  aiThinkStart: 140,
  
  // Camera moves to AI response area
  panToAiStart: 150,
  panToAiEnd: 170,
  
  // AI starts typing
  aiTypeStart: 180,
  aiTypeEnd: 270,        // ~3s of typing
  
  // Zoom out for embed
  embedZoomStart: 290,
  embedAppear: 310,
  embedGrow: 340,
  
  // Hold
  end: 420,              // 14 seconds
};

// ============ TYPING LOGIC ============
const getTypedText = (frame: number, text: string, startFrame: number, charFrames: number = 2): string => {
  const elapsed = Math.max(0, frame - startFrame);
  const chars = Math.floor(elapsed / charFrames);
  return text.slice(0, Math.min(chars, text.length));
};

// ============ CURSOR ============
const Cursor: React.FC<{ visible: boolean }> = ({ visible }) => {
  const frame = useCurrentFrame();
  const blink = interpolate(frame % 20, [0, 10, 20], [1, 0, 1]);
  
  if (!visible) return null;
  
  return (
    <span style={{
      display: 'inline-block',
      width: 3,
      height: '1.2em',
      backgroundColor: COLORS.purple,
      marginLeft: 2,
      opacity: blink,
      verticalAlign: 'text-bottom',
    }} />
  );
};

// ============ TYPING INDICATOR ============
const TypingIndicator: React.FC = () => {
  const frame = useCurrentFrame();
  
  return (
    <div style={{
      display: 'flex',
      gap: 6,
      padding: '18px 24px',
      background: COLORS.aiBubble,
      borderRadius: 22,
      borderBottomLeftRadius: 6,
    }}>
      {[0, 1, 2].map((i) => (
        <div
          key={i}
          style={{
            width: 12,
            height: 12,
            backgroundColor: COLORS.purple,
            borderRadius: '50%',
            transform: `translateY(${interpolate((frame + i * 6) % 24, [0, 12, 24], [0, -10, 0])}px)`,
          }}
        />
      ))}
    </div>
  );
};

// ============ SPINNER ============
const Spinner: React.FC = () => {
  const frame = useCurrentFrame();
  return (
    <span style={{
      display: 'inline-block',
      width: 22,
      height: 22,
      border: `3px solid ${COLORS.border}`,
      borderTopColor: '#635BFF',
      borderRadius: '50%',
      transform: `rotate(${frame * 15}deg)`,
      marginRight: 14,
      verticalAlign: 'middle',
    }} />
  );
};

// ============ STRIPE EMBED ============
const StripeEmbed: React.FC<{ progress: number }> = ({ progress }) => {
  const scale = interpolate(progress, [0, 0.3, 1], [0.5, 0.6, 1], { extrapolateRight: 'clamp' });
  const opacity = interpolate(progress, [0, 0.2], [0, 1], { extrapolateRight: 'clamp' });
  
  const payments = [
    { email: 'john@example.com', amount: '$449.00', status: 'Ready to retry', bg: '#FFF8E6', color: '#9C6F19' },
    { email: 'sarah@company.co', amount: '$299.00', status: 'Card updated', bg: '#D7F7E0', color: '#0E6245' },
    { email: 'mike@startup.io', amount: '$499.00', status: 'Ready to retry', bg: '#FFF8E6', color: '#9C6F19' },
  ];

  return (
    <div style={{
      opacity,
      transform: `scale(${scale})`,
      transformOrigin: 'top left',
      marginTop: 20,
    }}>
      <div style={{
        background: '#FFFFFF',
        borderRadius: 16,
        overflow: 'hidden',
        width: 550,
        boxShadow: '0 8px 40px rgba(99, 91, 255, 0.25)',
      }}>
        <div style={{
          padding: '18px 22px',
          borderBottom: '1px solid #E3E8EE',
          display: 'flex',
          alignItems: 'center',
          gap: 14,
        }}>
          <div style={{
            background: '#635BFF',
            color: 'white',
            fontWeight: 700,
            fontSize: 13,
            padding: '7px 14px',
            borderRadius: 6,
          }}>stripe</div>
          <div>
            <div style={{ fontSize: 16, fontWeight: 600, color: '#1A1F36' }}>Payment Recovery</div>
            <div style={{ fontSize: 12, color: '#697386' }}>3 opportunities • $1,247 recoverable</div>
          </div>
        </div>
        
        <div style={{ padding: '10px 0' }}>
          {payments.map((p, i) => {
            const rowProgress = interpolate(progress, [0.4 + i * 0.1, 0.6 + i * 0.1], [0, 1], { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' });
            return (
              <div 
                key={i}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  padding: '14px 22px',
                  borderBottom: i < 2 ? '1px solid #E3E8EE' : 'none',
                  opacity: rowProgress,
                  transform: `translateX(${interpolate(rowProgress, [0, 1], [-20, 0])}px)`,
                }}
              >
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: '#1A1F36' }}>{p.email}</div>
                </div>
                <div style={{ fontSize: 15, fontWeight: 600, color: '#1A1F36', marginRight: 18 }}>{p.amount}</div>
                <div style={{
                  padding: '5px 12px',
                  borderRadius: 5,
                  fontSize: 12,
                  fontWeight: 500,
                  background: p.bg,
                  color: p.color,
                }}>{p.status}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

// ============ THE STATIC CANVAS (all content) ============
const ChatCanvas: React.FC = () => {
  const frame = useCurrentFrame();
  
  // User typing state
  const userText = getTypedText(frame, USER_QUESTION, T.userTypeStart, 1);
  const userTyping = frame >= T.userTypeStart && frame < T.userTypeEnd;
  const userDone = frame >= T.userTypeEnd;
  
  // AI typing state
  const aiText = getTypedText(frame, AI_RESPONSE, T.aiTypeStart, 1);
  const aiTyping = frame >= T.aiTypeStart && frame < T.aiTypeEnd;
  const aiDone = frame >= T.aiTypeEnd;
  
  // Embed state
  const embedProgress = frame >= T.embedAppear 
    ? interpolate(frame, [T.embedAppear, T.embedGrow], [0, 1], { extrapolateRight: 'clamp' })
    : 0;

  return (
    <div style={{
      width: CANVAS.width,
      height: CANVAS.height,
      background: COLORS.bg,
      position: 'relative',
    }}>
      {/* Background gradient */}
      <div style={{
        position: 'absolute',
        inset: 0,
        background: `
          radial-gradient(ellipse at 30% 20%, rgba(99, 91, 255, 0.12) 0%, transparent 50%),
          radial-gradient(ellipse at 70% 80%, rgba(118, 75, 162, 0.12) 0%, transparent 50%)
        `,
      }} />
      
      {/* Chat Window - positioned on canvas */}
      <div style={{
        position: 'absolute',
        left: 200,
        top: 150,
        width: 1800,
        height: 1200,
        background: COLORS.window,
        borderRadius: 24,
        boxShadow: '0 30px 100px rgba(0,0,0,0.6)',
        border: `1px solid ${COLORS.border}`,
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
      }}>
        {/* Title bar */}
        <div style={{
          height: 60,
          background: COLORS.titlebar,
          display: 'flex',
          alignItems: 'center',
          padding: '0 24px',
          borderBottom: `1px solid ${COLORS.border}`,
          flexShrink: 0,
        }}>
          <div style={{ display: 'flex', gap: 10 }}>
            <div style={{ width: 14, height: 14, borderRadius: '50%', background: '#ff5f57' }} />
            <div style={{ width: 14, height: 14, borderRadius: '50%', background: '#ffbd2e' }} />
            <div style={{ width: 14, height: 14, borderRadius: '50%', background: '#27ca40' }} />
          </div>
          <div style={{ flex: 1, textAlign: 'center', color: COLORS.textMuted, fontSize: 16 }}>
            AI Assistant
          </div>
          <div style={{ width: 60 }} />
        </div>
        
        {/* Messages area */}
        <div style={{
          flex: 1,
          padding: 36,
          display: 'flex',
          flexDirection: 'column',
          gap: 28,
        }}>
          {/* User message - only show after typing starts */}
          {frame >= T.zoomOutStart && (
            <div style={{
              alignSelf: 'flex-end',
              maxWidth: '65%',
              padding: '20px 28px',
              background: `linear-gradient(135deg, ${COLORS.purple}, ${COLORS.purpleEnd})`,
              color: COLORS.text,
              borderRadius: 24,
              borderBottomRightRadius: 8,
              fontSize: 22,
              lineHeight: 1.5,
            }}>
              {USER_QUESTION}
            </div>
          )}
          
          {/* AI typing indicator */}
          {frame >= T.aiThinkStart && frame < T.aiTypeStart && (
            <div style={{ alignSelf: 'flex-start' }}>
              <TypingIndicator />
            </div>
          )}
          
          {/* AI message */}
          {frame >= T.aiTypeStart && (
            <div style={{
              alignSelf: 'flex-start',
              maxWidth: '75%',
            }}>
              <div style={{
                padding: '20px 28px',
                background: COLORS.aiBubble,
                color: COLORS.text,
                borderRadius: 24,
                borderBottomLeftRadius: 8,
                fontSize: 22,
                lineHeight: 1.5,
              }}>
                {frame >= T.embedZoomStart ? (
                  <><Spinner />Analyzing your payment data...</>
                ) : (
                  <>
                    {aiText}
                    <Cursor visible={aiTyping} />
                  </>
                )}
              </div>
              
              {/* Stripe Embed */}
              {frame >= T.embedAppear && (
                <StripeEmbed progress={embedProgress} />
              )}
            </div>
          )}
        </div>
        
        {/* Input area */}
        <div style={{
          padding: '20px 28px 28px',
          borderTop: `1px solid ${COLORS.border}`,
          flexShrink: 0,
        }}>
          <div style={{
            display: 'flex',
            gap: 16,
            alignItems: 'center',
            background: COLORS.inputBg,
            border: `2px solid ${userTyping ? '#4a4a7a' : COLORS.border}`,
            borderRadius: 16,
            padding: '16px 22px',
          }}>
            <span style={{
              flex: 1,
              color: userText ? COLORS.text : COLORS.textMuted,
              fontSize: 20,
            }}>
              {frame < T.zoomOutStart ? (
                <>
                  {userText || 'Type a message...'}
                  <Cursor visible={userTyping && userText.length > 0} />
                </>
              ) : (
                'Type a message...'
              )}
            </span>
            <div style={{
              width: 50,
              height: 50,
              background: `linear-gradient(135deg, ${COLORS.purple}, ${COLORS.purpleEnd})`,
              borderRadius: 12,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2">
                <path d="M22 2L11 13M22 2L15 22L11 13L2 9L22 2Z"/>
              </svg>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============ MAIN COMPOSITION WITH DOLLY CAMERA ============
export const StripeDollyDemo: React.FC = () => {
  const frame = useCurrentFrame();
  
  // ========== CAMERA KEYFRAMES ==========
  // Camera position is where the viewport's TOP-LEFT corner is on the canvas
  // Zoom affects how much of the canvas we see
  
  // Calculate text width for following (rough estimate: 12px per char at this font size)
  const userTextLength = getTypedText(frame, USER_QUESTION, T.userTypeStart, 1).length;
  const aiTextLength = getTypedText(frame, AI_RESPONSE, T.aiTypeStart, 1).length;
  
  // Camera X follows the typing cursor
  const typingFollowX = frame >= T.userTypeStart && frame < T.userTypeEnd
    ? Math.min(userTextLength * 10, 200)  // Follow but cap it
    : 0;
  
  const aiTypingFollowX = frame >= T.aiTypeStart && frame < T.aiTypeEnd
    ? Math.min(aiTextLength * 8, 150)
    : 0;
  
  // ZOOM: Higher = more zoomed in (seeing less of canvas)
  const zoom = interpolate(
    frame,
    [
      T.start,           // Start zoomed in on input
      T.userTypeStart,   // Stay zoomed while typing
      T.zoomOutStart,    // Begin zoom out
      T.zoomOutEnd,      // Zoomed out to see message
      T.panToAiEnd,      // Pan complete
      T.aiTypeStart,     // Zoom in on AI text
      T.aiTypeEnd,       // Done typing
      T.embedZoomStart,  // Zoom out for embed
      T.embedGrow,       // Full view
    ],
    [2.2, 2.2, 1.6, 1.1, 1.1, 1.5, 1.5, 1.0, 1.0],
    { extrapolateLeft: 'clamp', extrapolateRight: 'clamp', easing: Easing.inOut(Easing.cubic) }
  );
  
  // Camera X position (where to look on canvas)
  const cameraX = interpolate(
    frame,
    [
      T.start,
      T.userTypeStart,
      T.zoomOutStart,
      T.zoomOutEnd,
      T.panToAiStart,
      T.panToAiEnd,
      T.embedZoomStart,
      T.embedGrow,
    ],
    [
      350 + typingFollowX,   // Start at input field, follow typing
      350 + typingFollowX,
      450,                    // Center-ish for message
      300,
      200,                    // Pan left for AI
      100 + aiTypingFollowX,
      200,                    // Center for embed
      200,
    ],
    { extrapolateLeft: 'clamp', extrapolateRight: 'clamp', easing: Easing.inOut(Easing.cubic) }
  );
  
  // Camera Y position
  const cameraY = interpolate(
    frame,
    [
      T.start,
      T.userTypeEnd,
      T.zoomOutStart,
      T.zoomOutEnd,
      T.panToAiEnd,
      T.aiTypeStart,
      T.embedZoomStart,
      T.embedGrow,
    ],
    [
      700,    // Looking at input (bottom)
      700,
      400,    // Pan up
      200,    // See the message
      250,    // AI area
      280,
      200,    // Embed area
      150,
    ],
    { extrapolateLeft: 'clamp', extrapolateRight: 'clamp', easing: Easing.inOut(Easing.cubic) }
  );
  
  // Calculate viewport position
  // At zoom=1, viewport shows exactly VIEWPORT dimensions
  // At zoom=2, we see half the area (more zoomed in)
  const viewportWidth = VIEWPORT.width / zoom;
  const viewportHeight = VIEWPORT.height / zoom;
  
  return (
    <AbsoluteFill style={{ backgroundColor: COLORS.bg, overflow: 'hidden' }}>
      <div style={{
        position: 'absolute',
        // Scale up by zoom, then position
        width: CANVAS.width,
        height: CANVAS.height,
        transform: `scale(${zoom}) translate(${-cameraX}px, ${-cameraY}px)`,
        transformOrigin: 'top left',
      }}>
        <ChatCanvas />
      </div>
    </AbsoluteFill>
  );
};
