import React from "react";
import {
  AbsoluteFill,
  Img,
  staticFile,
  useCurrentFrame,
  useVideoConfig,
  Sequence,
  interpolate,
  Easing,
} from "remotion";
import { Audio } from "@remotion/media";
import { Video } from "@remotion/media";
import { TransitionSeries, linearTiming } from "@remotion/transitions";
import { slide } from "@remotion/transitions/slide";
import { fade } from "@remotion/transitions/fade";
import { Captions } from "./Captions";
import { FONT_FAMILY } from "./fonts";

const TRANSITION_FRAMES = 6;
const CTA_DURATION = 210;

// ─── Localized CTA strings ─────────────────────────────────

const CTA_STRINGS: Record<string, { tagline: string; button: string }> = {
  en: { tagline: "Play together. Every day.", button: "Try Today!" },
  fr: { tagline: "Jouez ensemble. Chaque jour.", button: "Essayez aujourd'hui !" },
  es: { tagline: "Jueguen juntos. Cada día.", button: "¡Pruébalo hoy!" },
  it: { tagline: "Giocate insieme. Ogni giorno.", button: "Provalo oggi!" },
  pt: { tagline: "Brinquem juntos. Todo dia.", button: "Experimente hoje!" },
  de: { tagline: "Spielt zusammen. Jeden Tag.", button: "Jetzt ausprobieren!" },
};

type ClipDef = { file: string; title: string; durationFrames: number };

export type HeartyAdProps = {
  clips: ClipDef[];
  lang?: string; // "en" | "fr" | "es" | "it" | "pt" | "de"
  voFile?: string; // override voiceover mp3 path (relative to public/)
  srtFile?: string; // override srt path (relative to public/)
  ctaDuration?: number; // override CTA card duration in frames (default 210)
};

// ─── Clip sets ──────────────────────────────────────────────

export const CLIPS_V1: ClipDef[] = [
  { file: "clips/01_felt_tip_pens.mp4", title: "Falling Felt-Tip Pens", durationFrames: 75 },
  { file: "clips/02_treasure_map.mp4", title: "Treasure Map", durationFrames: 78 },
  { file: "clips/03_sponge_sailboat.mp4", title: "Sponge Sailboat", durationFrames: 72 },
  { file: "clips/04_pom_pom_popper.mp4", title: "Clown Pom Pom Popper", durationFrames: 60 },
  { file: "clips/05_worry_rocks.mp4", title: "Worry Rocks", durationFrames: 72 },
  { file: "clips/06_water_battles.mp4", title: "Water Battles", durationFrames: 60 },
  { file: "clips/07_fruits_box.mp4", title: "Fruits in the Box", durationFrames: 60 },
];

export const CLIPS_V2: ClipDef[] = [
  { file: "clips-v2/01_three_legged_race.mp4", title: "Three-Legged Race", durationFrames: 75 },
  { file: "clips-v2/02_ping_pong_cup.mp4", title: "Ping Pong Cup Challenge", durationFrames: 78 },
  { file: "clips-v2/03_air_hockey.mp4", title: "Dining Table Air Hockey", durationFrames: 72 },
  { file: "clips-v2/04_gift_unwrap.mp4", title: "Gift Unwrap Challenge", durationFrames: 60 },
  { file: "clips-v2/05_helicopter_rope.mp4", title: "Helicopter Rope Game", durationFrames: 72 },
  { file: "clips-v2/06_catch_tail.mp4", title: "Catch My Tail", durationFrames: 60 },
  { file: "clips-v2/07_balloon_cup.mp4", title: "Balloon World Cup", durationFrames: 60 },
];

