/* translate.jsx — Translate entire resume to another language */

const LANGUAGES = [
  { code: "ar", label: "Arabic", rtl: true },
  { code: "fr", label: "French" },
  { code: "es", label: "Spanish" },
  { code: "bn", label: "Bengali" },
  { code: "de", label: "German" },
  { code: "pt", label: "Portuguese" },
  { code: "zh", label: "Chinese (Simplified)" },
  { code: "hi", label: "Hindi" },
  { code: "ms", label: "Malay" },
  { code: "tr", label: "Turkish" },
  { code: "ru", label: "Russian" },
  { code: "ja", label: "Japanese" },
];

function TranslateDrawer({ data, patch, onClose }) {
  const { useState: S, useEffect: E } = React;
  const [lang,     setLang]    = S("fr");
  const [stage,    setStage]   = S("idle"); // idle | loading | done | error
  const [errMsg,   setErrMsg]  = S("");
  const [limitHit, setLimitHit] = S(false);
  const [preview,  setPreview] = S(null);

  E(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const translate = async () => {
    if (!window.groqStream) { setErrMsg("AI not available."); setStage("error"); return; }
    setStage("loading");
    setPreview(null);
    setErrMsg("");

    const langLabel = LANGUAGES.find(l => l.code === lang)?.label || lang;

    // Collect all translatable text fields into a flat map
    const fields = {};
    if (data.summary) fields["summary"] = data.summary;
    (data.experience || []).forEach((x, xi) => {
      (x.bullets || []).forEach((b, bi) => { if (b.trim()) fields[`exp_${xi}_${bi}`] = b; });
    });
    (data.projects || []).forEach((x, xi) => {
      if (x.detail) fields[`proj_${xi}_detail`] = x.detail;
      (x.bullets || []).forEach((b, bi) => { if (b.trim()) fields[`proj_${xi}_${bi}`] = b; });
    });
    (data.education || []).forEach((x, xi) => {
      if (x.detail) fields[`edu_${xi}_detail`] = x.detail;
    });
    (data.activities || []).forEach((a, ai) => {
      if (a.detail) fields[`act_${ai}_detail`] = a.detail;
    });
    (data.certs || []).forEach((c, ci) => {
      if (c) fields[`cert_${ci}`] = c;
    });

    const payload = JSON.stringify(fields);
    let raw = "";

    await window.groqStream({
      messages: [
        { role: "system", content: "You are a professional resume translator. Preserve resume formatting, action verbs style, and professional tone. Translate all values but keep keys identical. Return ONLY valid JSON, no explanation." },
        { role: "user", content: `Translate all values in this JSON object to ${langLabel}. Keep all JSON keys exactly the same. Return ONLY the translated JSON object:\n\n${payload}` },
      ],
      maxTokens: 3000,
      onChunk: (_, full) => { raw = full; },
      onDone: () => {
        try {
          let s = raw.trim().replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/i,"");
          const translated = JSON.parse(s.match(/\{[\s\S]*\}/)?.[0] || s);

          // Rebuild data with translated fields
          const nd = JSON.parse(JSON.stringify(data)); // deep clone
          if (translated.summary) nd.summary = translated.summary;

          (nd.experience || []).forEach((x, xi) => {
            (x.bullets || []).forEach((b, bi) => {
              const key = `exp_${xi}_${bi}`;
              if (translated[key]) x.bullets[bi] = translated[key];
            });
          });
          (nd.projects || []).forEach((x, xi) => {
            if (translated[`proj_${xi}_detail`]) x.detail = translated[`proj_${xi}_detail`];
            (x.bullets || []).forEach((b, bi) => {
              if (translated[`proj_${xi}_${bi}`]) x.bullets[bi] = translated[`proj_${xi}_${bi}`];
            });
          });
          (nd.education || []).forEach((x, xi) => {
            if (translated[`edu_${xi}_detail`]) x.detail = translated[`edu_${xi}_detail`];
          });
          (nd.activities || []).forEach((a, ai) => {
            if (translated[`act_${ai}_detail`]) a.detail = translated[`act_${ai}_detail`];
          });
          (nd.certs || []).forEach((c, ci) => {
            if (translated[`cert_${ci}`]) nd.certs[ci] = translated[`cert_${ci}`];
          });

          setPreview(nd);
          setStage("done");
        } catch(_) {
          setErrMsg("Could not parse translation. Try again.");
          setStage("error");
        }
      },
      onError: (e) => { if (e === "free_limit_reached") { setLimitHit(true); } else { setErrMsg(typeof e === "string" ? e : "AI error."); } setStage("error"); },
    });
  };

  const applyTranslation = () => {
    if (!preview) return;
    patch(() => preview);
    onClose();
  };

  const selectedLang = LANGUAGES.find(l => l.code === lang);

  return (
    <>
      <div className="drawer-back" onClick={onClose} />
      <div className="drawer" style={{ width: 420 }}>
        <div className="drawer-h" style={{ display:"flex", alignItems:"center" }}>
          <div>
            <h3 style={{ margin:0, fontSize:16, fontWeight:700, color:"var(--navy)" }}>Translate Resume</h3>
            <p style={{ margin:"3px 0 0", fontSize:12.5, color:"var(--slate-500)" }}>AI rewrites content in any language</p>
          </div>
          <div style={{ flex:1 }} />
          <button className="x" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="drawer-body scroll" style={{ padding:"20px 20px 24px" }}>

          {/* Language picker */}
          <div style={{ marginBottom:20 }}>
            <label style={{ fontSize:12, fontWeight:700, color:"var(--slate-600)", textTransform:"uppercase", letterSpacing:".06em", display:"block", marginBottom:8 }}>
              Target language
            </label>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:8 }}>
              {LANGUAGES.map(l => (
                <button key={l.code}
                  onClick={() => setLang(l.code)}
                  style={{
                    padding:"9px 12px", borderRadius:9, border:"2px solid",
                    borderColor: lang === l.code ? "var(--brand-blue)" : "var(--slate-200)",
                    background: lang === l.code ? "rgba(28,155,230,.06)" : "#fff",
                    color: lang === l.code ? "var(--brand-blue)" : "var(--slate-700)",
                    fontWeight: lang === l.code ? 700 : 500,
                    fontSize: 13, cursor:"pointer", textAlign:"left", transition:"all .14s",
                    display:"flex", alignItems:"center", gap:8,
                  }}>
                  {lang === l.code && <Icon name="check" size={13} style={{ color:"var(--brand-blue)", flexShrink:0 }} />}
                  {l.label}
                  {l.rtl && <span style={{ fontSize:10, color:"var(--slate-400)", marginLeft:"auto" }}>RTL</span>}
                </button>
              ))}
            </div>
          </div>

          {/* Info */}
          <div style={{ background:"var(--grad-soft)", border:"1px solid rgba(28,155,230,.15)", borderRadius:10, padding:"12px 14px", marginBottom:20, fontSize:12.5, color:"var(--slate-600)", lineHeight:1.55 }}>
            <strong style={{ color:"var(--navy)" }}>What gets translated:</strong> Summary, all bullet points, project descriptions, education details, activity descriptions, certifications.<br />
            <strong style={{ color:"var(--navy)" }}>Kept in English:</strong> Names, companies, schools, dates, contact info.
          </div>

          {stage === "idle" && (
            <button className="btn btn-grad" style={{ width:"100%", justifyContent:"center" }} onClick={translate}>
              <Icon name="writeai" size={15} /> Translate to {selectedLang?.label}
            </button>
          )}

          {stage === "loading" && (
            <div style={{ textAlign:"center", padding:"24px 0" }}>
              <span className="spin" style={{ width:28, height:28, borderWidth:3, borderColor:"rgba(28,155,230,.2)", borderTopColor:"var(--brand-blue)", display:"inline-block" }} />
              <p style={{ marginTop:14, color:"var(--slate-500)", fontSize:13 }}>Translating to {selectedLang?.label}…</p>
            </div>
          )}

          {stage === "error" && (limitHit ? <ProUpgradeCard onClose={onClose} /> : (
            <div style={{ textAlign:"center" }}>
              <p style={{ color:"var(--danger)", marginBottom:12 }}>{errMsg}</p>
              <button className="btn btn-grad" onClick={translate}>Try again</button>
            </div>
          ))}

          {stage === "done" && preview && (
            <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
              <div style={{ background:"rgba(22,163,107,.08)", border:"1px solid rgba(22,163,107,.2)", borderRadius:10, padding:"12px 14px", fontSize:13, color:"var(--good)", fontWeight:600 }}>
                ✓ Translation complete — {selectedLang?.label} version ready
              </div>
              <p style={{ fontSize:12.5, color:"var(--slate-500)", margin:"4px 0 8px", lineHeight:1.5 }}>
                Applying will replace your current resume content with the {selectedLang?.label} translation. Your names, companies, and dates remain unchanged.
              </p>
              <button className="btn btn-grad" style={{ width:"100%", justifyContent:"center" }} onClick={applyTranslation}>
                Apply {selectedLang?.label} Translation
              </button>
              <button className="btn btn-ghost btn-sm" style={{ width:"100%", justifyContent:"center" }} onClick={() => { setStage("idle"); setPreview(null); }}>
                Cancel
              </button>
              <div style={{ borderTop:"1px solid var(--slate-100)", paddingTop:14, marginTop:4 }}>
                <button className="btn btn-ghost btn-sm" onClick={() => { setLang(lang); setStage("idle"); }}>
                  ← Try a different language
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
