/* interview-prep.jsx — AI-generated interview questions from resume */

function InterviewPrepDrawer({ data, onClose }) {
  const { useState: S, useEffect: E } = React;
  const [stage,    setStage]    = S("idle"); // idle | loading | done | error
  const [groups,   setGroups]   = S([]);
  const [openQ,    setOpenQ]    = S({});
  const [errMsg,   setErrMsg]   = 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 generate = async () => {
    if (!window.groqStream) { setErrMsg("AI not available."); setStage("error"); return; }
    setStage("loading");
    setGroups([]);
    setErrMsg("");

    const ctx = window.buildResumeCtx ? window.buildResumeCtx(data) : JSON.stringify(data).slice(0, 4000);
    let raw = "";

    await window.groqStream({
      messages: [
        { role: "system", content: window.GROQ_SYSTEM || "" },
        { role: "user", content: `Based on this resume, generate 12 realistic interview questions a hiring manager would ask. Return ONLY a JSON array of objects with this structure:
[
  { "category": "Behavioral", "q": "Tell me about a time you led a team under pressure.", "hint": "Use STAR method — Situation, Task, Action, Result." },
  ...
]

Use 3 categories: "Behavioral" (4 questions), "Technical / Role-specific" (4 questions), "Career & Motivation" (4 questions).
Base questions directly on the candidate's specific experience, skills, and companies — not generic ones.

Resume:
${ctx}` },
      ],
      maxTokens: 1800,
      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);
          // Group by category
          const map = {};
          arr.forEach(item => {
            const cat = item.category || "General";
            if (!map[cat]) map[cat] = [];
            map[cat].push(item);
          });
          setGroups(Object.entries(map).map(([cat, qs]) => ({ cat, qs })));
          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 toggleQ = (key) => setOpenQ(o => ({ ...o, [key]: !o[key] }));

  const CATEGORY_COLORS = {
    "Behavioral":               { bg: "rgba(28,155,230,.08)",  color: "var(--brand-blue)" },
    "Technical / Role-specific":{ bg: "rgba(109,90,224,.08)",  color: "#6D5AE0" },
    "Career & Motivation":      { bg: "rgba(22,163,107,.08)",  color: "var(--good)" },
  };

  return (
    <>
      <div className="drawer-back" onClick={onClose} />
      <div className="drawer" style={{ width: 460 }}>
        <div className="drawer-h" style={{ display:"flex", alignItems:"center" }}>
          <div>
            <h3 style={{ margin:0, fontSize:16, fontWeight:700, color:"var(--navy)" }}>Interview Prep</h3>
            <p style={{ margin:"3px 0 0", fontSize:12.5, color:"var(--slate-500)" }}>AI questions tailored to your resume</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:"0 20px 24px" }}>
          {stage === "idle" && (
            <div style={{ textAlign:"center", padding:"40px 20px 20px" }}>
              <div style={{ width:56, height:56, borderRadius:"50%", background:"var(--grad)", display:"grid", placeItems:"center", margin:"0 auto 16px" }}>
                <Icon name="sparkle" size={24} style={{ color:"#fff" }} />
              </div>
              <h4 style={{ margin:"0 0 8px", color:"var(--navy)", fontSize:15 }}>Ready to practice?</h4>
              <p style={{ margin:"0 0 24px", fontSize:13.5, color:"var(--slate-500)", lineHeight:1.55 }}>
                AI analyzes your resume and generates 12 realistic questions across behavioral, technical, and motivation categories.
              </p>
              <button className="btn btn-grad" style={{ width:"100%", justifyContent:"center" }} onClick={generate}>
                <Icon name="writeai" size={15} /> Generate Interview Questions
              </button>
            </div>
          )}

          {stage === "loading" && (
            <div style={{ textAlign:"center", padding:"60px 20px" }}>
              <span className="spin" style={{ width:32, height:32, borderWidth:3, borderColor:"rgba(28,155,230,.2)", borderTopColor:"var(--brand-blue)", display:"inline-block" }} />
              <p style={{ marginTop:16, color:"var(--slate-500)", fontSize:13.5 }}>Analyzing your resume…</p>
            </div>
          )}

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

          {stage === "done" && (
            <>
              <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"16px 0 8px" }}>
                <span style={{ fontSize:12, color:"var(--slate-400)" }}>{groups.reduce((n,g)=>n+g.qs.length,0)} questions generated</span>
                <button className="btn btn-ghost btn-sm" onClick={generate}>↺ Regenerate</button>
              </div>

              {groups.map(({ cat, qs }) => {
                const col = CATEGORY_COLORS[cat] || { bg:"rgba(28,155,230,.08)", color:"var(--brand-blue)" };
                return (
                  <div key={cat} style={{ marginBottom:20 }}>
                    <div style={{ fontSize:11, fontWeight:800, letterSpacing:".07em", textTransform:"uppercase", color:col.color, background:col.bg, padding:"4px 10px", borderRadius:6, display:"inline-block", marginBottom:10 }}>
                      {cat}
                    </div>
                    <div style={{ display:"flex", flexDirection:"column", gap:6 }}>
                      {qs.map((item, qi) => {
                        const key = cat + qi;
                        const open = openQ[key];
                        return (
                          <div key={qi} style={{ border:"1px solid var(--slate-200)", borderRadius:10, overflow:"hidden" }}>
                            <button onClick={() => toggleQ(key)}
                              style={{ width:"100%", display:"flex", alignItems:"flex-start", gap:10, padding:"12px 14px", background:"#fff", border:"none", cursor:"pointer", textAlign:"left" }}>
                              <span style={{ fontSize:11, fontWeight:700, color:col.color, background:col.bg, borderRadius:"50%", width:22, height:22, display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0, marginTop:1 }}>
                                {qi+1}
                              </span>
                              <span style={{ flex:1, fontSize:13.5, fontWeight:600, color:"var(--navy)", lineHeight:1.4 }}>{item.q}</span>
                              <Icon name="chev" size={15} style={{ color:"var(--slate-400)", transform:open?"rotate(180deg)":"", transition:"transform .15s", flexShrink:0, marginTop:3 }} />
                            </button>
                            {open && (
                              <div style={{ padding:"0 14px 14px 46px", fontSize:12.5, color:"var(--slate-600)", lineHeight:1.55, borderTop:"1px solid var(--slate-100)", paddingTop:10 }}>
                                <span style={{ fontWeight:700, color:col.color }}>Tip: </span>{item.hint}
                              </div>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })}

              <button className="btn btn-grad" style={{ width:"100%", justifyContent:"center", marginTop:8 }} onClick={generate}>
                ↺ Regenerate Questions
              </button>
            </>
          )}
        </div>
      </div>
    </>
  );
}
