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

// ============ CONFIG ============
const SOFTWARE = {
  name: 'Stripe',
  abbr: 'S',
  color: '#635BFF',
  category: 'payments',
};

// Category-specific questions
const CATEGORY_QUESTIONS: Record<string, string> = {
  payments: "What patterns do you see in my transaction data?",
  crm: "Who should I follow up with to close deals this week?",
  accounting: "Based on my cash flow, should I hire this month?",
  fieldService: "How do I maximize revenue per technician today?",
  projectManagement: "What's blocking my team from shipping faster?",
  emailMarketing: "Which segment should I target to maximize engagement?",
  support: "Which tickets are about to breach SLA?",
};

const USER_QUESTION = CATEGORY_QUESTIONS[SOFTWARE.category];
const AI_RESPONSE = "Let me analyze your Stripe data...";

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

// ============ TIMING (30fps) ============
const T = {
  // Phase 1: User types
  userTypeStart: 0,
  userTypeEnd: 60,      // 2 seconds of typing
  
  // Phase 2: Message sent, camera pans up
  messageSent: 70,
  cameraPanUp: 80,
  
  // Phase 3: AI thinking
  aiThinking: 100,
  
  // Phase 4: AI responds
  aiResponse: 130,
  
  // Phase 5: Processing + embed loading
  processing: 180,
  embedAppear: 210,
  embedShrink: 230,     // shrink to center
  embedGrow: 260,       // grow out centered
  
  // End
  end: 330,             // 11 seconds total
};

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

// ============ CURSOR ============
const Cursor: React.FC = () => {
  const frame = useCurrentFrame();
  const opacity = interpolate(frame % 16, [0, 8, 16], [1, 0, 1]);
  
  return (
    <span style={{
      display: 'inline-block',
      width: '3px',
      height: '1.1em',
      backgroundColor: COLORS.purple,
      marginLeft: '2px',
      opacity,
      verticalAlign: 'middle',
    }} />
  );
};

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

// ============ SPINNER ============
const Spinner: React.FC = () => {
  const frame = useCurrentFrame();
  const rotation = (frame * 12) % 360;
  
  return (
    <div style={{
      width: 20,
      height: 20,
      border: `2px solid ${COLORS.border}`,
      borderTopColor: SOFTWARE.color,
      borderRadius: '50%',
      transform: `rotate(${rotation}deg)`,
      display: 'inline-block',
      marginRight: 12,
      verticalAlign: 'middle',
    }} />
  );
};

