/**
 * DemoVideo — marketing/demo video composition with custom scene types.
 *
 * Extends standard slide types with specialized marketing scenes:
 *   - terminal: typewriter terminal output
 *   - notification: slide-in notification card
 *   - kanban: kanban board visualization
 *   - pipeline: flowchart with animated progress
 *
 * Format: Feed (1080×1080) for landing page
 * Total: 810 frames (27s at 30fps)
 */

import React from 'react';
import { AbsoluteFill, Sequence, useCurrentFrame, interpolate } from 'remotion';
import { BackgroundMusic } from './BackgroundMusic';
import type { AudioConfig } from '../renderer';

// ─── Types ──────────────────────────────────────────────────────────────────

export interface DemoSlideData {
  type: 'cover' | 'terminal' | 'key_point' | 'notification' | 'steps' | 'kanban' | 'pipeline' | 'quote' | 'cta';
  title: string;
  subtitle?: string;
  content?: string;
  items?: string[];
  value?: string;
  label?: string;
  background_style?: string;
  cta_text?: string;
}

export interface DemoVideoProps {
  slides: DemoSlideData[];
  format: 'feed' | 'reels';
  audio?: AudioConfig;
}

// ─── Constants ──────────────────────────────────────────────────────────────

const ACCENT = '#10b981';
const TEXT = '#ffffff';
const MUTED = 'rgba(255,255,255,0.6)';
const FONT = '"Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';

// Custom frame durations for different scene types
const FRAME_DURATIONS: Record<string, number> = {
  cover: 90,        // 3s
  terminal: 150,    // 5s
  key_point: 90,    // 3s
  notification: 90, // 3s
  steps: 150,       // 5s (kanban)
  kanban: 150,      // 5s
  pipeline: 135,    // 4.5s
  quote: 135,       // 4.5s
  cta: 105,         // 3.5s
};

// ─── DemoVideo ──────────────────────────────────────────────────────────────

export const DemoVideo: React.FC<DemoVideoProps> = ({ slides, audio }) => {
  let currentFrame = 0;

  return (
    <AbsoluteFill
      style={{
        background: 'linear-gradient(135deg, #0f172a 0%, #1e293b 100%)',
      }}
    >
      {slides.map((slide, i) => {
        const duration = FRAME_DURATIONS[slide.type] || 90;
        const from = currentFrame;
        currentFrame += duration;

        return (
          <Sequence key={i} from={from} durationInFrames={duration}>
            <DemoSlide slide={slide} />
          </Sequence>
        );
      })}
      {audio && <BackgroundMusic audio={audio} />}
    </AbsoluteFill>
  );
};

// ─── DemoSlide ──────────────────────────────────────────────────────────────

const DemoSlide: React.FC<{ slide: DemoSlideData }> = ({ slide }) => {
  const frame = useCurrentFrame();
  const opacity = interpolate(frame, [0, 15], [0, 1], { extrapolateRight: 'clamp' });
  const y = interpolate(frame, [0, 15], [24, 0], { extrapolateRight: 'clamp' });

  return (
    <AbsoluteFill
      style={{
        opacity,
        transform: `translateY(${y}px)`,
        fontFamily: FONT,
        color: TEXT,
        padding: '80px',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'flex-start',
      }}
    >
      <SlideContent slide={slide} />
    </AbsoluteFill>
  );
};

// ─── Slide content by type ──────────────────────────────────────────────────

function SlideContent({ slide }: { slide: DemoSlideData }) {
  const frame = useCurrentFrame();

  switch (slide.type) {
    case 'cover':
      return (
        <>
          <h1
            style={{
              fontSize: 72,
              fontWeight: 900,
              lineHeight: 1.1,
              margin: 0,
              marginBottom: 20,
              color: TEXT,
            }}
          >
            {slide.title}
          </h1>
          {slide.subtitle && (
            <p style={{ fontSize: 36, color: MUTED, fontWeight: 400, margin: 0 }}>
              {slide.subtitle}
            </p>
          )}
        </>
      );

    case 'terminal':
      return <TerminalScene title={slide.title} content={slide.content || ''} frame={frame} />;

    case 'notification':
      return <NotificationScene title={slide.title} content={slide.content || ''} frame={frame} />;

    case 'key_point':
      return (
        <>
          <div
            style={{
              fontSize: 13,
              fontWeight: 600,
              letterSpacing: 2,
              color: ACCENT,
              textTransform: 'uppercase',
              marginBottom: 16,
            }}
          >
            {slide.title}
          </div>
          <p style={{ fontSize: 40, fontWeight: 600, lineHeight: 1.4, margin: 0, color: TEXT }}>
            {slide.content}
          </p>
        </>
      );

    case 'steps':
    case 'kanban':
      return <KanbanScene title={slide.title} items={slide.items || []} frame={frame} />;

    case 'pipeline':
      return <PipelineScene title={slide.title} content={slide.content || ''} label={slide.label} frame={frame} />;

    case 'quote':
      return (
        <>
          <div
            style={{
              width: 48,
              height: 4,
              background: ACCENT,
              marginBottom: 32,
              borderRadius: 2,
            }}
          />
          <p
            style={{
              fontSize: 36,
              fontWeight: 600,
              lineHeight: 1.5,
              margin: 0,
              marginBottom: 32,
              fontStyle: 'italic',
              color: TEXT,
            }}
          >
            &ldquo;{slide.content}&rdquo;
          </p>
        </>
      );

    case 'cta':
      return (
        <>
          <h2
            style={{
              fontSize: 56,
              fontWeight: 800,
              lineHeight: 1.1,
              margin: 0,
              marginBottom: 40,
              color: TEXT,
            }}
          >
            {slide.title}
          </h2>
          <div
            style={{
              padding: '20px 40px',
              background: ACCENT,
              borderRadius: 12,
              fontSize: 22,
              fontWeight: 700,
              color: '#0f172a',
              fontFamily: 'monospace',
            }}
          >
            {slide.cta_text || 'Get Started'}
          </div>
        </>
      );

    default:
      return <div style={{ fontSize: 32 }}>{slide.title}</div>;
  }
}