export const CLIPS_V3: ClipDef[] = [
  { file: "clips-v3/01_rainbow_spinner.mp4", title: "Rainbow Paper Spinner", durationFrames: 75 },
  { file: "clips-v3/02_oil_milk_art.mp4", title: "Oil & Milk Droplet Art", durationFrames: 78 },
  { file: "clips-v3/03_shake_color.mp4", title: "Shake & Color Surprise", durationFrames: 72 },
  { file: "clips-v3/04_dot_art.mp4", title: "Dot Art Fun", durationFrames: 60 },
  { file: "clips-v3/05_dancing_paper.mp4", title: "Dancing Paper People", durationFrames: 72 },
  { file: "clips-v3/06_floral_straw.mp4", title: "Floral Paper Straw Art", durationFrames: 60 },
  { file: "clips-v3/07_foil_bubble.mp4", title: "Foil Flower Bubble Magic", durationFrames: 60 },
];

export const CLIPS_V4: ClipDef[] = [
  { file: "clips-v4/01_water_gun_paint.mp4", title: "Water Gun T-Shirt Painting", durationFrames: 75 },
  { file: "clips-v4/02_balloon_race.mp4", title: "Head-to-Head Balloon Race", durationFrames: 78 },
  { file: "clips-v4/03_shower_paint.mp4", title: "Shower Curtain Painting", durationFrames: 72 },
  { file: "clips-v4/04_zip_line.mp4", title: "Zip Line Your Balloon!", durationFrames: 60 },
  { file: "clips-v4/05_dough_monsters.mp4", title: "Modeling Dough Monsters", durationFrames: 72 },
  { file: "clips-v4/06_potato_hedgehog.mp4", title: "Potato Hedgehog Craft", durationFrames: 60 },
  { file: "clips-v4/07_ping_pong.mp4", title: "Ping Pong Cup Challenge", durationFrames: 60 },
];

// ─── Iteration A: Fresh craft/science clips ─────────────────
export const CLIPS_A: ClipDef[] = [
  { file: "clips-a/01_leaky_cup.mp4", title: "Leaky Cup Experiment", durationFrames: 75 },
  { file: "clips-a/02_color_bubbles.mp4", title: "Colorful Bubble Painting", durationFrames: 78 },
  { file: "clips-a/03_lollipop_flowers.mp4", title: "Lollipop Paper Flowers", durationFrames: 72 },
  { file: "clips-a/04_unpoppable_bubbles.mp4", title: "Unpoppable Bubbles", durationFrames: 60 },
  { file: "clips-a/05_paper_heart.mp4", title: "Paper Heart Wreath", durationFrames: 72 },
  { file: "clips-a/06_paper_rocket.mp4", title: "Paper Rocket Launch", durationFrames: 60 },
  { file: "clips-a/07_sunken_ship.mp4", title: "Sunken Ship Trick", durationFrames: 60 },
];

// ─── Iteration B: Hook swap tests (V3 clips, different opener) ──
// B1: Oil & Milk Droplet Art opens (currently clip 2 in V3)
export const CLIPS_B1: ClipDef[] = [
  { file: "clips-v3/02_oil_milk_art.mp4", title: "Oil & Milk Droplet Art", durationFrames: 75 },
  { file: "clips-v3/01_rainbow_spinner.mp4", title: "Rainbow Paper Spinner", durationFrames: 78 },
  { file: "clips-v3/03_shake_color.mp4", title: "Shake & Color Surprise", durationFrames: 72 },
  { file: "clips-v3/04_dot_art.mp4", title: "Dot Art Fun", durationFrames: 60 },
  { file: "clips-v3/05_dancing_paper.mp4", title: "Dancing Paper People", durationFrames: 72 },
  { file: "clips-v3/06_floral_straw.mp4", title: "Floral Paper Straw Art", durationFrames: 60 },
  { file: "clips-v3/07_foil_bubble.mp4", title: "Foil Flower Bubble Magic", durationFrames: 60 },
];

