// remix-screen.jsx — Remix flow (2 steps):
//   Step 1: YouTube URL → transcript + explanation (lang A).
//   Step 2: rewrite a new script (lang B) with optional user instructions.
// Self-contained. Reuses the AutoCut shell + CSS design tokens.
// Registered as a global component, rendered when appMode === "remix".

const TXT_REMIX = {
  vi: {
    title: "Viết lại kịch bản từ YouTube",
    subtitle: "Bước 1: lấy transcript + nội dung video. Bước 2: viết lại kịch bản theo ý bạn.",
    // step 1
    urlLabel: "Link YouTube",
    urlPlaceholder: "https://www.youtube.com/watch?v=…",
    langA: "Ngôn ngữ giải thích (A)",
    analyze: "Phân tích video",
    analyzing: "Đang lấy transcript & phân tích nội dung…",
    // results
    transcript: "Transcript gốc",
    sourceLang: "Ngôn ngữ gốc",
    explanation: "Nội dung video",
    newScript: "Kịch bản mới",
    // step 2
    step2Title: "Bước 2 — Viết lại kịch bản",
    langB: "Ngôn ngữ kịch bản mới (B)",
    instructions: "Hướng dẫn viết lại (tuỳ chọn)",
    instructionsPlaceholder: "VD: viết ngắn gọn hơn, giọng hài hước, nhắm Gen Z, mở đầu bằng câu hỏi gây tò mò…",
    rewrite: "Viết lại",
    rewriting: "Đang viết lại kịch bản…",
    rewriteAgain: "Viết lại lần nữa",
    // actions
    copy: "Copy",
    copied: "Đã copy!",
    download: "Tải .txt",
    sendToStudio: "Đưa sang Studio",
    newJob: "Làm video khác",
    back: "Quay lại",
    noTranscript: "Video này không có transcript. Hãy thử video khác có phụ đề.",
    failed: "Thất bại",
  },
  en: {
    title: "Remix a script from YouTube",
    subtitle: "Step 1: grab the transcript + video content. Step 2: rewrite the script your way.",
    urlLabel: "YouTube link",
    urlPlaceholder: "https://www.youtube.com/watch?v=…",
    langA: "Explanation language (A)",
    analyze: "Analyze video",
    analyzing: "Fetching transcript & analyzing content…",
    transcript: "Original transcript",
    sourceLang: "Source language",
    explanation: "Video content",
    newScript: "New script",
    step2Title: "Step 2 — Rewrite the script",
    langB: "New script language (B)",
    instructions: "Rewrite instructions (optional)",
    instructionsPlaceholder: "e.g. make it shorter, funny tone, target Gen Z, open with a curious question…",
    rewrite: "Rewrite",
    rewriting: "Rewriting the script…",
    rewriteAgain: "Rewrite again",
    copy: "Copy",
    copied: "Copied!",
    download: "Download .txt",
    sendToStudio: "Send to Studio",
    newJob: "New video",
    back: "Back",
    noTranscript: "This video has no transcript. Try another video that has captions.",
    failed: "Failed",
  },
};

const REMIX_LANG_OPTS = ["Vietnamese", "English", "Spanish", "French", "Japanese", "Korean", "Chinese"];

// ── small styled primitives (matching enhance-screen) ─────────────────────────
const rmxInput = {
  background: "var(--bg-1)", border: "1px solid var(--line)", color: "var(--fg-0)",
  borderRadius: "var(--radius)", padding: "8px 10px", fontSize: 13,
  fontFamily: "var(--font-sans)", width: "100%", boxSizing: "border-box",
};
const rmxBtn = (primary) => ({
  padding: "10px 18px", fontSize: 13.5, fontWeight: 600,
  borderRadius: "var(--radius)", cursor: "pointer", border: "none",
  background: primary ? "var(--accent)" : "var(--bg-3)",
  color: primary ? "var(--accent-fg)" : "var(--fg-1)",
});

function RmxField({ label, children }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 4, flex: 1, minWidth: 0 }}>
      <span style={{ fontSize: 10, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: ".05em" }}>{label}</span>
      {children}
    </label>
  );
}

function RmxSelect({ value, options, onChange }) {
  return (
    <select value={value} onChange={(e) => onChange(e.target.value)} style={{ ...rmxInput, cursor: "pointer" }}>
      {options.map((o) => <option key={o} value={o}>{o}</option>)}
    </select>
  );
}

