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

// ============ CONSTANTS ============
const COLORS = {
  bg: '#0f0f1a',
  window: '#1a1a2e',
  titlebar: '#252540',
  border: '#2a2a4a',
  inputBg: '#12121f',
  text: '#e2e2f0',
  textMuted: '#8888aa',
  textPlaceholder: '#5a5a7a',
  purple: '#6366f1',
  purpleEnd: '#8b5cf6',
  aiBubble: '#2a2a4a',
  ghlOrange: '#f97316',
  qbGreen: '#22c55e',
  stripeBlue: '#6366f1',
  red: '#dc2626',
  green: '#22c55e',
  yellow: '#f59e0b',
};

// ============ 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));
};

const isTypingComplete = (frame: number, text: string, charFrames: number = 2): boolean => {
  return frame >= text.length * charFrames;
};

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

// ============ CHAT BUBBLE COMPONENT ============
const ChatBubble: React.FC<{
  message: string;
  isUser: boolean;
  typing?: boolean;
  charFrames?: number;
  children?: React.ReactNode;
  startFrame?: number;
  showFull?: boolean;
  highlight?: boolean;
}> = ({ message, isUser, typing = false, charFrames = 2, children, startFrame = 0, showFull = false, highlight = false }) => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  
  const localFrame = Math.max(0, frame - startFrame);
  const displayText = (typing && !showFull) ? getTypedText(localFrame, message, charFrames) : message;
  const showCursor = typing && !showFull && !isTypingComplete(localFrame, message, charFrames);
  
  // Entry animation
  const slideIn = spring({
    frame: localFrame,
    fps,
    config: { damping: 15, stiffness: 100 },
  });
  
  const translateY = interpolate(slideIn, [0, 1], [30, 0]);
  const opacity = interpolate(slideIn, [0, 1], [0, 1]);
  
  // Highlight glow for special messages
  const glowOpacity = highlight ? interpolate(
    (frame % 30),
    [0, 15, 30],
    [0.3, 0.6, 0.3],
    { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' }
  ) : 0;
  
  return (
    <div style={{
      display: 'flex',
      flexDirection: 'column',
      alignItems: isUser ? 'flex-end' : 'flex-start',
      maxWidth: '85%',
      alignSelf: isUser ? 'flex-end' : 'flex-start',
      transform: `translateY(${translateY}px)`,
      opacity,
    }}>
      <div style={{
        padding: '16px 22px',
        borderRadius: '20px',
        borderBottomRightRadius: isUser ? '6px' : '20px',
        borderBottomLeftRadius: isUser ? '20px' : '6px',
        fontSize: '20px',
        lineHeight: 1.5,
        background: highlight 
          ? `linear-gradient(135deg, ${COLORS.green}, #16a34a)`
          : isUser
            ? `linear-gradient(135deg, ${COLORS.purple}, ${COLORS.purpleEnd})`
            : COLORS.aiBubble,
        color: COLORS.text,
        boxShadow: highlight ? `0 0 20px rgba(34, 197, 94, ${glowOpacity})` : 'none',
      }}>
        <span>{displayText}</span>
        {showCursor && <Cursor />}
      </div>
      {children}
    </div>
  );
};

// ============ 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],
          { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' }
        );
        return (
          <div
            key={i}
            style={{
              width: '10px',
              height: '10px',
              backgroundColor: COLORS.purple,
              borderRadius: '50%',
              transform: `translateY(${bounce}px)`,
            }}
          />
        );
      })}
    </div>
  );
};

// ============ LOADING SPINNER ============
const Spinner: React.FC<{ size?: number }> = ({ size = 32 }) => {
  const frame = useCurrentFrame();
  const rotation = (frame * 12) % 360;
  
  return (
    <div style={{
      width: size,
      height: size,
      border: `3px solid ${COLORS.border}`,
      borderTopColor: COLORS.purple,
      borderRadius: '50%',
      transform: `rotate(${rotation}deg)`,
    }} />
  );
};