// ─── Custom Scene Components ────────────────────────────────────────────────

function TerminalScene({ title, content, frame }: { title: string; content: string; frame: number }) {
  // Typewriter effect
  const lines = content.split('\n');
  const charsPerFrame = 2;
  const visibleChars = Math.floor(frame * charsPerFrame);

  let charCount = 0;
  const visibleLines = lines.map((line) => {
    const lineStart = charCount;
    charCount += line.length + 1; // +1 for newline
    const lineEnd = lineStart + line.length;

    if (visibleChars < lineStart) return '';
    if (visibleChars >= lineEnd) return line;
    return line.slice(0, visibleChars - lineStart);
  });

  return (
    <div style={{ width: '100%' }}>
      <div
        style={{
          fontSize: 13,
          fontWeight: 600,
          letterSpacing: 2,
          color: ACCENT,
          textTransform: 'uppercase',
          marginBottom: 24,
        }}
      >
        {title}
      </div>
      <div
        style={{
          background: 'rgba(15, 23, 42, 0.8)',
          border: `1px solid ${ACCENT}`,
          borderRadius: 8,
          padding: '32px',
          fontFamily: 'monospace',
          fontSize: 20,
          lineHeight: 1.8,
        }}
      >
        {visibleLines.map((line, i) => (
          <div key={i} style={{ color: i === visibleLines.length - 1 ? ACCENT : TEXT }}>
            {line || '\u00A0'}
          </div>
        ))}
      </div>
    </div>
  );
}

function NotificationScene({ title, content, frame }: { title: string; content: string; frame: number }) {
  // Slide in from right
  const x = interpolate(frame, [0, 20], [100, 0], { extrapolateRight: 'clamp' });

  return (
    <div style={{ width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
      <div
        style={{
          fontSize: 80,
          fontWeight: 900,
          color: TEXT,
          marginBottom: 40,
        }}
      >
        {title}
      </div>
      <div
        style={{
          transform: `translateX(${x}px)`,
          background: 'rgba(16, 185, 129, 0.1)',
          border: `2px solid ${ACCENT}`,
          borderRadius: 16,
          padding: '32px 48px',
          boxShadow: `0 0 40px rgba(16, 185, 129, 0.3)`,
        }}
      >
        <div style={{ fontSize: 32, fontWeight: 600, color: TEXT }}>{content}</div>
      </div>
    </div>
  );
}

function KanbanScene({ title, items, frame }: { title: string; items: string[]; frame: number }) {
  return (
    <div style={{ width: '100%' }}>
      <div
        style={{
          fontSize: 13,
          fontWeight: 600,
          letterSpacing: 2,
          color: ACCENT,
          textTransform: 'uppercase',
          marginBottom: 32,
        }}
      >
        {title}
      </div>
      <div style={{ display: 'flex', gap: 24 }}>
        {items.map((item, i) => {
          const delay = i * 10;
          const opacity = interpolate(frame, [delay, delay + 15], [0, 1], { extrapolateRight: 'clamp' });
          const scale = interpolate(frame, [delay, delay + 15], [0.8, 1], { extrapolateRight: 'clamp' });

          return (
            <div
              key={i}
              style={{
                flex: 1,
                opacity,
                transform: `scale(${scale})`,
                background: 'rgba(15, 23, 42, 0.6)',
                border: `1px solid ${i === 2 ? ACCENT : 'rgba(255,255,255,0.1)'}`,
                borderRadius: 12,
                padding: '24px 20px',
                boxShadow: i === 2 ? `0 0 20px rgba(16, 185, 129, 0.3)` : 'none',
              }}
            >
              <div style={{ fontSize: 24, fontWeight: 600, color: TEXT, textAlign: 'center' }}>
                {item}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function PipelineScene({ title, content, label, frame }: { title: string; content: string; label?: string; frame: number }) {
  const steps = content.split(' → ');
  const progress = interpolate(frame, [0, 100], [0, 1], { extrapolateRight: 'clamp' });

  return (
    <div style={{ width: '100%' }}>
      <div
        style={{
          fontSize: 13,
          fontWeight: 600,
          letterSpacing: 2,
          color: ACCENT,
          textTransform: 'uppercase',
          marginBottom: 32,
        }}
      >
        {title}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 32 }}>
        {steps.map((step, i) => (
          <React.Fragment key={i}>
            <div
              style={{
                padding: '16px 24px',
                background: i / (steps.length - 1) <= progress ? ACCENT : 'rgba(255,255,255,0.1)',
                borderRadius: 8,
                fontSize: 20,
                fontWeight: 600,
                color: i / (steps.length - 1) <= progress ? '#0f172a' : TEXT,
                transition: 'all 0.3s',
              }}
            >
              {step}
            </div>
            {i < steps.length - 1 && (
              <div style={{ fontSize: 24, color: MUTED }}>→</div>
            )}
          </React.Fragment>
        ))}
      </div>
      {label && (
        <div
          style={{
            fontSize: 48,
            fontWeight: 800,
            color: ACCENT,
            textAlign: 'center',
          }}
        >
          {label}
        </div>
      )}
    </div>
  );
}