// B2: Leaky Cup (colorful rain) opens — strongest "satisfying" moment
export const CLIPS_B2: ClipDef[] = [
  { file: "clips-a/01_leaky_cup.mp4", title: "Leaky Cup Experiment", durationFrames: 75 },
  { file: "clips-v3/01_rainbow_spinner.mp4", title: "Rainbow Paper Spinner", durationFrames: 78 },
  { file: "clips-v3/02_oil_milk_art.mp4", title: "Oil & Milk Droplet Art", durationFrames: 72 },
  { file: "clips-v3/04_dot_art.mp4", title: "Dot Art Fun", durationFrames: 60 },
  { file: "clips-v3/05_dancing_paper.mp4", title: "Dancing Paper People", durationFrames: 72 },
  { file: "clips-v3/06_floral_straw.mp4", title: "Floral Paper Straw Art", durationFrames: 60 },
  { file: "clips-v3/07_foil_bubble.mp4", title: "Foil Flower Bubble Magic", durationFrames: 60 },
];

// B3: Unpoppable Bubbles opens — kid wow moment
export const CLIPS_B3: ClipDef[] = [
  { file: "clips-a/04_unpoppable_bubbles.mp4", title: "Unpoppable Bubbles", durationFrames: 75 },
  { file: "clips-v3/01_rainbow_spinner.mp4", title: "Rainbow Paper Spinner", durationFrames: 78 },
  { file: "clips-v3/02_oil_milk_art.mp4", title: "Oil & Milk Droplet Art", durationFrames: 72 },
  { file: "clips-v3/03_shake_color.mp4", title: "Shake & Color Surprise", durationFrames: 60 },
  { file: "clips-v3/04_dot_art.mp4", title: "Dot Art Fun", durationFrames: 72 },
  { file: "clips-v3/06_floral_straw.mp4", title: "Floral Paper Straw Art", durationFrames: 60 },
  { file: "clips-v3/07_foil_bubble.mp4", title: "Foil Flower Bubble Magic", durationFrames: 60 },
];

// ─── Iteration D1: V3 clips + app UI during "open the app" VO ──
// Activity clips fill 0s–12.9s; app UI clips fill 12.9s–17s; CTA = 4s
export const CLIPS_D1: ClipDef[] = [
  // Activity clips (net ~12.9s)
  { file: "clips-v3/01_rainbow_spinner.mp4", title: "Rainbow Paper Spinner", durationFrames: 85 },
  { file: "clips-v3/02_oil_milk_art.mp4", title: "Oil & Milk Droplet Art", durationFrames: 84 },
  { file: "clips-v3/03_shake_color.mp4", title: "Shake & Color Surprise", durationFrames: 84 },
  { file: "clips-v3/04_dot_art.mp4", title: "Dot Art Fun", durationFrames: 84 },
  { file: "clips-v3/05_dancing_paper.mp4", title: "Dancing Paper People", durationFrames: 80 },
  // App UI clips during "Just open the app, pick one" (~12.9s–17s VO)
  { file: "clips-app/01_carousel_scroll.mp4", title: "App: Browse Ideas", durationFrames: 50 },
  { file: "clips-app/02_tap_indoor.mp4", title: "App: Pick Category", durationFrames: 45 },
  { file: "clips-app/03_grid_scroll.mp4", title: "App: Activity Grid", durationFrames: 50 },
];

// ─── Iteration E: 15s cut (5 clips from V3) ────────────────
export const CLIPS_E: ClipDef[] = [
  { file: "clips-v3/01_rainbow_spinner.mp4", title: "Rainbow Paper Spinner", durationFrames: 60 },
  { file: "clips-v3/02_oil_milk_art.mp4", title: "Oil & Milk Droplet Art", durationFrames: 60 },
  { file: "clips-v3/04_dot_art.mp4", title: "Dot Art Fun", durationFrames: 54 },
  { file: "clips-v3/05_dancing_paper.mp4", title: "Dancing Paper People", durationFrames: 54 },
  { file: "clips-v3/06_floral_straw.mp4", title: "Floral Paper Straw Art", durationFrames: 54 },
];

// ─── Title overlay ──────────────────────────────────────────