// ============ INPUT FIELD ============
const InputField: React.FC<{
  text?: string;
  typing?: boolean;
  charFrames?: number;
  startFrame?: number;
}> = ({ text, typing = false, charFrames = 2, startFrame = 0 }) => {
  const frame = useCurrentFrame();
  
  const localFrame = Math.max(0, frame - startFrame);
  const displayText = text && typing
    ? getTypedText(localFrame, text, charFrames)
    : text || '';
  
  const showCursor = typing && text && !isTypingComplete(localFrame, text, charFrames);
  const isActive = displayText && displayText.length > 0;
  
  return (
    <div style={{
      display: 'flex',
      gap: '14px',
      alignItems: 'center',
      background: COLORS.inputBg,
      border: `2px solid ${isActive ? '#3a3a6a' : COLORS.border}`,
      borderRadius: '14px',
      padding: '14px 18px',
    }}>
      <span style={{
        flex: 1,
        color: displayText ? COLORS.text : COLORS.textPlaceholder,
        fontSize: '18px',
      }}>
        {displayText || 'Type a message...'}
        {showCursor && <Cursor />}
      </span>
      <div style={{
        width: '44px',
        height: '44px',
        background: `linear-gradient(135deg, ${COLORS.purple}, ${COLORS.purpleEnd})`,
        borderRadius: '10px',
        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>
  );
};

// ============ APP LOGO SLOTS (LOADING STATE) ============
const AppLogoSlots: React.FC<{ startFrame: number }> = ({ startFrame }) => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  const localFrame = Math.max(0, frame - startFrame);
  
  const apps = [
    { name: 'GoHighLevel', abbr: 'GHL', color: COLORS.ghlOrange },
    { name: 'QuickBooks', abbr: 'QB', color: COLORS.qbGreen },
    { name: 'Stripe', abbr: 'S', color: COLORS.stripeBlue },
  ];
  
  return (
    <div style={{
      marginTop: '20px',
      display: 'flex',
      justifyContent: 'center',
      gap: '32px',
    }}>
      {apps.map((app, i) => {
        const delay = i * 8;
        const scale = spring({
          frame: localFrame - delay,
          fps,
          config: { damping: 12, stiffness: 100 },
        });
        
        return (
          <div
            key={app.name}
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: '10px',
              transform: `scale(${Math.max(0, scale)})`,
              opacity: Math.max(0, scale),
            }}
          >
            <div style={{
              width: '64px',
              height: '64px',
              borderRadius: '16px',
              background: app.color,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '20px',
              fontWeight: 700,
              color: 'white',
            }}>
              {app.abbr}
            </div>
            <span style={{ color: COLORS.textMuted, fontSize: '13px' }}>{app.name}</span>
            <Spinner size={18} />
          </div>
        );
      })}
    </div>
  );
};

