/* import-cv.jsx — Import existing CV via file upload or paste */

function ImportCVModal({ onApply, onClose }) {
  const { useState: S, useRef: R, useEffect: E } = React;

  const [tab,       setTab]      = S("paste");
  const [pasteText, setPaste]    = S("");
  const [file,      setFile]     = S(null);
  const [stage,     setStage]    = S("input"); // "input" | "parsing" | "review" | "error"
  const [parsed,    setParsed]   = S(null);
  const [statusMsg, setStatus]   = S("Reading your CV…");
  const [error,     setError]    = S("");
  const [dragOver,  setDragOver] = S(false);
  const [progress,  setProgress] = S(0);
  const [limitHit,  setLimitHit] = S(false);
  const [remaining, setRemaining] = S(() => window.getAIUsesRemaining ? window.getAIUsesRemaining() : 10);

  const fileRef  = R(null);

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

  // Animate progress bar while parsing (asymptotic to 90%, jumps to 100 when done)
  E(() => {
    if (stage !== "parsing") return;
    setProgress(0);
    const id = setInterval(() => {
      setProgress(p => {
        const next = p + (90 - p) * 0.045;
        return next >= 89.5 ? 89.5 : next;
      });
    }, 180);
    return () => clearInterval(id);
  }, [stage]);

  /* ── Text extraction ──────────────────────────────────────── */
  const extractFromFile = async (f) => {
    const ext = f.name.split(".").pop().toLowerCase();

    if (ext === "pdf") {
      const lib = window.pdfjsLib;
      if (!lib) throw new Error("PDF library not loaded — please paste your CV text instead.");
      lib.GlobalWorkerOptions.workerSrc =
        "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js";
      const ab  = await f.arrayBuffer();
      const pdf = await lib.getDocument({ data: ab }).promise;
      let text = "";
      for (let i = 1; i <= pdf.numPages; i++) {
        const page    = await pdf.getPage(i);
        const content = await page.getTextContent();
        text += content.items.map((x) => x.str).join(" ") + "\n";
      }
      return text.trim();
    }

    if (ext === "docx") {
      if (!window.mammoth) throw new Error("DOCX library not loaded — please paste your CV text instead.");
      const ab     = await f.arrayBuffer();
      const result = await window.mammoth.extractRawText({ arrayBuffer: ab });
      return result.value.trim();
    }

    if (ext === "txt") return await f.text();

    throw new Error("Unsupported format. Please upload PDF, DOCX, or TXT — or paste your CV text.");
  };

  /* ── AI parse ─────────────────────────────────────────────── */
  const parseWithAI = (text) =>
    new Promise((resolve, reject) => {
      if (!window.groqStream) { reject(new Error("AI not available")); return; }

      const prompt = `Parse the following CV/resume and return a single JSON object.
Return ONLY valid JSON — no markdown, no code fences, no explanation.

JSON structure (fill all fields, use empty string or [] when unknown):
{
  "basics": { "name": "", "title": "", "email": "", "phone": "", "location": "", "website": "", "linkedin": "" },
  "summary": "",
  "experience": [{ "id": "e1", "company": "", "role": "", "location": "", "start": "Mon YYYY", "end": "Mon YYYY or Present", "bullets": [] }],
  "projects":   [{ "id": "p1", "name": "", "tech": "", "detail": "", "bullets": [] }],
  "education":  [{ "id": "ed1", "school": "", "degree": "", "location": "", "start": "YYYY", "end": "YYYY", "detail": "" }],
  "skills":     [{ "id": "s1", "group": "Category", "items": [] }],
  "certs":      []
}

Rules:
- IDs must be sequential: e1,e2… p1,p2… ed1,ed2… s1,s2…
- Use "Present" for current roles
- Group skills logically (Technical, Tools, Languages, Soft Skills…)
- Include all certifications and courses found

CV:
${text.slice(0, 14000)}`;

      window.groqStream({
        messages: [
          { role: "system", content: "You are a resume parser. Output only valid JSON, nothing else." },
          { role: "user",   content: prompt },
        ],
        maxTokens: 3500,
        onChunk:  () => {},
        onDone:   (full) => {
          try {
            let s = full.trim()
              .replace(/^```json\s*/i, "").replace(/^```\s*/i, "").replace(/\s*```$/i, "");
            resolve(JSON.parse(s));
          } catch (_) {
            const m = full.match(/\{[\s\S]*\}/);
            if (m) { try { resolve(JSON.parse(m[0])); return; } catch (_2) {} }
            reject(new Error("AI returned unexpected format. Please try again."));
          }
        },
        onError: (err) => reject(new Error(err)),
      });
    });

  /* ── Normalise imported data ──────────────────────────────── */
  const normalize = (d) => ({
    basics:     { name: "", title: "", email: "", phone: "", location: "", website: "", linkedin: "", ...(d.basics || {}) },
    summary:    d.summary || "",
    experience: (d.experience || []).map((e, i) => ({ id:"e"+(i+1), company:"", role:"", location:"", start:"", end:"", bullets:[], ...e })),
    projects:   (d.projects   || []).map((p, i) => ({ id:"p"+(i+1), name:"",    tech:"",  detail:"",   bullets:[], ...p })),
    education:  (d.education  || []).map((ed,i) => ({ id:"ed"+(i+1),school:"",  degree:"",location:"", start:"",  end:"", detail:"", ...ed })),
    skills:     (d.skills     || []).map((s, i) => ({ id:"s"+(i+1), group:"",   items:[], ...s })),
    certs:      (d.certs || []).map(c =>
      typeof c === "string" ? c :
      [c.name, c.issuer, c.date].filter(Boolean).join(" · ")
    ),
  });

  /* ── Extract flow ─────────────────────────────────────────── */
  const handleExtract = async () => {
    setError("");
    if (limitHit) { setError("You've reached the free limit. Upgrade to Pro for unlimited imports."); return; }

    try {
      setStage("parsing");
      let text = "";

      if (tab === "paste" || tab === "linkedin") {
        text = pasteText.trim();
        if (!text) { setStage("input"); setError(tab === "linkedin" ? "Please paste your LinkedIn profile text." : "Please paste your CV text."); return; }
        setStatus(tab === "linkedin" ? "Parsing LinkedIn profile…" : "Analysing your CV…");
      } else {
        if (!file) { setStage("input"); setError("Please select a file."); return; }
        setStatus("Reading " + file.name + "…");
        text = await extractFromFile(file);
        if (!text) throw new Error("Could not extract text — try pasting your CV instead.");
        setStatus("Extracting your info with AI…");
      }

      const raw  = await parseWithAI(text);
      setProgress(100);
      await new Promise(r => setTimeout(r, 320));
      setParsed(normalize(raw));
      setStage("review");
    } catch (e) {
      const msg = e.message || "";
      if (msg === "free_limit_reached") {
        setLimitHit(true);
        setError("You've used all 10 free AI imports. Upgrade to Pro for unlimited.");
      } else {
        setError(msg || "Something went wrong. Please try again.");
      }
      setStage("input");
    }
  };

  const handleDrop = (e) => {
    e.preventDefault(); setDragOver(false);
    const f = e.dataTransfer.files[0];
    if (f) { setFile(f); setTab("file"); }
  };

  /* ── Review summary card ──────────────────────────────────── */
  const ReviewCard = ({ data }) => {
    const b    = data.basics || {};
    const rows = [
      (data.experience || []).length  && `${data.experience.length} job${data.experience.length  > 1 ? "s" : ""}`,
      (data.projects   || []).length  && `${data.projects.length} project${data.projects.length  > 1 ? "s" : ""}`,
      (data.education  || []).length  && `${data.education.length} education entr${data.education.length > 1 ? "ies" : "y"}`,
      (data.skills || []).reduce((n,g) => n+(g.items||[]).length, 0) && `${(data.skills||[]).reduce((n,g)=>n+(g.items||[]).length,0)} skills`,
      (data.certs  || []).length      && `${data.certs.length} cert${data.certs.length > 1 ? "s" : ""}`,
    ].filter(Boolean);

    return (
      <div style={{ display:"flex", flexDirection:"column", gap:12 }}>
        <div style={{ display:"flex", alignItems:"center", gap:12, padding:"14px 16px", background:"var(--grad-soft)", borderRadius:"var(--r-sm)", border:"1px solid rgba(28,155,230,.15)" }}>
          <div style={{ width:44, height:44, borderRadius:"50%", background:"var(--grad)", display:"grid", placeItems:"center", color:"#fff", fontSize:16, fontWeight:700, flexShrink:0, letterSpacing:"-.01em" }}>
            {(b.name||"?").trim().split(/\s+/).map(w=>w[0]).slice(0,2).join("").toUpperCase()}
          </div>
          <div>
            <div style={{ fontWeight:700, fontSize:15, color:"var(--navy)" }}>{b.name || "Name not found"}</div>
            <div style={{ fontSize:13, color:"var(--slate-500)" }}>{b.title || b.email || "—"}</div>
          </div>
        </div>

        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:7 }}>
          {rows.map((r, i) => (
            <div key={i} style={{ display:"flex", alignItems:"center", gap:8, padding:"9px 12px", background:"#fff", borderRadius:"var(--r-sm)", border:"1px solid var(--slate-100)", fontSize:13.5, color:"var(--slate-700)", fontWeight:500 }}>
              <span style={{ color:"var(--brand-green)", fontWeight:700 }}>✓</span> {r}
            </div>
          ))}
        </div>

        {data.summary && (
          <div style={{ padding:"11px 13px", background:"var(--slate-50)", borderRadius:"var(--r-sm)", border:"1px solid var(--slate-100)", fontSize:13, color:"var(--slate-600)", lineHeight:1.55 }}>
            <span style={{ fontWeight:600, color:"var(--navy)" }}>Summary: </span>
            {data.summary.slice(0, 180)}{data.summary.length > 180 ? "…" : ""}
          </div>
        )}

        <p style={{ margin:0, fontSize:12, color:"var(--slate-400)", lineHeight:1.5 }}>
          This will replace your current resume. You can edit everything in the builder after importing.
        </p>
      </div>
    );
  };

  /* ── Render ───────────────────────────────────────────────── */
  return (
    <>
      <div onClick={onClose} style={{ position:"fixed", inset:0, background:"rgba(10,14,57,.5)", backdropFilter:"blur(4px)", zIndex:1000 }} />
      <div style={{
        position:"fixed", top:"50%", left:"50%", transform:"translate(-50%,-50%)",
        width:"min(520px, calc(100vw - 24px))", maxHeight:"88vh",
        background:"#fff", borderRadius:18, boxShadow:"0 28px 72px rgba(10,14,57,.24)",
        zIndex:1001, display:"flex", flexDirection:"column", overflow:"hidden",
      }}>

        {/* Header */}
        <div style={{ padding:"22px 24px 16px", borderBottom:"1px solid var(--slate-100)", display:"flex", alignItems:"center", gap:12 }}>
          <div style={{ width:38, height:38, borderRadius:11, background:"var(--grad)", display:"grid", placeItems:"center", color:"#fff", flexShrink:0 }}>
            <Icon name="import" size={18} />
          </div>
          <div style={{ flex:1 }}>
            <h2 style={{ margin:0, fontSize:17, fontWeight:700, color:"var(--navy)", letterSpacing:"-.02em" }}>Import existing CV</h2>
            <p style={{ margin:0, fontSize:12.5, color:"var(--slate-400)" }}>AI extracts your info and pre-fills the builder</p>
          </div>
          <button onClick={onClose} style={{ background:"none", border:"none", cursor:"pointer", color:"var(--slate-400)", padding:4, borderRadius:6, display:"flex" }}>
            <Icon name="x" size={20} />
          </button>
        </div>

        {/* Body */}
        <div style={{ flex:1, overflowY:"auto", padding:"20px 24px" }}>

          {/* Loading */}
          {stage === "parsing" && (
            <div style={{ display:"flex", flexDirection:"column", alignItems:"center", gap:20, padding:"32px 0 28px" }}>
              {/* Icon */}
              <div style={{ width:56, height:56, borderRadius:"50%", background:"var(--grad-soft)", display:"grid", placeItems:"center", flexShrink:0 }}>
                <span className="spin" style={{ width:28, height:28, borderWidth:3, borderColor:"rgba(28,155,230,.18)", borderTopColor:"var(--brand-blue)", borderRadius:"50%", display:"block" }} />
              </div>

              {/* Text */}
              <div style={{ textAlign:"center" }}>
                <div style={{ fontWeight:600, fontSize:15, color:"var(--navy)", marginBottom:4 }}>
                  {progress < 30 ? "Reading your CV…" : progress < 70 ? "Extracting information…" : progress < 99 ? "Finalising details…" : "Done!"}
                </div>
                <div style={{ fontSize:13, color:"var(--slate-400)" }}>AI is analysing your resume…</div>
              </div>

              {/* Progress bar */}
              <div style={{ width:"100%", display:"flex", flexDirection:"column", gap:7 }}>
                <div style={{ height:8, background:"var(--slate-100)", borderRadius:99, overflow:"hidden" }}>
                  <div style={{
                    height:"100%",
                    width: Math.round(progress) + "%",
                    background:"linear-gradient(90deg, #1C9BE6, #2de39a)",
                    borderRadius:99,
                    transition:"width .22s ease",
                  }} />
                </div>
                <div style={{ textAlign:"right", fontSize:12.5, fontWeight:600, color:"var(--brand-blue)" }}>
                  {Math.round(progress)}%
                </div>
              </div>
            </div>
          )}

          {/* Review */}
          {stage === "review" && parsed && <ReviewCard data={parsed} />}

          {/* Input */}
          {stage === "input" && (
            <>
              {/* Tab toggle */}
              <div style={{ display:"flex", gap:4, background:"var(--slate-50)", borderRadius:10, padding:4, marginBottom:18 }}>
                {[["paste","📋","Paste CV"],["file","📁","Upload file"],["linkedin","in","LinkedIn"]].map(([t,icon,label]) => (
                  <button key={t} onClick={() => setTab(t)} style={{
                    flex:1, padding:"8px 6px", borderRadius:7, border:"none", cursor:"pointer",
                    background: tab===t ? "#fff" : "transparent",
                    boxShadow: tab===t ? "0 1px 4px rgba(0,0,0,.09)" : "none",
                    fontWeight: tab===t ? 600 : 500, fontSize:13,
                    color: t==="linkedin" && tab===t ? "#0A66C2" : tab===t ? "var(--navy)" : "var(--slate-500)",
                    fontFamily:"inherit", transition:"all .12s",
                    display:"flex", alignItems:"center", justifyContent:"center", gap:5,
                  }}>
                    {t === "linkedin"
                      ? <span style={{ fontWeight:900, fontSize:13, background:"#0A66C2", color:"#fff", borderRadius:4, padding:"1px 5px", letterSpacing:"-.01em" }}>in</span>
                      : icon}
                    {label}
                  </button>
                ))}
              </div>

              {/* Paste mode */}
              {tab === "paste" && (
                <textarea
                  autoFocus
                  style={{
                    width:"100%", minHeight:210, padding:"12px 14px", boxSizing:"border-box",
                    border:"1.5px solid var(--slate-200)", borderRadius:"var(--r-sm)",
                    fontFamily:"inherit", fontSize:13.5, color:"var(--navy)", lineHeight:1.6,
                    resize:"vertical", outline:"none", background:"#fff",
                  }}
                  placeholder={"Paste your CV or resume here — any text format works.\n\nJohn Smith · Software Engineer · john@email.com\n\nExperience\nSenior Engineer at Acme Corp · Jan 2021 – Present\n  • Led migration to microservices, reducing deploy time 60%\n  • …\n\nEducation\nBS Computer Science, MIT · 2016–2020\n\nSkills: Python, Go, React, AWS, Docker"}
                  value={pasteText}
                  onChange={e => setPaste(e.target.value)}
                />
              )}

              {/* LinkedIn mode */}
              {tab === "linkedin" && (
                <div>
                  <div style={{ display:"flex", alignItems:"center", gap:10, padding:"12px 14px", background:"rgba(10,102,194,.06)", border:"1px solid rgba(10,102,194,.18)", borderRadius:10, marginBottom:14 }}>
                    <span style={{ fontWeight:900, fontSize:15, background:"#0A66C2", color:"#fff", borderRadius:5, padding:"2px 7px", flexShrink:0 }}>in</span>
                    <div style={{ fontSize:12.5, color:"var(--slate-600)", lineHeight:1.5 }}>
                      Open your <strong>LinkedIn profile</strong> → click <strong>More → Save to PDF</strong> or select all text (Ctrl+A) and paste below.
                    </div>
                  </div>
                  <textarea
                    autoFocus
                    style={{
                      width:"100%", minHeight:200, padding:"12px 14px", boxSizing:"border-box",
                      border:"1.5px solid rgba(10,102,194,.3)", borderRadius:"var(--r-sm)",
                      fontFamily:"inherit", fontSize:13.5, color:"var(--navy)", lineHeight:1.6,
                      resize:"vertical", outline:"none", background:"#fff",
                    }}
                    placeholder={"Paste your LinkedIn profile text here...\n\nJohn Smith\nSenior Software Engineer at Google\nSan Francisco Bay Area · 500+ connections\n\nAbout\nI build scalable distributed systems...\n\nExperience\nSenior Software Engineer\nGoogle · Full-time\nJan 2021 – Present · 3 yrs\n..."}
                    value={pasteText}
                    onChange={e => setPaste(e.target.value)}
                  />
                </div>
              )}

              {/* File upload mode */}
              {tab === "file" && (
                <div
                  onDragOver={e => { e.preventDefault(); setDragOver(true); }}
                  onDragLeave={() => setDragOver(false)}
                  onDrop={handleDrop}
                  onClick={() => fileRef.current && fileRef.current.click()}
                  style={{
                    border:"2px dashed " + (dragOver ? "var(--brand-blue)" : "var(--slate-200)"),
                    borderRadius:"var(--r-sm)", padding:"40px 24px", textAlign:"center",
                    cursor:"pointer", background: dragOver ? "var(--grad-soft)" : "var(--slate-50)",
                    transition:"all .15s", minHeight:170,
                    display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", gap:8,
                  }}
                >
                  <input ref={fileRef} type="file" accept=".pdf,.docx,.txt" style={{ display:"none" }}
                    onChange={e => e.target.files[0] && setFile(e.target.files[0])} />
                  {file ? (
                    <>
                      <div style={{ fontSize:36 }}>{file.name.toLowerCase().endsWith(".pdf") ? "📄" : "📝"}</div>
                      <div style={{ fontWeight:600, color:"var(--navy)" }}>{file.name}</div>
                      <div style={{ fontSize:12.5, color:"var(--slate-400)" }}>{(file.size/1024).toFixed(0)} KB · click to change</div>
                    </>
                  ) : (
                    <>
                      <Icon name="upload" size={28} style={{ color:"var(--slate-300)" }} />
                      <div style={{ fontWeight:600, color:"var(--navy)" }}>Drop your file here</div>
                      <div style={{ fontSize:13, color:"var(--slate-400)" }}>or click to browse</div>
                      <div style={{ fontSize:12, color:"var(--slate-300)", marginTop:4 }}>PDF · DOCX · TXT</div>
                    </>
                  )}
                </div>
              )}

              {/* Error */}
              {error && (
                <div style={{ marginTop:12, padding:"10px 13px", background:"rgba(224,83,61,.07)", border:"1px solid rgba(224,83,61,.18)", borderRadius:"var(--r-sm)", fontSize:13, color:"var(--bad)", lineHeight:1.5 }}>
                  {error}
                </div>
              )}

              {/* Destructive action warning */}
              {!limitHit && !error && (
                <div style={{ marginTop:12, padding:"9px 13px", background:"rgba(224,160,19,.07)", border:"1px solid rgba(224,160,19,.25)", borderRadius:"var(--r-sm)", fontSize:12.5, color:"var(--slate-600)", lineHeight:1.5 }}>
                  ⚠️ Importing will <b>replace your current resume</b>. Export a backup first if needed.
                </div>
              )}

              {/* Limit hit notice */}
              {limitHit && !error && (
                <div style={{ marginTop:12, padding:"11px 14px", background:"var(--grad-soft)", border:"1px solid rgba(28,155,230,.2)", borderRadius:"var(--r-sm)", fontSize:12.5, color:"var(--slate-600)", lineHeight:1.55 }}>
                  You've used all 10 free AI imports. <b>Upgrade to Pro</b> for unlimited imports.
                </div>
              )}

              {/* Remaining uses */}
              {!limitHit && !window.IS_PRO && remaining !== null && remaining <= 5 && (
                <div style={{ marginTop:8, fontSize:12, color:"var(--slate-400)", textAlign:"right" }}>
                  {remaining} free import{remaining !== 1 ? "s" : ""} remaining
                </div>
              )}
            </>
          )}
        </div>

        {/* Footer */}
        <div style={{ padding:"14px 24px 18px", borderTop:"1px solid var(--slate-100)", display:"flex", alignItems:"center", gap:10 }}>
          {stage === "review" ? (
            <>
              <button onClick={() => setStage("input")} className="btn btn-ghost btn-sm">← Back</button>
              <div style={{ flex:1 }} />
              <button onClick={onClose} className="btn btn-ghost btn-sm">Cancel</button>
              <button onClick={() => onApply(parsed)} className="btn btn-grad" style={{ paddingLeft:22, paddingRight:22 }}>
                Apply to resume →
              </button>
            </>
          ) : stage === "input" && (
            <>
              <div style={{ flex:1 }} />
              <button onClick={onClose} className="btn btn-ghost btn-sm">Cancel</button>
              <button
                onClick={handleExtract}
                disabled={limitHit || ((tab==="paste"||tab==="linkedin") ? !pasteText.trim() : !file)}
                className="btn btn-grad"
                style={{ paddingLeft:22, paddingRight:22, opacity: (limitHit || ((tab==="paste"||tab==="linkedin") ? !pasteText.trim() : !file)) ? 0.45 : 1 }}
              >
                <Icon name="sparkle" size={14} /> Extract info
              </button>
            </>
          )}
        </div>
      </div>
    </>
  );
}

window.ImportCVModal = ImportCVModal;
