/**
 * Storyboard / Storytelling types
 */

export type StoryboardStyle =
  | "cinematic"
  | "documentary"
  | "social_media"
  | "ugc"
  | "explainer"
  | "emotional"
  | "humorous";

export type StoryboardLength =
  | "short"    // 3-5 scenes
  | "medium"   // 6-9 scenes
  | "long"     // 10-15 scenes
  | "custom";  // user-defined scene count

export type OutputLanguage = "id" | "en";

/** Preset durasi per scene */
export type SceneDurationPreset =
  | "2-3s"
  | "3-5s"
  | "5-8s"
  | "8-12s"
  | "custom";

/** Target total durasi video */
export type TotalDurationPreset =
  | "15s"
  | "30s"
  | "60s"
  | "90s"
  | "3min"
  | "5min"
  | "custom";

export interface StoryboardScene {
  sceneNumber: number;
  title: string;
  narration: string;
  visualDescription: string;
  duration: string;           // e.g. "3-5 detik"
  cameraAngle?: string;
  emotion?: string;
  transition?: string;
}

export interface StoryboardOutput {
  sourceUrl: string;
  sourcePlatform: string;
  sourceTitle: string;
  theme: string;
  hook: string;
  summary: string;
  callToAction: string;
  scenes: StoryboardScene[];
  metadata: {
    generatedAt: string;
    model: string;
    style: StoryboardStyle;
    length: StoryboardLength;
    totalScenes: number;
    estimatedDuration: string;
    sceneCount: number;
    sceneDuration: string;
    totalDuration: string;
  };
}

export interface StoryboardRequest {
  url: string;
  style: StoryboardStyle;
  length: StoryboardLength;
  language: OutputLanguage;
  tone?: string;
  targetAudience?: string;
  customInstructions?: string;
  // Kustomisasi scene
  customSceneCount?: number;       // 1-30, aktif jika length = "custom"
  sceneDurationPreset?: SceneDurationPreset;
  customSceneDuration?: string;    // aktif jika sceneDurationPreset = "custom"
  totalDurationPreset?: TotalDurationPreset;
  customTotalDuration?: string;    // aktif jika totalDurationPreset = "custom"
}

export interface StoryboardHistoryItem {
  id: string;
  user_id: string;
  source_url: string;
  source_platform: string;
  source_title: string;
  style: StoryboardStyle;
  length: StoryboardLength;
  language: OutputLanguage;
  output: StoryboardOutput;
  is_favorite: boolean;
  created_at: string;
}

// ── Config constants ──────────────────────────────────────────────────────────

export const STORYBOARD_STYLES: Record<StoryboardStyle, { label: string; icon: string; description: string }> = {
  cinematic:    { label: "Cinematic",    icon: "🎬", description: "Dramatis, sinematik, nuansa film" },
  documentary:  { label: "Dokumenter",  icon: "📹", description: "Faktual, informatif, terstruktur" },
  social_media: { label: "Social Media",icon: "📱", description: "Singkat, catchy, viral-ready" },
  ugc:          { label: "UGC",         icon: "🤳", description: "Kasual, autentik, user-generated feel" },
  explainer:    { label: "Explainer",   icon: "💡", description: "Edukatif, jelas, step-by-step" },
  emotional:    { label: "Emotional",   icon: "💖", description: "Menyentuh hati, penuh empati" },
  humorous:     { label: "Humoris",     icon: "😄", description: "Ringan, lucu, menghibur" },
};

export const STORYBOARD_LENGTHS: Record<StoryboardLength, { label: string; scenes: string; duration: string; count?: [number, number] }> = {
  short:  { label: "Pendek",   scenes: "3–5 scene",   duration: "15–30 detik",  count: [3, 5]   },
  medium: { label: "Sedang",   scenes: "6–9 scene",   duration: "30–60 detik",  count: [6, 9]   },
  long:   { label: "Panjang",  scenes: "10–15 scene", duration: "1–3 menit",    count: [10, 15] },
  custom: { label: "Custom",   scenes: "kamu tentukan", duration: "kamu tentukan" },
};

export const SCENE_DURATION_PRESETS: Record<SceneDurationPreset, { label: string; value: string }> = {
  "2-3s":  { label: "2–3 detik",  value: "2-3 detik"  },
  "3-5s":  { label: "3–5 detik",  value: "3-5 detik"  },
  "5-8s":  { label: "5–8 detik",  value: "5-8 detik"  },
  "8-12s": { label: "8–12 detik", value: "8-12 detik" },
  "custom":{ label: "Custom",     value: ""            },
};

export const TOTAL_DURATION_PRESETS: Record<TotalDurationPreset, { label: string; value: string }> = {
  "15s":   { label: "15 detik", value: "15 detik"  },
  "30s":   { label: "30 detik", value: "30 detik"  },
  "60s":   { label: "60 detik", value: "60 detik"  },
  "90s":   { label: "90 detik", value: "90 detik"  },
  "3min":  { label: "3 menit",  value: "3 menit"   },
  "5min":  { label: "5 menit",  value: "5 menit"   },
  "custom":{ label: "Custom",   value: ""           },
};

// ── GPT Image Prompt Generation ──────────────────────────────────────────────

export type GptImageAspectRatio = "1:1" | "16:9" | "9:16" | "4:3" | "3:4";
export type GptImageQuality     = "standard" | "hd";

export interface GptImageScenePrompt {
  sceneNumber:    number;
  title:          string;
  prompt:         string;   // Prompt lengkap siap pakai di GPT Image
  negativeHint:   string;   // Hal yang harus dihindari (catatan, bukan param resmi DALL-E)
  compositionNote: string;  // Penjelasan singkat komposisi/sudut kamera
  colorMood:      string;   // Palet warna & mood dominan scene ini
  aspectRatio:    GptImageAspectRatio;
  quality:        GptImageQuality;
}

export interface GptImagePromptsOutput {
  scenePrompts: GptImageScenePrompt[];
  storyboardStyle: string;
  metadata: {
    generatedAt:  string;
    model:        string;
    aspectRatio:  GptImageAspectRatio;
    quality:      GptImageQuality;
    totalScenes:  number;
  };
}

export interface GptImagePromptsRequest {
  scenes:       StoryboardScene[];
  style:        StoryboardStyle;
  language:     OutputLanguage;
  aspectRatio?: GptImageAspectRatio;
  quality?:     GptImageQuality;
  extraContext?: string;   // tema/hook dari storyboard induk
}

/** Hitung estimasi jumlah scene dari total durasi + durasi per scene */
export function estimateSceneCount(
  totalDuration: string,
  sceneDuration: string
): number | null {
  const totalSec = parseDurationToSeconds(totalDuration);
  const sceneSec = parseDurationToSeconds(sceneDuration);
  if (!totalSec || !sceneSec) return null;
  return Math.max(1, Math.round(totalSec / sceneSec));
}

function parseDurationToSeconds(str: string): number | null {
  if (!str) return null;
  const s = str.toLowerCase().trim();
  // "30 detik" / "30s" / "30 sec"
  const secMatch = s.match(/(\d+(?:\.\d+)?)\s*(?:detik|sec|s\b)/);
  if (secMatch) return parseFloat(secMatch[1]);
  // "3 menit" / "3 min" / "3m"
  const minMatch = s.match(/(\d+(?:\.\d+)?)\s*(?:menit|min|m\b)/);
  if (minMatch) return parseFloat(minMatch[1]) * 60;
  // plain number → assume seconds
  const plain = parseFloat(s);
  if (!isNaN(plain)) return plain;
  return null;
}
