/* cold-email.jsx — Cold email / cover note generator */

const EMAIL_TONES = [
  { id:"professional", label:"Professional", desc:"Formal, polished" },
  { id:"confident",    label:"Confident",    desc:"Direct, assertive" },
  { id:"friendly",     label:"Friendly",     desc:"Warm, approachable" },
];

const EMAIL_TYPES = [
  { id:"outreach",  label:"Cold outreach",     desc:"Reach out to recruiter / hiring manager directly" },
  { id:"apply",     label:"Application note",  desc:"Short email when submitting application" },
  { id:"followup",  label:"Follow-up",         desc:"After no response for 1–2 weeks" },
];

function ColdEmailDrawer({ data, onClose }) {
  const { useState: S, useEffect: E } = React;
  const [jobText,  setJobText]  = S("");
  const [tone,     setTone]     = S("professional");
  const [type,     setType]     = S("outreach");
  const [stage,    setStage]    = S("idle");
  const [email,    setEmail]    = S("");
  const [copied,   setCopied]   = S(false);
  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; }
    if (!jobText.trim()) { setErrMsg("Paste a job posting or job description first."); return; }
    setStage("loading"); setEmail(""); setErrMsg("");

    const ctx = window.buildResumeCtx ? window.buildResumeCtx(data) : "";
    const toneLabel = EMAIL_TONES.find(t => t.id === tone)?.label || "Professional";
    const typeLabel = EMAIL_TYPES.find(t => t.id === type)?.label || "Cold outreach";

    await window.groqStream({
      messages: [
        { role: "system", content: window.GROQ_SYSTEM || "" },
        { role: "user", content: `Write a ${toneLabel.toLowerCase()} ${typeLabel.toLowerCase()} email for a job application.

Type: ${typeLabel}
Tone: ${toneLabel}

Rules:
- EXACTLY 3 short paragraphs (2-3 sentences each)
- Paragraph 1: Who you are + strongest relevant credential from resume
- Paragraph 2: Why THIS specific role/company (use details from job posting)
- Paragraph 3: Clear call to action (request a call / meeting)
- No subject line — just the email body
- No generic phrases like "I hope this email finds you well"
- No "I am writing to express my interest"
- Strong verbs, specific numbers from resume where relevant
- End with candidate's name: ${data.basics?.name || "[Your Name]"}

Candidate resume context:
${ctx.slice(0, 2000)}

Job posting:
${jobText.slice(0, 2000)}` },
      ],
      maxTokens: 600,
      onChunk: (_, full) => { setEmail(full); setStage("streaming"); },
      onDone: (full) => { setEmail(full); setStage("done"); },
      onError: e => { if (e === "free_limit_reached") { setLimitHit(true); } else { setErrMsg(typeof e==="string"?e:"AI error."); } setStage("error"); },
    });
  };

  const copy = () => {
    navigator.clipboard?.writeText(email).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2200);
    });
  };

  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)" }}>Cold Email Generator</h3>
            <p style={{ margin:"3px 0 0", fontSize:12.5, color:"var(--slate-500)" }}>3-paragraph outreach from resume + job posting</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" }}>

          {/* Email type */}
          <div style={{ marginBottom:16 }}>
            <label style={{ fontSize:12, fontWeight:700, color:"var(--slate-600)", textTransform:"uppercase", letterSpacing:".06em", display:"block", marginBottom:8 }}>Email type</label>
            <div style={{ display:"flex", gap:6 }}>
              {EMAIL_TYPES.map(t => (
                <button key={t.id} onClick={() => setType(t.id)}
                  style={{ flex:1, padding:"8px 6px", borderRadius:9, border:"2px solid", borderColor: type===t.id?"var(--brand-blue)":"var(--slate-200)", background: type===t.id?"rgba(28,155,230,.06)":"#fff", cursor:"pointer", textAlign:"center" }}>
                  <div style={{ fontSize:12, fontWeight:700, color: type===t.id?"var(--brand-blue)":"var(--navy)" }}>{t.label}</div>
                  <div style={{ fontSize:10.5, color:"var(--slate-400)", marginTop:2 }}>{t.desc}</div>
                </button>
              ))}
            </div>
          </div>

          {/* Tone */}
          <div style={{ marginBottom:16 }}>
            <label style={{ fontSize:12, fontWeight:700, color:"var(--slate-600)", textTransform:"uppercase", letterSpacing:".06em", display:"block", marginBottom:8 }}>Tone</label>
            <div style={{ display:"flex", gap:6 }}>
              {EMAIL_TONES.map(t => (
                <button key={t.id} onClick={() => setTone(t.id)}
                  style={{ flex:1, padding:"7px 8px", borderRadius:9, border:"2px solid", borderColor: tone===t.id?"var(--brand-blue)":"var(--slate-200)", background: tone===t.id?"rgba(28,155,230,.06)":"#fff", cursor:"pointer" }}>
                  <div style={{ fontSize:12.5, fontWeight:700, color: tone===t.id?"var(--brand-blue)":"var(--navy)" }}>{t.label}</div>
                  <div style={{ fontSize:10.5, color:"var(--slate-400)" }}>{t.desc}</div>
                </button>
              ))}
            </div>
          </div>

          {/* Job posting input */}
          <div style={{ marginBottom:16 }}>
            <label style={{ fontSize:12, fontWeight:700, color:"var(--slate-600)", textTransform:"uppercase", letterSpacing:".06em", display:"block", marginBottom:8 }}>
              Job posting / description
            </label>
            <textarea
              style={{ width:"100%", minHeight:120, padding:"11px 13px", boxSizing:"border-box", border:"1.5px solid var(--slate-200)", borderRadius:10, fontFamily:"inherit", fontSize:13, color:"var(--navy)", lineHeight:1.6, resize:"vertical", outline:"none", background:"#fff" }}
              placeholder={"Paste job title, company name, and key requirements...\n\nSenior Product Designer at Stripe\n\nWe're looking for a product designer with 5+ years experience designing complex financial products..."}
              value={jobText}
              onChange={e => setJobText(e.target.value)}
            />
            {errMsg && !email && <div style={{ marginTop:6, fontSize:12.5, color:"var(--danger)" }}>{errMsg}</div>}
          </div>

          <button className="btn btn-grad" style={{ width:"100%", justifyContent:"center", marginBottom:16 }}
            disabled={stage==="loading" || stage==="streaming"} onClick={generate}>
            {stage==="loading" || stage==="streaming"
              ? <><span className="spin" style={{ width:14, height:14, borderWidth:2, borderColor:"rgba(255,255,255,.3)", borderTopColor:"#fff", display:"inline-block", verticalAlign:"middle", marginRight:7 }} />Writing…</>
              : <><Icon name="writeai" size={15} style={{ marginRight: 7, verticalAlign: "middle" }} />Generate Email</>}
          </button>

          {/* Output */}
          {(stage === "streaming" || stage === "done") && email && (
            <div>
              <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:8 }}>
                <span style={{ fontSize:12, fontWeight:700, color:"var(--slate-500)", textTransform:"uppercase", letterSpacing:".06em" }}>Generated email</span>
                <div style={{ display:"flex", gap:6 }}>
                  {stage === "done" && <button className="btn btn-ghost btn-sm" onClick={generate}>↺ Regenerate</button>}
                  <button className="btn btn-grad btn-sm" onClick={copy} style={{ background: copied ? "var(--good)" : undefined, borderColor: copied ? "var(--good)" : undefined }}>
                    {copied ? "✓ Copied!" : "Copy"}
                  </button>
                </div>
              </div>
              <textarea
                style={{ width:"100%", minHeight:220, padding:"14px", boxSizing:"border-box", border:"1.5px solid var(--slate-200)", borderRadius:10, fontFamily:"inherit", fontSize:13.5, color:"var(--navy)", lineHeight:1.7, resize:"vertical", outline:"none", background:"#fafbfc" }}
                value={email}
                onChange={e => setEmail(e.target.value)}
              />
              <div style={{ fontSize:11, color:"var(--slate-400)", marginTop:6 }}>Edit directly in the box above before copying.</div>
            </div>
          )}

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