// A result block with a header, copy/download actions and scrollable body.
function RmxResultCard({ title, body, T, mono, maxHeight, accent, extraActions }) {
  const [copied, setCopied] = React.useState(false);
  const copy = async () => {
    try { await navigator.clipboard.writeText(body || ""); setCopied(true); setTimeout(() => setCopied(false), 1400); } catch (e) {}
  };
  const download = () => {
    const blob = new Blob([body || ""], { type: "text/plain;charset=utf-8" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `${title.replace(/\s+/g, "_").toLowerCase()}.txt`;
    a.click();
    URL.revokeObjectURL(a.href);
  };
  return (
    <section style={{ marginBottom: 20 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
        <h3 style={{ fontSize: 14, fontWeight: 600, color: accent ? "var(--accent)" : "var(--fg-0)", margin: 0 }}>{title}</h3>
        <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
          {extraActions}
          <button onClick={copy} style={{ ...rmxBtn(false), padding: "5px 12px", fontSize: 12 }}>{copied ? T.copied : T.copy}</button>
          <button onClick={download} style={{ ...rmxBtn(false), padding: "5px 12px", fontSize: 12 }}>↓ {T.download}</button>
        </div>
      </div>
      <div style={{
        background: "var(--bg-1)", border: "1px solid var(--line)", borderRadius: "var(--radius)",
        padding: "12px 14px", fontSize: 13, lineHeight: 1.6, color: "var(--fg-1)",
        whiteSpace: "pre-wrap", maxHeight: maxHeight || 320, overflow: "auto",
        fontFamily: mono ? "var(--font-mono)" : "var(--font-sans)",
      }}>{body}</div>
    </section>
  );
}

function RmxSpinner({ label }) {
  return (
    <div style={{ textAlign: "center", paddingTop: 60 }}>
      <div style={{
        width: 40, height: 40, margin: "0 auto 20px",
        border: "3px solid var(--line)", borderTopColor: "var(--accent)",
        borderRadius: "50%", animation: "rmxspin 0.8s linear infinite",
      }} />
      <div style={{ fontSize: 15, fontWeight: 600, color: "var(--fg-0)" }}>{label}</div>
      <style>{`@keyframes rmxspin{to{transform:rotate(360deg)}}`}</style>
    </div>
  );
}

function RemixScreen({ uiLang, onSendToStudio }) {
  const T = TXT_REMIX[uiLang] || TXT_REMIX.vi;
  // input | analyzing | analyzed | rewriting | done | error
  const [phase, setPhase] = React.useState("input");
  const [url, setUrl] = React.useState("");
  const [langA, setLangA] = React.useState(uiLang === "vi" ? "Vietnamese" : "English");
  const [langB, setLangB] = React.useState(uiLang === "vi" ? "English" : "Vietnamese");
  const [instructions, setInstructions] = React.useState("");
  const [analysis, setAnalysis] = React.useState(null); // {transcript, source_lang, explanation}
  const [script, setScript] = React.useState("");
  const [error, setError] = React.useState(null);

  const wrap = { maxWidth: 880, margin: "0 auto", padding: "0 24px" };

  const readDetail = async (res) => {
    let detail = `${res.status}`;
    try { const j = await res.json(); detail = j.detail || detail; } catch (e) {}
    if (res.status === 422) detail = T.noTranscript;
    return detail;
  };

  // ── Step 1: analyze ────────────────────────────────────────────────────────
  const analyze = async () => {
    if (!url.trim()) return;
    setError(null); setScript(""); setAnalysis(null); setPhase("analyzing");
    try {
      const res = await fetch("/api/remix/analyze", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ youtube_url: url.trim(), language_a: langA }),
      });
      if (!res.ok) throw new Error(await readDetail(res));
      setAnalysis(await res.json());
      setPhase("analyzed");
    } catch (e) {
      setError(String(e.message || e));
      setPhase("error");
    }
  };

  // ── Step 2: rewrite ────────────────────────────────────────────────────────
  const rewrite = async () => {
    if (!analysis) return;
    setError(null); setPhase("rewriting");
    try {
      const res = await fetch("/api/remix/rewrite", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          transcript: analysis.transcript,
          explanation: analysis.explanation,
          language_b: langB,
          instructions: instructions,
        }),
      });
      if (!res.ok) throw new Error(await readDetail(res));
      const data = await res.json();
      setScript(data.script);
      setPhase("done");
    } catch (e) {
      setError(String(e.message || e));
      setPhase("error");
    }
  };

  const reset = () => {
    setPhase("input"); setUrl(""); setInstructions("");
    setAnalysis(null); setScript(""); setError(null);
  };

  // ── ANALYZING / REWRITING ──────────────────────────────────────────────────
  if (phase === "analyzing") return <div style={wrap}><RmxSpinner label={T.analyzing} /></div>;
  if (phase === "rewriting") return <div style={wrap}><RmxSpinner label={T.rewriting} /></div>;

  // ── ERROR ──────────────────────────────────────────────────────────────────
  if (phase === "error") {
    return (
      <div style={{ ...wrap, textAlign: "center", paddingTop: 40 }}>
        <div style={{ fontSize: 15, fontWeight: 600, color: "var(--err)" }}>⚠ {T.failed}</div>
        <pre style={{
          textAlign: "left", whiteSpace: "pre-wrap", color: "var(--fg-2)", fontSize: 12.5,
          background: "var(--bg-1)", border: "1px solid var(--line)", borderRadius: "var(--radius)",
          padding: 12, marginTop: 12, maxHeight: 240, overflow: "auto",
        }}>{error}</pre>
        <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 16 }}>
          {analysis && <button onClick={() => setPhase("analyzed")} style={rmxBtn(false)}>{T.back}</button>}
          <button onClick={reset} style={rmxBtn(false)}>{T.newJob}</button>
        </div>
      </div>
    );
  }

  // ── STEP 1: INPUT ──────────────────────────────────────────────────────────
  if (phase === "input") {
    return (
      <div style={wrap}>
        <h1 style={{ fontSize: 26, fontWeight: 700, color: "var(--fg-0)", margin: "8px 0 4px" }}>{T.title}</h1>
        <p style={{ color: "var(--fg-2)", fontSize: 14, marginTop: 0, marginBottom: 22 }}>{T.subtitle}</p>

        <RmxField label={T.urlLabel}>
          <input value={url} onChange={(e) => setUrl(e.target.value)} placeholder={T.urlPlaceholder}
            style={rmxInput}
            onKeyDown={(e) => { if (e.key === "Enter") analyze(); }} />
        </RmxField>

        <div style={{ display: "flex", gap: 14, marginTop: 16 }}>
          <RmxField label={T.langA}><RmxSelect value={langA} options={REMIX_LANG_OPTS} onChange={setLangA} /></RmxField>
          <div style={{ flex: 1 }} />
        </div>

        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 20 }}>
          <button disabled={!url.trim()} onClick={analyze}
            style={{ ...rmxBtn(true), opacity: url.trim() ? 1 : 0.5, cursor: url.trim() ? "pointer" : "not-allowed" }}>
            {T.analyze} →
          </button>
        </div>
      </div>
    );
  }

  // ── STEP 2 panel (reused by analyzed + done) ───────────────────────────────
  const a = analysis || {};
  const step2Panel = (
    <section style={{
      marginBottom: 22, padding: "16px 18px", background: "var(--bg-2)",
      border: "1px solid var(--accent-line)", borderRadius: "var(--radius-lg)",
    }}>
      <h3 style={{ fontSize: 15, fontWeight: 700, color: "var(--fg-0)", margin: "0 0 14px" }}>{T.step2Title}</h3>
      <div style={{ display: "flex", gap: 14, marginBottom: 12 }}>
        <div style={{ width: 220 }}>
          <RmxField label={T.langB}><RmxSelect value={langB} options={REMIX_LANG_OPTS} onChange={setLangB} /></RmxField>
        </div>
        <div style={{ flex: 1 }} />
      </div>
      <RmxField label={T.instructions}>
        <textarea rows={3} value={instructions} onChange={(e) => setInstructions(e.target.value)}
          placeholder={T.instructionsPlaceholder}
          style={{ ...rmxInput, resize: "vertical", lineHeight: 1.5 }} />
      </RmxField>
      <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 14 }}>
        <button onClick={rewrite} style={rmxBtn(true)}>
          {phase === "done" ? T.rewriteAgain : T.rewrite} →
        </button>
      </div>
    </section>
  );

  const analysisCards = (
    <React.Fragment>
      <RmxResultCard title={`${T.explanation} (${langA})`} body={a.explanation} T={T} maxHeight={280} />
      <RmxResultCard
        title={a.source_lang ? `${T.transcript} · ${T.sourceLang}: ${a.source_lang}` : T.transcript}
        body={a.transcript} T={T} mono maxHeight={220} />
    </React.Fragment>
  );

  // ── STEP 2: ANALYZED (ready to rewrite) ────────────────────────────────────
  if (phase === "analyzed") {
    return (
      <div style={wrap}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
          <h1 style={{ fontSize: 22, fontWeight: 700, color: "var(--fg-0)", margin: "8px 0 0" }}>✅ {T.explanation}</h1>
          <button onClick={reset} style={rmxBtn(false)}>{T.newJob}</button>
        </div>
        {step2Panel}
        {analysisCards}
        <div style={{ height: 40 }} />
      </div>
    );
  }

  // ── DONE ───────────────────────────────────────────────────────────────────
  return (
    <div style={wrap}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, color: "var(--fg-0)", margin: "8px 0 0" }}>✅ {T.newScript}</h1>
        <button onClick={reset} style={rmxBtn(false)}>{T.newJob}</button>
      </div>

      <RmxResultCard title={`${T.newScript} (${langB})`} body={script} T={T} accent maxHeight={360}
        extraActions={
          <button onClick={() => onSendToStudio && onSendToStudio(script, langB)}
            style={{ ...rmxBtn(true), padding: "5px 12px", fontSize: 12 }}>→ {T.sendToStudio}</button>
        } />

      {step2Panel}
      {analysisCards}
      <div style={{ height: 40 }} />
    </div>
  );
}
