/* achievement.jsx — Achievement quantifier: flags vague bullets, suggests metrics */

function AchievementDrawer({ data, patch, onClose }) {
  const { useState: S, useEffect: E } = React;
  const [stage,    setStage]    = S("idle");
  const [flags,    setFlags]    = S([]);
  const [errMsg,   setErrMsg]   = S("");
  const [applied,  setApplied]  = S({});
  const [limitHit, setLimitHit] = S(false);

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

  const analyze = async () => {
    if (!window.groqStream) { setErrMsg("AI not available."); setStage("error"); return; }
    setStage("loading"); setFlags([]); setErrMsg(""); setApplied({});

    // Collect all bullets with location keys
    const bullets = [];
    (data.experience || []).forEach((x, xi) =>
      (x.bullets || []).forEach((b, bi) => {
        if (b.trim()) bullets.push({ key: `exp_${xi}_${bi}`, text: b, section: x.role + " @ " + x.company });
      })
    );
    (data.projects || []).forEach((x, xi) =>
      (x.bullets || []).forEach((b, bi) => {
        if (b.trim()) bullets.push({ key: `proj_${xi}_${bi}`, text: b, section: "Project: " + x.name });
      })
    );

    if (!bullets.length) { setErrMsg("No bullets found. Add experience bullets first."); setStage("error"); return; }

    let raw = "";
    await window.groqStream({
      messages: [
        { role: "system", content: window.GROQ_SYSTEM || "" },
        { role: "user", content: `Analyze these resume bullets. Flag vague ones that lack measurable impact. For each vague bullet, suggest a stronger quantified version.

Return ONLY a JSON array. Each item:
{
  "key": "exp_0_0",
  "vague": true,
  "reason": "One phrase explaining what's missing (e.g., 'No metric for scale or impact')",
  "suggestion": "Rewritten bullet with placeholder metric, e.g. 'Led migration of X services, reducing deploy time by Y%'"
}

Only include bullets where vague=true. Skip already-quantified bullets entirely.

Bullets:
${JSON.stringify(bullets.map(b => ({ key: b.key, text: b.text })))}` },
      ],
      maxTokens: 2000,
      onChunk: (_, full) => { raw = full; },
      onDone: () => {
        try {
          let s = raw.trim().replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/i,"");
          const arr = JSON.parse(s.match(/\[[\s\S]*\]/)?.[0] || s);
          // Merge with original bullet text + section label
          const merged = arr.map(f => {
            const orig = bullets.find(b => b.key === f.key);
            return { ...f, original: orig?.text || "", section: orig?.section || "" };
          });
          setFlags(merged);
          setStage("done");
        } catch(_) {
          setErrMsg("Could not parse AI response. Try again.");
          setStage("error");
        }
      },
      onError: e => { if (e === "free_limit_reached") { setLimitHit(true); } else { setErrMsg(typeof e==="string"?e:"AI error."); } setStage("error"); },
    });
  };

  const applyFix = (flag) => {
    const parts = flag.key.split("_");
    const type = parts[0], xi = +parts[1], bi = +parts[2];
    patch(d => {
      const nd = { ...d };
      if (type === "exp") {
        const exp = d.experience.map((x, i) => {
          if (i !== xi) return x;
          const bullets = [...x.bullets];
          bullets[bi] = flag.suggestion;
          return { ...x, bullets };
        });
        return { ...nd, experience: exp };
      } else {
        const projs = d.projects.map((x, i) => {
          if (i !== xi) return x;
          const bullets = [...x.bullets];
          bullets[bi] = flag.suggestion;
          return { ...x, bullets };
        });
        return { ...nd, projects: projs };
      }
    });
    setApplied(a => ({ ...a, [flag.key]: true }));
  };

  return (
    <>
      <div className="drawer-back" onClick={onClose} />
      <div className="drawer" style={{ width: 480 }}>
        <div className="drawer-h" style={{ display:"flex", alignItems:"center" }}>
          <div>
            <h3 style={{ margin:0, fontSize:16, fontWeight:700, color:"var(--navy)" }}>Achievement Quantifier</h3>
            <p style={{ margin:"3px 0 0", fontSize:12.5, color:"var(--slate-500)" }}>Flags vague bullets — AI suggests metrics</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 28px" }}>

          {stage === "idle" && (
            <div style={{ textAlign:"center", padding:"32px 16px 16px" }}>
              <div style={{ width:52, height:52, borderRadius:"50%", background:"linear-gradient(135deg,#f59e0b,#ef4444)", display:"grid", placeItems:"center", margin:"0 auto 16px" }}>
                <Icon name="sparkle" size={22} style={{ color:"#fff" }} />
              </div>
              <h4 style={{ margin:"0 0 8px", color:"var(--navy)", fontSize:15 }}>Find weak bullets</h4>
              <p style={{ margin:"0 0 24px", fontSize:13.5, color:"var(--slate-500)", lineHeight:1.55 }}>
                Scans every bullet in experience and projects. Flags vague phrases like "responsible for" or "helped with" and rewrites them with measurable impact.
              </p>
              <button className="btn btn-grad" style={{ width:"100%", justifyContent:"center" }} onClick={analyze}>
                <Icon name="writeai" size={15} /> Scan My Bullets
              </button>
            </div>
          )}

          {stage === "loading" && (
            <div style={{ textAlign:"center", padding:"52px 0" }}>
              <span className="spin" style={{ width:32, height:32, borderWidth:3, borderColor:"rgba(245,158,11,.2)", borderTopColor:"#f59e0b", display:"inline-block" }} />
              <p style={{ marginTop:16, color:"var(--slate-500)", fontSize:13 }}>Analyzing your bullets…</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={analyze}>Try again</button>
            </div>
          ))}

          {stage === "done" && (
            <>
              {flags.length === 0 ? (
                <div style={{ textAlign:"center", padding:"40px 20px" }}>
                  <div style={{ fontSize:40, marginBottom:12 }}>🎉</div>
                  <h4 style={{ margin:"0 0 8px", color:"var(--navy)" }}>All bullets look strong!</h4>
                  <p style={{ margin:"0 0 20px", fontSize:13.5, color:"var(--slate-500)" }}>No vague bullets found. Your resume already reads with impact.</p>
                  <button className="btn btn-ghost btn-sm" onClick={analyze}>↺ Re-scan</button>
                </div>
              ) : (
                <>
                  <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:14 }}>
                    <div style={{ fontSize:13, fontWeight:650, color:"#f59e0b" }}>
                      {flags.filter(f => !applied[f.key]).length} vague bullet{flags.filter(f=>!applied[f.key]).length!==1?"s":""} found
                    </div>
                    <button className="btn btn-ghost btn-sm" onClick={analyze}>↺ Re-scan</button>
                  </div>

                  <div style={{ display:"flex", flexDirection:"column", gap:12 }}>
                    {flags.map(flag => {
                      const done = applied[flag.key];
                      return (
                        <div key={flag.key} style={{ border:"1.5px solid", borderColor: done ? "rgba(22,163,107,.3)" : "rgba(245,158,11,.3)", borderRadius:12, overflow:"hidden", opacity: done ? 0.7 : 1, transition:"opacity .2s" }}>
                          {/* Header */}
                          <div style={{ padding:"10px 13px 8px", background: done ? "rgba(22,163,107,.05)" : "rgba(245,158,11,.05)", borderBottom:"1px solid", borderBottomColor: done ? "rgba(22,163,107,.12)" : "rgba(245,158,11,.12)" }}>
                            <div style={{ fontSize:11, fontWeight:700, color: done ? "var(--good)" : "#f59e0b", textTransform:"uppercase", letterSpacing:".05em" }}>
                              {done ? "✓ Applied" : "⚠ Vague"} · {flag.section}
                            </div>
                          </div>
                          <div style={{ padding:"12px 13px", display:"flex", flexDirection:"column", gap:8 }}>
                            {/* Original */}
                            <div>
                              <div style={{ fontSize:10.5, fontWeight:700, color:"var(--slate-400)", textTransform:"uppercase", letterSpacing:".05em", marginBottom:4 }}>Original</div>
                              <div style={{ fontSize:13, color:"var(--slate-600)", lineHeight:1.45 }}>• {flag.original}</div>
                            </div>
                            {/* Reason */}
                            <div style={{ fontSize:12, color:"#b45309", background:"rgba(245,158,11,.07)", padding:"5px 9px", borderRadius:6 }}>
                              {flag.reason}
                            </div>
                            {/* Suggestion */}
                            <div>
                              <div style={{ fontSize:10.5, fontWeight:700, color:"var(--good)", textTransform:"uppercase", letterSpacing:".05em", marginBottom:4 }}>Suggested</div>
                              <div style={{ fontSize:13, color:"var(--navy)", lineHeight:1.45, fontWeight:500 }}>• {flag.suggestion}</div>
                            </div>
                            {!done && (
                              <button className="btn btn-grad btn-sm" style={{ alignSelf:"flex-end" }} onClick={() => applyFix(flag)}>
                                Apply fix →
                              </button>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </>
              )}
            </>
          )}
        </div>
      </div>
    </>
  );
}