// ============ FINAL EMBED WITH DATA ============
const FinalEmbed: React.FC<{ startFrame: number }> = ({ startFrame }) => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  const localFrame = Math.max(0, frame - startFrame);
  
  const fadeIn = spring({
    frame: localFrame,
    fps,
    config: { damping: 15, stiffness: 80 },
  });
  
  const contacts = [
    { name: 'Sarah Johnson', initials: 'SJ', status: 'Overdue', amount: '$1,250' },
    { name: 'Mike Chen', initials: 'MC', status: 'Overdue', amount: '$850' },
    { name: 'Acme Corp', initials: 'AC', status: 'Pending', amount: '$3,200' },
    { name: 'Jane Doe', initials: 'JD', status: 'Paid', amount: '$0' },
  ];
  
  const statusColors: Record<string, string> = {
    Overdue: COLORS.red,
    Pending: COLORS.yellow,
    Paid: COLORS.green,
  };
  
  return (
    <div style={{
      marginTop: '20px',
      display: 'flex',
      gap: '16px',
      justifyContent: 'center',
      opacity: fadeIn,
      transform: `scale(${0.95 + fadeIn * 0.05})`,
    }}>
      {/* GHL Panel */}
      <div style={{
        width: '240px',
        background: COLORS.inputBg,
        borderRadius: '14px',
        padding: '14px',
        border: `1px solid ${COLORS.border}`,
      }}>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: '10px',
          marginBottom: '12px',
          paddingBottom: '10px',
          borderBottom: `1px solid ${COLORS.border}`,
        }}>
          <div style={{
            width: '28px',
            height: '28px',
            borderRadius: '7px',
            background: COLORS.ghlOrange,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '11px',
            fontWeight: 700,
            color: 'white',
          }}>GHL</div>
          <span style={{ fontSize: '14px', fontWeight: 600, color: COLORS.text }}>GoHighLevel</span>
        </div>
        
        {/* Mini Chat */}
        <div style={{
          background: COLORS.window,
          borderRadius: '10px',
          padding: '10px',
          marginBottom: '10px',
        }}>
          <div style={{
            fontSize: '11px',
            padding: '6px 10px',
            borderRadius: '10px',
            background: COLORS.purple,
            color: 'white',
            marginLeft: 'auto',
            width: 'fit-content',
            marginBottom: '4px',
          }}>Hi! Following up on invoice #1042</div>
          <div style={{
            fontSize: '11px',
            padding: '6px 10px',
            borderRadius: '10px',
            background: COLORS.border,
            color: COLORS.text,
            width: 'fit-content',
            marginBottom: '4px',
          }}>Thanks, I'll pay today</div>
          <div style={{
            fontSize: '11px',
            padding: '6px 10px',
            borderRadius: '10px',
            background: COLORS.purple,
            color: 'white',
            marginLeft: 'auto',
            width: 'fit-content',
          }}>Great! Here's your link: [link]</div>
        </div>
        
        {/* Contact List */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
          {contacts.map((c) => (
            <div key={c.name} style={{
              display: 'flex',
              alignItems: 'center',
              gap: '6px',
              padding: '6px 8px',
              background: COLORS.window,
              borderRadius: '6px',
              fontSize: '11px',
            }}>
              <div style={{
                width: '22px',
                height: '22px',
                borderRadius: '50%',
                background: '#3a3a5a',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: '9px',
                color: COLORS.textMuted,
              }}>{c.initials}</div>
              <span style={{ flex: 1, color: COLORS.text }}>{c.name}</span>
              <span style={{
                padding: '2px 5px',
                borderRadius: '4px',
                fontSize: '9px',
                fontWeight: 600,
                background: statusColors[c.status],
                color: 'white',
              }}>{c.status}</span>
              <span style={{ color: COLORS.textMuted, fontSize: '10px' }}>{c.amount}</span>
            </div>
          ))}
        </div>
      </div>
      
      {/* QuickBooks Panel */}
      <div style={{
        width: '180px',
        background: COLORS.inputBg,
        borderRadius: '14px',
        padding: '14px',
        border: `1px solid ${COLORS.border}`,
      }}>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: '10px',
          marginBottom: '12px',
          paddingBottom: '10px',
          borderBottom: `1px solid ${COLORS.border}`,
        }}>
          <div style={{
            width: '28px',
            height: '28px',
            borderRadius: '7px',
            background: COLORS.qbGreen,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '11px',
            fontWeight: 700,
            color: 'white',
          }}>QB</div>
          <span style={{ fontSize: '14px', fontWeight: 600, color: COLORS.text }}>QuickBooks</span>
        </div>
        
        <div style={{ fontSize: '12px' }}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr 1fr',
            padding: '4px 0',
            borderBottom: `1px solid ${COLORS.border}`,
            color: COLORS.textMuted,
            fontSize: '10px',
          }}>
            <span></span>
            <span style={{ textAlign: 'right' }}>With</span>
            <span style={{ textAlign: 'right' }}>Without</span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr 1fr',
            padding: '6px 0',
            borderBottom: `1px solid ${COLORS.window}`,
            fontSize: '11px',
          }}>
            <span style={{ color: COLORS.textMuted }}>Revenue</span>
            <span style={{ textAlign: 'right', color: COLORS.green }}>$152K</span>
            <span style={{ textAlign: 'right', color: COLORS.red }}>$140K</span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr 1fr',
            padding: '6px 0',
            fontSize: '11px',
          }}>
            <span style={{ color: COLORS.textMuted }}>Net Income</span>
            <span style={{ textAlign: 'right', color: COLORS.green }}>$58K</span>
            <span style={{ textAlign: 'right', color: COLORS.red }}>$46K</span>
          </div>
        </div>
        
        <div style={{
          marginTop: '12px',
          padding: '10px',
          background: COLORS.window,
          borderRadius: '8px',
          textAlign: 'center',
        }}>
          <div style={{ color: COLORS.textMuted, fontSize: '10px' }}>Potential Increase</div>
          <div style={{ color: COLORS.green, fontSize: '20px', fontWeight: 700 }}>+$12,450</div>
        </div>
      </div>
      
      {/* Stripe Panel */}
      <div style={{
        width: '160px',
        background: COLORS.inputBg,
        borderRadius: '14px',
        padding: '14px',
        border: `1px solid ${COLORS.border}`,
      }}>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: '10px',
          marginBottom: '12px',
          paddingBottom: '10px',
          borderBottom: `1px solid ${COLORS.border}`,
        }}>
          <div style={{
            width: '28px',
            height: '28px',
            borderRadius: '7px',
            background: COLORS.stripeBlue,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '11px',
            fontWeight: 700,
            color: 'white',
          }}>S</div>
          <span style={{ fontSize: '14px', fontWeight: 600, color: COLORS.text }}>Stripe</span>
        </div>
        
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          paddingTop: '10px',
        }}>
          <div style={{
            width: '80px',
            height: '80px',
            borderRadius: '50%',
            background: `conic-gradient(${COLORS.purple} 0% 85%, ${COLORS.border} 85% 100%)`,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
            <div style={{
              width: '56px',
              height: '56px',
              background: COLORS.inputBg,
              borderRadius: '50%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '16px',
              fontWeight: 700,
              color: COLORS.purple,
            }}>85%</div>
          </div>
          <div style={{ marginTop: '12px', fontSize: '22px', fontWeight: 700, color: COLORS.text }}>$12,450</div>
          <div style={{ fontSize: '11px', color: COLORS.textMuted }}>Collectible Revenue</div>
        </div>
      </div>
    </div>
  );
};