/** Shows activity title at the top, within 3:4 safe zone */
const ActivityTitle: React.FC<{ title: string }> = ({ title }) => {
  const frame = useCurrentFrame();
  const { fps, height, width } = useVideoConfig();

  // In 9:16 (1920), 3:4 safe zone starts at 240px.
  // In 3:4 (1440), no inset needed — use a small padding.
  const safeTop = height > width * (4 / 3) + 1
    ? Math.round((height - width * (4 / 3)) / 2) + 20
    : 30;

  // Slide in + fade
  const opacity = interpolate(frame, [0, 0.2 * fps], [0, 1], {
    extrapolateRight: "clamp",
  });
  const translateY = interpolate(frame, [0, 0.25 * fps], [-20, 0], {
    extrapolateRight: "clamp",
    easing: Easing.out(Easing.cubic),
  });

  return (
    <AbsoluteFill
      style={{
        justifyContent: "flex-start",
        alignItems: "center",
        paddingTop: safeTop,
        pointerEvents: "none",
      }}
    >
      <div
        style={{
          opacity,
          transform: `translateY(${translateY}px)`,
          backgroundColor: "rgba(0, 0, 0, 0.55)",
          borderRadius: 14,
          padding: "10px 28px",
        }}
      >
        <span
          style={{
            fontSize: 38,
            fontWeight: 700,
            fontFamily: FONT_FAMILY,
            color: "white",
            textShadow: "0 2px 8px rgba(0,0,0,0.5)",
          }}
        >
          {title}
        </span>
      </div>
    </AbsoluteFill>
  );
};

// ─── Clip + Video ───────────────────────────────────────────

const ClipScene: React.FC<{ file: string }> = ({ file }) => {
  return (
    <AbsoluteFill>
      <Video
        src={staticFile(file)}
        style={{
          width: "100%",
          height: "100%",
          objectFit: "cover",
        }}
        muted
      />
    </AbsoluteFill>
  );
};

// ─── CTA Card ───────────────────────────────────────────────