// ============ STRIPE EMBED ============
const StripeEmbed: React.FC<{ startFrame: number }> = ({ startFrame }) => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  const localFrame = Math.max(0, frame - startFrame);
  
  // Shrink then grow animation
  const shrinkProgress = spring({
    frame: localFrame,
    fps,
    config: { damping: 20, stiffness: 100 },
  });
  
  const growProgress = spring({
    frame: Math.max(0, localFrame - 30),
    fps,
    config: { damping: 15, stiffness: 80 },
  });
  
  // Start at 0.6 scale, shrink to 0.5 (centering), then grow to 1.0
  const scale = interpolate(
    localFrame,
    [0, 20, 50],
    [0.6, 0.55, 1],
    { extrapolateRight: 'clamp', easing: Easing.out(Easing.cubic) }
  );
  
  const opacity = interpolate(localFrame, [0, 15], [0, 1], { extrapolateRight: 'clamp' });
  
  // Row stagger animation
  const rowOpacity = (index: number) => {
    const delay = 40 + index * 8;
    return interpolate(localFrame, [delay, delay + 15], [0, 1], { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' });
  };
  
  const rowTranslate = (index: number) => {
    const delay = 40 + index * 8;
    return interpolate(localFrame, [delay, delay + 15], [15, 0], { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' });
  };

  const payments = [
    { email: 'john@example.com', amount: '$449.00', status: 'Ready to retry', statusColor: '#FFF8E6', statusText: '#9C6F19' },
    { email: 'sarah@company.co', amount: '$299.00', status: 'Card updated', statusColor: '#D7F7E0', statusText: '#0E6245' },
    { email: 'mike@startup.io', amount: '$499.00', status: 'Ready to retry', statusColor: '#FFF8E6', statusText: '#9C6F19' },
  ];

  return (
    <div style={{
      display: 'flex',
      justifyContent: 'center',
      marginTop: 16,
      opacity,
      transform: `scale(${scale})`,
      transformOrigin: 'top center',
    }}>
      <div style={{
        background: '#FFFFFF',
        borderRadius: 16,
        overflow: 'hidden',
        width: 500,
        boxShadow: `0 4px 30px rgba(99, 91, 255, 0.2), 0 0 0 1px rgba(99, 91, 255, 0.15)`,
      }}>
        {/* Header */}
        <div style={{
          padding: '16px 20px',
          borderBottom: '1px solid #E3E8EE',
          display: 'flex',
          alignItems: 'center',
          gap: 12,
        }}>
          <div style={{
            background: SOFTWARE.color,
            color: 'white',
            fontWeight: 700,
            fontSize: 12,
            padding: '6px 12px',
            borderRadius: 6,
          }}>stripe</div>
          <div>
            <div style={{ fontSize: 15, fontWeight: 600, color: '#1A1F36' }}>Payment Recovery</div>
            <div style={{ fontSize: 11, color: '#697386' }}>3 opportunities found</div>
          </div>
        </div>
        
        {/* Stats */}
        <div style={{
          display: 'flex',
          gap: 32,
          padding: '14px 20px',
          background: '#F6F9FC',
          borderBottom: '1px solid #E3E8EE',
        }}>
          <div>
            <div style={{ fontSize: 22, fontWeight: 600, color: '#30B566' }}>$1,247</div>
            <div style={{ fontSize: 10, color: '#697386', textTransform: 'uppercase', letterSpacing: 0.5 }}>Recoverable</div>
          </div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 600, color: '#1A1F36' }}>87%</div>
            <div style={{ fontSize: 10, color: '#697386', textTransform: 'uppercase', letterSpacing: 0.5 }}>Success Rate</div>
          </div>
        </div>
        
        {/* Table */}
        <div style={{ padding: '8px 0' }}>
          {payments.map((p, i) => (
            <div 
              key={i}
              style={{
                display: 'flex',
                alignItems: 'center',
                padding: '12px 20px',
                borderBottom: i < payments.length - 1 ? '1px solid #E3E8EE' : 'none',
                opacity: rowOpacity(i),
                transform: `translateX(${rowTranslate(i)}px)`,
              }}
            >
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500, color: '#1A1F36' }}>{p.email}</div>
                <div style={{ fontSize: 11, color: '#697386', fontFamily: 'monospace' }}>cus_xxx...xxx</div>
              </div>
              <div style={{ fontSize: 14, fontWeight: 600, color: '#1A1F36', marginRight: 16 }}>{p.amount}</div>
              <div style={{
                padding: '4px 10px',
                borderRadius: 4,
                fontSize: 11,
                fontWeight: 500,
                background: p.statusColor,
                color: p.statusText,
              }}>{p.status}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ============ MAIN COMPOSITION ============
export const StripeCameraDemo: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps, width, height } = useVideoConfig();
  
  // ========== CAMERA MOVEMENT ==========
  // Camera zooms in on input, pans to follow conversation, zooms out for embed
  
  const cameraZoom = interpolate(
    frame,
    [
      0,              // Start: zoomed into input
      T.messageSent,  // Stay zoomed while typing
      T.cameraPanUp,  // Begin zoom out
      T.aiResponse,   // Zoomed out to show conversation
      T.embedAppear,  // Stay
      T.embedGrow,    // Slight zoom for emphasis
      T.end,          // End
    ],
    [1.4, 1.4, 1.15, 1.0, 1.0, 1.02, 1.0],
    { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' }
  );
  
  // Camera Y position (positive = looking down, negative = looking up)
  const cameraY = interpolate(
    frame,
    [
      0,              // Start: looking at input (bottom)
      T.messageSent,  // Stay
      T.cameraPanUp,  // Pan up to show messages
      T.aiResponse,   // Centered
      T.processing,   // Stay
      T.embedAppear,  // Pan down slightly for embed
      T.end,
    ],
    [250, 250, 100, -20, -20, 40, 40],
    { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' }
  );
  
  const cameraX = interpolate(
    frame,
    [0, T.messageSent, T.aiResponse, T.end],
    [0, 0, 0, 0],
    { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' }
  );
  
  // Typing state
  const userTypingFrame = Math.max(0, frame - T.userTypeStart);
  const userText = frame >= T.userTypeStart && frame < T.messageSent
    ? getTypedText(userTypingFrame, USER_QUESTION, 1)
    : USER_QUESTION;
  const showUserCursor = frame >= T.userTypeStart && frame < T.messageSent;
  
  const aiTypingFrame = Math.max(0, frame - T.aiResponse);
  const aiText = frame >= T.aiResponse
    ? getTypedText(aiTypingFrame, AI_RESPONSE, 1)
    : '';
  
  return (
    <AbsoluteFill style={{ backgroundColor: COLORS.bg }}>
      {/* Background gradient */}
      <div style={{
        position: 'absolute',
        inset: 0,
        background: `
          radial-gradient(ellipse at 30% 20%, rgba(99, 91, 255, 0.1) 0%, transparent 50%),
          radial-gradient(ellipse at 70% 80%, rgba(118, 75, 162, 0.1) 0%, transparent 50%)
        `,
      }} />
      
      {/* Camera wrapper */}
      <div style={{
        position: 'absolute',
        inset: 0,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        overflow: 'hidden',
      }}>
        <div style={{
          transform: `scale(${cameraZoom}) translate(${cameraX}px, ${cameraY}px)`,
          transformOrigin: 'center center',
          transition: 'transform 0.1s ease-out',
        }}>
          {/* Chat Window */}
          <div style={{
            width: 1200,
            height: 750,
            background: COLORS.window,
            borderRadius: 20,
            boxShadow: '0 25px 80px rgba(0,0,0,0.5)',
            display: 'flex',
            flexDirection: 'column',
            border: `1px solid ${COLORS.border}`,
            overflow: 'hidden',
          }}>
            {/* Title bar */}
            <div style={{
              height: 52,
              background: COLORS.titlebar,
              display: 'flex',
              alignItems: 'center',
              padding: '0 20px',
              borderBottom: `1px solid ${COLORS.border}`,
            }}>
              <div style={{ display: 'flex', gap: 8 }}>
                <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#ff5f57' }} />
                <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#ffbd2e' }} />
                <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#27ca40' }} />
              </div>
              <div style={{ flex: 1, textAlign: 'center', color: COLORS.textMuted, fontSize: 14 }}>
                AI Assistant
              </div>
              <div style={{ width: 52 }} />
            </div>
            
            {/* Messages area */}
            <div style={{
              flex: 1,
              padding: 28,
              display: 'flex',
              flexDirection: 'column',
              gap: 20,
              overflow: 'hidden',
            }}>
              {/* User message */}
              {frame >= T.messageSent && (
                <div style={{
                  alignSelf: 'flex-end',
                  maxWidth: '70%',
                  padding: '16px 24px',
                  background: `linear-gradient(135deg, ${COLORS.purple}, ${COLORS.purpleEnd})`,
                  color: COLORS.text,
                  borderRadius: 20,
                  borderBottomRightRadius: 6,
                  fontSize: 18,
                  lineHeight: 1.5,
                }}>
                  {USER_QUESTION}
                </div>
              )}
              
              {/* AI thinking */}
              {frame >= T.aiThinking && frame < T.aiResponse && (
                <TypingIndicator />
              )}
              
              {/* AI response */}
              {frame >= T.aiResponse && (
                <div style={{
                  alignSelf: 'flex-start',
                  maxWidth: '80%',
                  display: 'flex',
                  flexDirection: 'column',
                }}>
                  <div style={{
                    padding: '16px 24px',
                    background: COLORS.aiBubble,
                    color: COLORS.text,
                    borderRadius: 20,
                    borderBottomLeftRadius: 6,
                    fontSize: 18,
                    lineHeight: 1.5,
                  }}>
                    {frame >= T.processing ? (
                      <span><Spinner />Analyzing your payment data...</span>
                    ) : (
                      <span>{aiText}{frame < T.processing && <Cursor />}</span>
                    )}
                  </div>
                  
                  {/* Embed */}
                  {frame >= T.embedAppear && (
                    <StripeEmbed startFrame={T.embedAppear} />
                  )}
                </div>
              )}
            </div>
            
            {/* Input area */}
            <div style={{
              padding: '16px 24px 24px',
              borderTop: `1px solid ${COLORS.border}`,
            }}>
              <div style={{
                display: 'flex',
                gap: 14,
                alignItems: 'center',
                background: COLORS.inputBg,
                border: `2px solid ${frame < T.messageSent ? '#3a3a6a' : COLORS.border}`,
                borderRadius: 14,
                padding: '14px 18px',
              }}>
                <span style={{
                  flex: 1,
                  color: frame < T.messageSent && userText ? COLORS.text : COLORS.textMuted,
                  fontSize: 17,
                }}>
                  {frame < T.messageSent ? (
                    <>
                      {userText || 'Type a message...'}
                      {showUserCursor && userText && <Cursor />}
                    </>
                  ) : (
                    'Type a message...'
                  )}
                </span>
                <div style={{
                  width: 44,
                  height: 44,
                  background: `linear-gradient(135deg, ${COLORS.purple}, ${COLORS.purpleEnd})`,
                  borderRadius: 10,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
                  <svg width="22" height="22" 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>
      </div>
    </AbsoluteFill>
  );
};