// ============ WINDOW CHROME ============
const WindowChrome: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  return (
    <div style={{
      width: '900px',
      height: '750px',
      background: COLORS.window,
      borderRadius: '16px',
      boxShadow: '0 30px 100px rgba(0,0,0,0.6)',
      display: 'flex',
      flexDirection: 'column',
      border: `1px solid ${COLORS.border}`,
      overflow: 'hidden',
    }}>
      {/* Title bar */}
      <div style={{
        height: '52px',
        background: COLORS.titlebar,
        display: 'flex',
        alignItems: 'center',
        padding: '0 18px',
        borderBottom: `1px solid ${COLORS.border}`,
        flexShrink: 0,
      }}>
        <div style={{ display: 'flex', gap: '9px' }}>
          <div style={{ width: '14px', height: '14px', borderRadius: '50%', background: '#ff5f57' }} />
          <div style={{ width: '14px', height: '14px', borderRadius: '50%', background: '#ffbd2e' }} />
          <div style={{ width: '14px', height: '14px', borderRadius: '50%', background: '#28ca41' }} />
        </div>
        <div style={{ flex: 1, textAlign: 'center', color: COLORS.textMuted, fontSize: '16px', fontWeight: 500 }}>
          AI Assistant
        </div>
        <div style={{ width: '60px' }} />
      </div>
      {children}
    </div>
  );
};

