/* tailor.jsx — "Tailor to job" Pro panel */

function TailorDrawer({ data, patch, coverLetter, setCoverLetter, showToast, onGotoCoverLetter, onClose }) {
  const { useState: S, useRef: R } = React;

  const isPro    = !!window.IS_PRO;

  const [jd,        setJd]       = S("");
  const [phase,     setPhase]    = S("input");   // "input" | "loading" | "review"
  const [status,    setStatus]   = S("");
  const [result,    setResult]   = S(null);
  const [applied,   setApplied]  = S(false);
  const [limitHit,  setLimitHit] = S(false);
  const [remaining, setRemaining] = S(() => {
    var v = window.getAIUsesRemaining ? window.getAIUsesRemaining() : null;
    return v;
  });
  const abortRef = R(false);

  const canRun = !limitHit;

  const reset = () => { setPhase("input"); setResult(null); setApplied(false); setStatus(""); abortRef.current = false; };

  /* ── helpers ──────────────────────────────────────────────── */
  function groqOnce(messages, maxTokens, onDone, onError) {
    let buf = "";
    window.groqStream({
      messages,
      maxTokens,
      model: "llama-3.3-70b-versatile",
      onChunk: (_, full) => { buf = full; },
      onDone:  (full)    => onDone(full || buf),
      onError: (err)     => onError(err),
    });
  }

  /* ── run tailoring ─────────────────────────────────────────── */
  const run = () => {
    const jdTrim = jd.trim();
    if (!jdTrim || !canRun) return;
    if (!window.groqStream) { showToast && showToast("AI not available"); return; }

    abortRef.current = false;
    setPhase("loading");
    setStatus("Reading your résumé…");
    setResult(null);
    setApplied(false);

    const ctx = window.buildResumeCtx ? window.buildResumeCtx(data) : "";

    const cvPrompt = [
      { role: "system", content: window.GROQ_SYSTEM || "" },
      { role: "user",   content:
        "Tailor this résumé for the job description below.\n\n" +
        "RÉSUMÉ:\n" + ctx + "\n\n" +
        "JOB DESCRIPTION:\n" + jdTrim + "\n\n" +
        "Return ONLY a JSON object — no markdown fences, no explanation — with this exact shape:\n" +
        '{"summary":"<rewritten 2–4 sentence summary targeting this JD, strong verbs, mirrors JD language>","bulletEdits":[{"role":"<role>","company":"<company>","bulletIndex":<0-based int>,"newBullet":"<improved bullet>"}],"newSkills":["<skill1>","<skill2>"]}\n\n' +
        "Rules:\n" +
        "• summary: rewrite to directly target this role. Mirror key terms.\n" +
        "• bulletEdits: max 4 edits total, only the bullets that most need improvement for this JD.\n" +
        "• newSkills: up to 6 keywords/tools from the JD not already in the résumé. Empty array [] if none.\n" +
        "Return pure JSON only."
      },
    ];

    const clPrompt = [
      { role: "system", content: window.GROQ_SYSTEM || "" },
      { role: "user",   content:
        "Write a targeted cover letter body for the job below using my résumé.\n\n" +
        "RÉSUMÉ:\n" + ctx + "\n\n" +
        "JOB DESCRIPTION:\n" + jdTrim + "\n\n" +
        "3 paragraphs separated by a blank line. Under 350 words. Professional but warm.\n" +
        "Paragraph 1: why this specific role + company excites me + who I am.\n" +
        "Paragraph 2: 2 concrete achievements from my background that map to the role's needs.\n" +
        "Paragraph 3: brief closing with call to action.\n" +
        "Return ONLY the letter body — no date, salutation, or sign-off."
      },
    ];

    let cvDone = false, clDone = false;
    let cvResult = null, clResult = null;
    let errored = false;

    function tryFinish() {
      if (abortRef.current || errored) return;
      if (!cvDone || !clDone) return;

      let parsed = null;
      try {
        const raw = cvResult.trim().replace(/^```(?:json)?|```$/gm, "").trim();
        parsed = JSON.parse(raw);
      } catch(e) {
        try {
          const m = cvResult.match(/\{[\s\S]*\}/);
          if (m) parsed = JSON.parse(m[0]);
        } catch(e2) {}
      }

      if (!parsed) {
        errored = true;
        setStatus("Couldn't parse AI response. Try again.");
        setPhase("input");
        return;
      }

      setResult({ summary: parsed.summary || "", bulletEdits: parsed.bulletEdits || [], newSkills: parsed.newSkills || [], coverLetter: clResult || "" });
      setPhase("review");
    }

    setStatus("Tailoring your CV…");
    const handleErr = (err) => {
      if (abortRef.current) return;
      errored = true;
      if (err === "free_limit_reached") {
        setLimitHit(true);
        reset();
      } else {
        setStatus("Error: " + err);
        setPhase("input");
      }
    };

    groqOnce(cvPrompt, 900, (full) => {
      if (abortRef.current) return;
      cvResult = full;
      cvDone   = true;
      setStatus("Writing cover letter…");
      const r = window.getAIUsesRemaining ? window.getAIUsesRemaining() : null;
      setRemaining(r);
      tryFinish();
    }, handleErr);

    groqOnce(clPrompt, 700, (full) => {
      if (abortRef.current) return;
      clResult = full;
      clDone   = true;
      tryFinish();
    }, handleErr);
  };

  /* ── apply all to resume ───────────────────────────────────── */
  const applyAll = () => {
    if (!result || applied) return;

    patch(d => {
      let next = { ...d };

      if (result.summary) next = { ...next, summary: result.summary };

      if (result.bulletEdits && result.bulletEdits.length) {
        next = {
          ...next,
          experience: (next.experience || []).map(x => {
            const edits = result.bulletEdits.filter(e => e.role === x.role && e.company === x.company);
            if (!edits.length) return x;
            const bullets = [...(x.bullets || [])];
            edits.forEach(e => { if (bullets[e.bulletIndex] !== undefined) bullets[e.bulletIndex] = e.newBullet; });
            return { ...x, bullets };
          }),
        };
      }

      if (result.newSkills && result.newSkills.length) {
        const groups = next.skills ? [...next.skills] : [];
        if (groups.length) {
          const existing = groups.flatMap(g => g.items || []).map(s => s.toLowerCase());
          const toAdd = result.newSkills.filter(s => !existing.includes(s.toLowerCase()));
          if (toAdd.length) {
            groups[0] = { ...groups[0], items: [...(groups[0].items || []), ...toAdd] };
          }
          next = { ...next, skills: groups };
        }
      }

      return next;
    });

    if (result.coverLetter) {
      setCoverLetter(cl => ({ ...cl, body: result.coverLetter }));
      if (showToast) showToast("Applied! Cover letter saved — opening tab…");
      if (onGotoCoverLetter) setTimeout(onGotoCoverLetter, 900);
    } else {
      if (showToast) showToast("Changes applied to your résumé.");
    }

    setApplied(true);
  };

  /* ── render ────────────────────────────────────────────────── */
  return (
    <>
      <div className="drawer-back" onClick={onClose} />
      <div className="drawer">

        {/* Header */}
        <div className="drawer-h" style={{ display: "flex", alignItems: "center" }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: "var(--navy)", display: "flex", alignItems: "center", gap: 8 }}>
              Tailor to job
              <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".05em", textTransform: "uppercase", color: "#534AB7", background: "#EEEDFE", border: "1px solid #AFA9EC", borderRadius: 99, padding: "2px 8px" }}>Pro</span>
            </h3>
            <p style={{ margin: "3px 0 0", fontSize: 12.5, color: "var(--slate-500)" }}>Paste a job description — AI rewrites your CV and drafts a cover letter.</p>
          </div>
          <div style={{ flex: 1 }} />
          <button className="x" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        {/* Usage bar — free users only */}
        {!isPro && remaining !== null && remaining !== Infinity && (
          <div style={{ padding: "8px 16px", borderBottom: "1px solid var(--slate-100)", display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ flex: 1, height: 4, borderRadius: 99, background: "var(--slate-100)", overflow: "hidden" }}>
              <div style={{ height: "100%", width: (Math.max(0, 10 - remaining) / 10 * 100) + "%", background: remaining <= 2 ? "var(--danger, #e53e3e)" : "var(--brand-blue)", borderRadius: 99, transition: "width .3s" }} />
            </div>
            <span style={{ fontSize: 11.5, color: "var(--slate-500)", whiteSpace: "nowrap" }}>
              {remaining} / 10 free {remaining === 1 ? "use" : "uses"} left
            </span>
          </div>
        )}

        <div className="drawer-body scroll" style={{ display: "flex", flexDirection: "column", gap: 16 }}>

          {/* Limit hit banner */}
          {limitHit && (
            <div style={{ background: "#EEEDFE", border: "1px solid #AFA9EC", borderRadius: 10, padding: "14px 16px", display: "flex", flexDirection: "column", gap: 8 }}>
              <div style={{ fontWeight: 700, fontSize: 13.5, color: "#3C3489" }}>You've used all 10 free AI requests</div>
              <div style={{ fontSize: 13, color: "#534AB7", lineHeight: 1.5 }}>Upgrade to Pro for unlimited AI tailoring, cover letters, and priority support.</div>
              <a href={(window.__LANDING_URL__ || "https://resumeai.bdrecruit.net").replace(/\/$/, "") + "/pricing"} target="_blank" rel="noreferrer"
                className="btn btn-grad btn-sm" style={{ marginTop: 4, display: "inline-flex", width: "fit-content", alignItems: "center", gap: 6, textDecoration: "none" }}>
                Upgrade to Pro →
              </a>
            </div>
          )}

          {/* ── INPUT PHASE ── */}
          {phase === "input" && (
            <>
              <div className="field" style={{ margin: 0 }}>
                <label style={{ fontSize: 12.5, fontWeight: 600, color: "var(--slate-600)", marginBottom: 6, display: "block" }}>
                  Job description
                </label>
                <textarea
                  className="ta"
                  value={jd}
                  onChange={e => setJd(e.target.value)}
                  placeholder={"Paste the full job description here…\n\nIncludes: role title, responsibilities, requirements, and any keywords or tools mentioned."}
                  style={{ minHeight: 220, fontSize: 13, lineHeight: 1.6 }}
                  disabled={limitHit}
                />
              </div>

              {status && (
                <div style={{ fontSize: 12.5, color: "var(--danger, #e53e3e)", padding: "8px 12px", background: "rgba(229,62,62,.07)", borderRadius: 8 }}>{status}</div>
              )}

              <button
                className="btn btn-grad"
                disabled={!jd.trim() || limitHit}
                onClick={run}
                style={{ width: "100%", justifyContent: "center", gap: 8 }}
              >
                <Icon name="writeai" size={16} /> Tailor my CV + cover letter
              </button>

              <div className="tip" style={{ margin: 0 }}>
                <div className="t"><Icon name="sparkle" size={14} style={{ color: "var(--brand-blue)" }} /> What this does</div>
                <p>
                  • Rewrites your summary to mirror the JD's language<br />
                  • Improves up to 4 experience bullets most relevant to the role<br />
                  • Adds missing keywords to your Skills section<br />
                  • Generates a targeted 3-paragraph cover letter
                </p>
              </div>
            </>
          )}

          {/* ── LOADING PHASE ── */}
          {phase === "loading" && (
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 18, padding: "48px 24px", textAlign: "center" }}>
              <span className="spin" style={{ width: 36, height: 36, borderWidth: 3, borderColor: "rgba(83,74,183,.18)", borderTopColor: "#534AB7" }} />
              <div style={{ fontSize: 14, fontWeight: 600, color: "var(--navy)" }}>{status || "Working…"}</div>
              <div style={{ fontSize: 12.5, color: "var(--slate-400)", lineHeight: 1.55 }}>
                Reading your résumé and the JD.<br />This takes 10–20 seconds.
              </div>
              <button className="btn btn-ghost btn-sm" onClick={() => { abortRef.current = true; reset(); }}>Cancel</button>
            </div>
          )}

          {/* ── REVIEW PHASE ── */}
          {phase === "review" && result && (
            <>
              <div style={{ background: "rgba(52,199,127,.07)", border: "1px solid rgba(52,199,127,.25)", borderRadius: 10, padding: "12px 14px", fontSize: 13, color: "var(--navy)", fontWeight: 600 }}>
                ✅ Ready to apply — review the changes below
              </div>

              {/* Summary */}
              {result.summary && (
                <div style={{ borderRadius: 10, border: "1px solid var(--slate-100)", overflow: "hidden" }}>
                  <div style={{ padding: "10px 14px", background: "var(--slate-50, #f8f9fc)", borderBottom: "1px solid var(--slate-100)", fontSize: 12, fontWeight: 700, color: "var(--slate-600)", display: "flex", alignItems: "center", gap: 6 }}>
                    <Icon name="text" size={13} /> New summary
                    <span style={{ marginLeft: "auto", fontSize: 11, color: "#0F6E56", background: "#E1F5EE", borderRadius: 99, padding: "2px 7px", fontWeight: 600 }}>rewritten</span>
                  </div>
                  <div style={{ padding: "12px 14px", fontSize: 13, color: "var(--slate-700)", lineHeight: 1.6 }}>{result.summary}</div>
                </div>
              )}

              {/* Bullet edits */}
              {result.bulletEdits && result.bulletEdits.length > 0 && (
                <div style={{ borderRadius: 10, border: "1px solid var(--slate-100)", overflow: "hidden" }}>
                  <div style={{ padding: "10px 14px", background: "var(--slate-50, #f8f9fc)", borderBottom: "1px solid var(--slate-100)", fontSize: 12, fontWeight: 700, color: "var(--slate-600)", display: "flex", alignItems: "center", gap: 6 }}>
                    <Icon name="bolt" size={13} /> {result.bulletEdits.length} bullet{result.bulletEdits.length > 1 ? "s" : ""} improved
                    <span style={{ marginLeft: "auto", fontSize: 11, color: "#854F0B", background: "#FAEEDA", borderRadius: 99, padding: "2px 7px", fontWeight: 600 }}>boosted</span>
                  </div>
                  <div style={{ padding: "10px 14px", display: "flex", flexDirection: "column", gap: 10 }}>
                    {result.bulletEdits.map((e, i) => (
                      <div key={i}>
                        <div style={{ fontSize: 11, fontWeight: 600, color: "var(--slate-500)", marginBottom: 3 }}>{e.role} @ {e.company}</div>
                        <div style={{ fontSize: 12.5, color: "var(--slate-700)", lineHeight: 1.5 }}>• {e.newBullet}</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* New skills */}
              {result.newSkills && result.newSkills.length > 0 && (
                <div style={{ borderRadius: 10, border: "1px solid var(--slate-100)", overflow: "hidden" }}>
                  <div style={{ padding: "10px 14px", background: "var(--slate-50, #f8f9fc)", borderBottom: "1px solid var(--slate-100)", fontSize: 12, fontWeight: 700, color: "var(--slate-600)", display: "flex", alignItems: "center", gap: 6 }}>
                    <Icon name="sparkle" size={13} /> {result.newSkills.length} new keyword{result.newSkills.length > 1 ? "s" : ""} matched
                    <span style={{ marginLeft: "auto", fontSize: 11, color: "#0F6E56", background: "#E1F5EE", borderRadius: 99, padding: "2px 7px", fontWeight: 600 }}>added</span>
                  </div>
                  <div style={{ padding: "10px 14px", display: "flex", flexWrap: "wrap", gap: 6 }}>
                    {result.newSkills.map((s, i) => (
                      <span key={i} style={{ fontSize: 12, padding: "3px 10px", borderRadius: 99, background: "#E1F5EE", color: "#085041", border: "1px solid #9FE1CB", fontWeight: 500 }}>{s}</span>
                    ))}
                  </div>
                </div>
              )}

              {/* Cover letter preview */}
              {result.coverLetter && (
                <div style={{ borderRadius: 10, border: "1px solid var(--slate-100)", overflow: "hidden" }}>
                  <div style={{ padding: "10px 14px", background: "var(--slate-50, #f8f9fc)", borderBottom: "1px solid var(--slate-100)", fontSize: 12, fontWeight: 700, color: "var(--slate-600)", display: "flex", alignItems: "center", gap: 6 }}>
                    <Icon name="letter" size={13} /> Cover letter draft
                    <span style={{ marginLeft: "auto", fontSize: 11, color: "#0F6E56", background: "#E1F5EE", borderRadius: 99, padding: "2px 7px", fontWeight: 600 }}>new</span>
                  </div>
                  <div style={{ padding: "12px 14px", fontSize: 12.5, color: "var(--slate-600)", lineHeight: 1.65, whiteSpace: "pre-wrap", maxHeight: 180, overflow: "auto" }}>{result.coverLetter}</div>
                </div>
              )}

              <div style={{ display: "flex", gap: 8, paddingTop: 4 }}>
                {!applied ? (
                  <>
                    <button className="btn btn-grad" style={{ flex: 1, justifyContent: "center" }} onClick={applyAll}>
                      <Icon name="check" size={15} /> Apply to my CV
                    </button>
                    <button className="btn btn-ghost btn-sm" onClick={reset}>Discard</button>
                  </>
                ) : (
                  <>
                    <div style={{ flex: 1, fontSize: 13, color: "var(--brand-green)", fontWeight: 600, display: "flex", alignItems: "center", gap: 6 }}>
                      <Icon name="check" size={15} /> Applied!
                    </div>
                    <button className="btn btn-ghost btn-sm" onClick={reset}>Tailor again</button>
                    <button className="x" onClick={onClose}><Icon name="x" size={18} /></button>
                  </>
                )}
              </div>
            </>
          )}

        </div>
      </div>
    </>
  );
}

window.TailorDrawer = TailorDrawer;