const CTACard: React.FC<{ lang: string }> = ({ lang }) => {
  const strings = CTA_STRINGS[lang] || CTA_STRINGS.en;
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

  const logoScale = interpolate(frame, [0, 0.4 * fps], [0.5, 1], {
    extrapolateRight: "clamp",
    easing: Easing.out(Easing.back(1.5)),
  });

  const textOpacity = interpolate(frame, [0.3 * fps, 0.7 * fps], [0, 1], {
    extrapolateLeft: "clamp",
    extrapolateRight: "clamp",
  });

  const ctaY = interpolate(frame, [0.5 * fps, 0.9 * fps], [40, 0], {
    extrapolateLeft: "clamp",
    extrapolateRight: "clamp",
    easing: Easing.out(Easing.cubic),
  });

  const ctaOpacity = interpolate(frame, [0.5 * fps, 0.9 * fps], [0, 1], {
    extrapolateLeft: "clamp",
    extrapolateRight: "clamp",
  });

  return (
    <AbsoluteFill
      style={{
        background:
          "linear-gradient(180deg, #FF6B6B 0%, #FF8E53 50%, #FFD93D 100%)",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <Img
        src={staticFile("app_icon.png")}
        style={{
          width: 220,
          height: 220,
          borderRadius: 48,
          transform: `scale(${logoScale})`,
          boxShadow: "0 12px 40px rgba(0,0,0,0.25)",
        }}
      />

      <div
        style={{
          transform: `scale(${logoScale})`,
          fontSize: 110,
          fontWeight: 900,
          fontFamily: FONT_FAMILY,
          color: "white",
          textShadow: "0 4px 20px rgba(0,0,0,0.2)",
          letterSpacing: -2,
          marginTop: 30,
        }}
      >
        Hearty
      </div>

      <div
        style={{
          opacity: textOpacity,
          fontSize: 42,
          fontWeight: 600,
          fontFamily: FONT_FAMILY,
          color: "white",
          marginTop: 20,
          textShadow: "0 2px 10px rgba(0,0,0,0.15)",
        }}
      >
        {strings.tagline}
      </div>

      <div
        style={{
          opacity: ctaOpacity,
          transform: `translateY(${ctaY}px)`,
          marginTop: 60,
          backgroundColor: "white",
          borderRadius: 60,
          padding: "24px 80px",
          boxShadow: "0 8px 30px rgba(0,0,0,0.15)",
        }}
      >
        <span
          style={{
            fontSize: 40,
            fontWeight: 800,
            fontFamily: FONT_FAMILY,
            color: "#FF6B6B",
          }}
        >
          {strings.button}
        </span>
      </div>
    </AbsoluteFill>
  );
};

// ─── Title timing helper ────────────────────────────────────

/**
 * Compute the start frame for each clip inside a TransitionSeries.
 * Each transition eats TRANSITION_FRAMES from the timeline.
 */
function getClipStartFrames(clips: ClipDef[]): number[] {
  const starts: number[] = [];
  let cursor = 0;
  for (let i = 0; i < clips.length; i++) {
    starts.push(cursor);
    cursor += clips[i].durationFrames;
    if (i < clips.length - 1) {
      cursor -= TRANSITION_FRAMES; // transition overlap
    }
  }
  return starts;
}

// ─── Main composition ───────────────────────────────────────

export const HeartyAd: React.FC<HeartyAdProps> = ({
  clips,
  lang = "en",
  voFile,
  srtFile: srtFileOverride,
  ctaDuration,
}) => {
  const ctaFrames = ctaDuration ?? CTA_DURATION;
  const { fps } = useVideoConfig();

  // Audio/SRT paths — use overrides if provided, else language-based defaults
  const voicePath =
    voFile ?? (lang === "en" ? "voiceover/voiceover.mp3" : `voiceover/${lang}/voiceover.mp3`);
  const srtPath =
    srtFileOverride ?? (lang === "en" ? "voiceover/voiceover.srt" : `voiceover/${lang}/voiceover.srt`);

  const clipStarts = getClipStartFrames(clips);

  const directions: Array<
    "from-left" | "from-right" | "from-top" | "from-bottom"
  > = [
    "from-right",
    "from-left",
    "from-bottom",
    "from-right",
    "from-left",
    "from-top",
  ];

  return (
    <AbsoluteFill style={{ backgroundColor: "black" }}>
      {/* Clip montage with transitions */}
      <TransitionSeries>
        {clips.map((clip, i) => {
          const elements = [];

          elements.push(
            <TransitionSeries.Sequence
              key={`clip-${i}`}
              durationInFrames={clip.durationFrames}
            >
              <ClipScene file={clip.file} />
            </TransitionSeries.Sequence>
          );

          if (i < clips.length - 1) {
            elements.push(
              <TransitionSeries.Transition
                key={`trans-${i}`}
                presentation={slide({
                  direction: directions[i % directions.length],
                })}
                timing={linearTiming({ durationInFrames: TRANSITION_FRAMES })}
              />
            );
          }

          return elements;
        })}

        <TransitionSeries.Transition
          presentation={fade()}
          timing={linearTiming({ durationInFrames: 10 })}
        />
        <TransitionSeries.Sequence durationInFrames={ctaFrames}>
          <CTACard lang={lang} />
        </TransitionSeries.Sequence>
      </TransitionSeries>

      {/* Voiceover */}
      <Audio src={staticFile(voicePath)} volume={1} />

      {/* Background music */}
      <Audio
        src={staticFile("bg-music.mp3")}
        volume={(f) =>
          interpolate(
            f,
            [0, 0.5 * fps, 18 * fps, 21 * fps],
            [0, 0.12, 0.12, 0],
            { extrapolateLeft: "clamp", extrapolateRight: "clamp" }
          )
        }
      />

      {/* Captions */}
      <Captions srtFile={srtPath} />

      {/* Gradient overlay */}
      <AbsoluteFill
        style={{
          background:
            "linear-gradient(180deg, rgba(0,0,0,0.3) 0%, transparent 15%, transparent 75%, rgba(0,0,0,0.4) 100%)",
          pointerEvents: "none",
        }}
      />
    </AbsoluteFill>
  );
};