// ============ CLOSING SCREEN ============
const ClosingScreen: React.FC<{ startFrame: number }> = ({ startFrame }) => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  const localFrame = Math.max(0, frame - startFrame);
  
  const fadeIn = spring({
    frame: localFrame,
    fps,
    config: { damping: 20, stiffness: 80 },
  });
  
  const scale = interpolate(fadeIn, [0, 1], [0.8, 1]);
  
  // Glow pulse
  const glowIntensity = interpolate(
    (localFrame % 60),
    [0, 30, 60],
    [0.3, 0.6, 0.3],
    { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' }
  );
  
  return (
    <AbsoluteFill style={{
      backgroundColor: COLORS.bg,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, sans-serif',
      opacity: fadeIn,
    }}>
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: '30px',
        transform: `scale(${scale})`,
      }}>
        <div style={{
          fontSize: '64px',
          fontWeight: 800,
          textAlign: 'center',
          lineHeight: 1.2,
          background: `linear-gradient(135deg, ${COLORS.purple}, ${COLORS.purpleEnd}, ${COLORS.green})`,
          WebkitBackgroundClip: 'text',
          WebkitTextFillColor: 'transparent',
          backgroundClip: 'text',
          filter: `drop-shadow(0 0 30px rgba(99, 102, 241, ${glowIntensity}))`,
        }}>
          Let AI work for you
        </div>
        <div style={{
          fontSize: '48px',
          fontWeight: 700,
          color: COLORS.text,
          textAlign: 'center',
        }}>
          AND keep{' '}
          <span style={{
            background: `linear-gradient(135deg, ${COLORS.green}, #16a34a)`,
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            backgroundClip: 'text',
          }}>
            full visibility
          </span>
          !
        </div>
      </div>
    </AbsoluteFill>
  );
};

// ============ MAIN ANIMATION ============
export const MCPChatAnimation: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  
  // Timeline (in frames) - extended
  const T = {
    // First exchange
    typing1Start: Math.round(0.5 * fps),
    msg1Show: Math.round(3 * fps),
    aiThinking1: Math.round(3.5 * fps),
    aiResponse1: Math.round(4.5 * fps),
    
    // Second exchange  
    typing2Start: Math.round(8 * fps),
    msg2Show: Math.round(10 * fps),
    aiThinking2: Math.round(10.5 * fps),
    aiResponse2: Math.round(11.5 * fps),
    
    // Third request with apps
    typing3Start: Math.round(15 * fps),
    msg3Show: Math.round(19 * fps),
    aiMoment: Math.round(19.5 * fps),
    logoSlots: Math.round(20 * fps),
    finalEmbed: Math.round(24 * fps),
    
    // NEW: Follow-up action messages
    aiAction1: Math.round(28 * fps),      // "13 clients behind..."
    aiAction2: Math.round(31 * fps),      // "John Smith has submitted..."
    
    // Closing screen
    closingScreen: Math.round(35 * fps),
  };
  
  const MSG1 = 'how can we make some money right now';
  const AI1 = 'Collect missed payments, do a high intent database reactivation, or purchase some on demand leads to have an appt with';
  const MSG2 = "let's collect missed payments";
  const AI2 = 'would you like to choose view or allow me to decide';
  const MSG3 = 'show me all the customers who are behind on payments and help me come up with an outreach strategy to collect $$ from them';
  const AI3 = 'one moment';
  const AI_FINAL = "Here's your payment collection overview:";
  const AI_ACTION1 = '13 clients behind have been emailed, texted and voicemail dropped.';
  const AI_ACTION2 = 'John Smith has submitted payment 💵💵';
  
  // Show closing screen
  if (frame >= T.closingScreen) {
    return <ClosingScreen startFrame={T.closingScreen} />;
  }
  
  // Scroll position to keep latest content visible
  const scrollOffset = frame >= T.aiAction2 ? -200 :
                       frame >= T.aiAction1 ? -160 :
                       frame >= T.finalEmbed ? -120 : 
                       frame >= T.msg3Show ? -60 : 
                       frame >= T.msg2Show ? -30 : 0;
  
  // Input field state
  let inputText = '';
  let inputTyping = false;
  let inputStartFrame = 0;
  
  if (frame >= T.typing1Start && frame < T.msg1Show) {
    inputText = MSG1;
    inputTyping = true;
    inputStartFrame = T.typing1Start;
  } else if (frame >= T.typing2Start && frame < T.msg2Show) {
    inputText = MSG2;
    inputTyping = true;
    inputStartFrame = T.typing2Start;
  } else if (frame >= T.typing3Start && frame < T.msg3Show) {
    inputText = MSG3;
    inputTyping = true;
    inputStartFrame = T.typing3Start;
  }
  
  return (
    <AbsoluteFill style={{
      backgroundColor: COLORS.bg,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, sans-serif',
    }}>
      <WindowChrome>
        {/* Chat Area */}
        <div style={{
          flex: 1,
          padding: '24px',
          display: 'flex',
          flexDirection: 'column',
          gap: '14px',
          overflowY: 'hidden',
          justifyContent: 'flex-end',
        }}>
          <div style={{
            display: 'flex',
            flexDirection: 'column',
            gap: '14px',
            transform: `translateY(${scrollOffset}px)`,
            transition: 'transform 0.3s ease-out',
          }}>
            {/* First exchange */}
            {frame >= T.msg1Show && (
              <ChatBubble 
                message={MSG1} 
                isUser={true} 
                startFrame={T.msg1Show}
                showFull={frame >= T.msg1Show + 60}
              />
            )}
            
            {frame >= T.aiThinking1 && frame < T.aiResponse1 && (
              <TypingIndicator />
            )}
            
            {frame >= T.aiResponse1 && (
              <ChatBubble 
                message={AI1} 
                isUser={false} 
                typing 
                charFrames={1} 
                startFrame={T.aiResponse1}
                showFull={frame >= T.aiResponse1 + 150}
              />
            )}
            
            {/* Second exchange */}
            {frame >= T.msg2Show && (
              <ChatBubble 
                message={MSG2} 
                isUser={true} 
                startFrame={T.msg2Show}
                showFull={frame >= T.msg2Show + 60}
              />
            )}
            
            {frame >= T.aiThinking2 && frame < T.aiResponse2 && (
              <TypingIndicator />
            )}
            
            {frame >= T.aiResponse2 && frame < T.finalEmbed && (
              <ChatBubble 
                message={AI2} 
                isUser={false} 
                typing 
                charFrames={1} 
                startFrame={T.aiResponse2}
                showFull={frame >= T.aiResponse2 + 80}
              />
            )}
            
            {/* Third exchange */}
            {frame >= T.msg3Show && (
              <ChatBubble 
                message={MSG3} 
                isUser={true} 
                startFrame={T.msg3Show}
                showFull={frame >= T.msg3Show + 60}
              />
            )}
            
            {frame >= T.aiMoment && frame < T.finalEmbed && (
              <ChatBubble 
                message={AI3} 
                isUser={false} 
                typing 
                charFrames={2} 
                startFrame={T.aiMoment}
                showFull={frame >= T.aiMoment + 40}
              >
                {frame >= T.logoSlots && <AppLogoSlots startFrame={T.logoSlots} />}
              </ChatBubble>
            )}
            
            {/* Final embed */}
            {frame >= T.finalEmbed && (
              <ChatBubble 
                message={AI_FINAL} 
                isUser={false} 
                typing 
                charFrames={1} 
                startFrame={T.finalEmbed}
                showFull={frame >= T.finalEmbed + 60}
              >
                <FinalEmbed startFrame={T.finalEmbed + 30} />
              </ChatBubble>
            )}
            
            {/* NEW: Follow-up action message 1 */}
            {frame >= T.aiAction1 && (
              <ChatBubble 
                message={AI_ACTION1} 
                isUser={false} 
                typing 
                charFrames={1} 
                startFrame={T.aiAction1}
                showFull={frame >= T.aiAction1 + 80}
              />
            )}
            
            {/* NEW: Follow-up action message 2 - highlighted */}
            {frame >= T.aiAction2 && (
              <ChatBubble 
                message={AI_ACTION2} 
                isUser={false} 
                typing 
                charFrames={1} 
                startFrame={T.aiAction2}
                showFull={frame >= T.aiAction2 + 50}
                highlight={true}
              />
            )}
          </div>
        </div>
        
        {/* Input Area */}
        <div style={{
          padding: '18px 24px 24px',
          borderTop: `1px solid ${COLORS.border}`,
          flexShrink: 0,
        }}>
          <InputField 
            text={inputText} 
            typing={inputTyping} 
            charFrames={2} 
            startFrame={inputStartFrame}
          />
        </div>
      </WindowChrome>
    </AbsoluteFill>
  );
};
