/* cover-letter.jsx — cover letter editor + live preview */

var CL_DEFAULTS = {
  date: "",
  toName: "",
  toTitle: "",
  toCompany: "",
  toAddress: "",
  opening: "Dear Hiring Manager,",
  body: "",
  closing: "Sincerely,",
};
var CL_FONT_STACKS = {
  geist:   '"Geist", -apple-system, "Segoe UI", sans-serif',
  ubuntu:  '"Ubuntu", sans-serif',
  lato:    '"Lato", sans-serif',
  roboto:  '"Roboto", sans-serif',
  opensans:'"Open Sans", sans-serif',
  mono:    '"Geist Mono", monospace',
  auto:    '"Geist", -apple-system, "Segoe UI", sans-serif',
};

function CoverLetterPreview({ cl, basics, accent, design }) {
  basics = basics || {};
  accent = accent || "#1C9BE6";
  design = design || {};
  var fontKey = design.font || "auto";
  var fontStack = CL_FONT_STACKS[fontKey] || CL_FONT_STACKS.auto;
  var date = cl.date || new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
  var toLines = [cl.toName, cl.toTitle, cl.toCompany, cl.toAddress].filter(Boolean);
  var body = cl.body || "";
  var paras = body.split("\n\n").filter(Boolean);

  return (
    <div style={{ fontFamily: fontStack, fontSize: 13.5, lineHeight: 1.65, color: "#15171f", padding: "72px 72px 80px", minHeight: 1056, background: "#fff" }}>
      {/* Sender */}
      <div style={{ marginBottom: 44 }}>
        <div style={{ fontSize: 23, fontWeight: 700, color: "#0f1117", letterSpacing: "-.018em" }}>
          {basics.name || "Your Name"}
        </div>
        {basics.title && (
          <div style={{ fontSize: 14, color: accent, fontWeight: 600, marginTop: 3 }}>{basics.title}</div>
        )}
        <div style={{ marginTop: 9, display: "flex", flexWrap: "wrap", gap: "3px 14px", fontSize: 12.5, color: "#5a6072" }}>
          {[basics.email, basics.phone, basics.location, basics.website].filter(Boolean).map(function(c, i) {
            return <span key={i}>{c}</span>;
          })}
        </div>
        <div style={{ marginTop: 12, height: 3, width: 40, borderRadius: 99, background: accent }} />
      </div>

      {/* Date */}
      <div style={{ marginBottom: 24, color: "#3a3d49" }}>{date}</div>

      {/* Recipient */}
      {toLines.length > 0 && (
        <div style={{ marginBottom: 28 }}>
          {toLines.map(function(ln, i) {
            return (
              <div key={i} style={{ fontWeight: i === 0 ? 600 : 400, color: i === 0 ? "#15171f" : "#3a3d49" }}>{ln}</div>
            );
          })}
        </div>
      )}

      {/* Opening */}
      {cl.opening && <div style={{ marginBottom: 22 }}>{cl.opening}</div>}

      {/* Body */}
      {paras.length > 0 ? (
        paras.map(function(para, i) {
          return <p key={i} style={{ margin: "0 0 18px", color: "#2a2d38" }}>{para}</p>;
        })
      ) : (
        <p style={{ margin: "0 0 18px", color: "#9aa2b8", fontStyle: "italic" }}>
          Your letter body will appear here. Write focused paragraphs about why you're a great fit for this role.
        </p>
      )}

      {/* Closing */}
      <div style={{ marginTop: 36 }}>
        <div style={{ marginBottom: 52, color: "#2a2d38" }}>{cl.closing || "Sincerely,"}</div>
        <div style={{ fontWeight: 700, color: "#0f1117", fontSize: 14 }}>{basics.name || "Your Name"}</div>
        {basics.title && (
          <div style={{ color: accent, fontSize: 13, marginTop: 2 }}>{basics.title}</div>
        )}
      </div>
    </div>
  );
}

function CoverLetterEditor({ cl, onChange, data, showToast }) {
  var set = function(k, v) { onChange(Object.assign({}, cl, { [k]: v })); };
  var today = new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });

  const { useState: S, useRef: R } = React;
  const [jd,         setJd]         = S("");
  const [showJd,     setShowJd]     = S(false);
  const [generating, setGenerating] = S(false);
  const bodyRef = R(null);

  const generate = () => {
    if (generating || !window.groqStream) return;
    setGenerating(true);

    const ctx = window.buildResumeCtx ? window.buildResumeCtx(data || {}) : "";
    const company  = cl.toCompany || "the company";
    const role     = cl.toTitle   || "the role";

    const prompt =
      "Write a targeted cover letter body using the résumé below" +
      (jd.trim() ? " and the job description provided" : "") + ".\n\n" +
      "RÉSUMÉ:\n" + ctx + "\n\n" +
      (jd.trim() ? "JOB DESCRIPTION:\n" + jd.trim() + "\n\n" : "") +
      "Company: " + company + "\n" +
      "Role: " + role + "\n\n" +
      "Write 3 paragraphs separated by a blank line (\\n\\n):\n" +
      "1. Opening — genuine enthusiasm for " + company + ", briefly who I am and my strongest credential.\n" +
      "2. Body — 2 specific, quantified achievements from my résumé that directly match the role's needs.\n" +
      "3. Closing — confident call to action, invite for an interview.\n\n" +
      "Under 350 words. Professional but warm. First-person. " +
      "Return ONLY the three paragraphs — no salutation, no date, no sign-off, no subject line.";

    let streamed = "";
    window.groqStream({
      messages: [
        { role: "system", content: window.GROQ_SYSTEM || "" },
        { role: "user",   content: prompt },
      ],
      maxTokens: 700,
      onChunk: (_, full) => {
        streamed = full;
        set("body", full);
      },
      onDone: (full) => {
        setGenerating(false);
        set("body", (full || streamed).trim());
        if (showToast) showToast("Cover letter generated!");
      },
      onError: (err) => {
        setGenerating(false);
        if (err === "free_limit_reached") {
          if (showToast) showToast("Free AI limit reached — upgrade to Pro for unlimited use.");
        } else {
          if (showToast) showToast("AI error: " + err);
        }
      },
    });
  };

  return (
    <div className="editor-inner">
      <div className="ed-head">
        <h2>Cover Letter</h2>
        <p>A targeted cover letter significantly improves your callback rate. Aim for three focused paragraphs — opening, body, close.</p>
      </div>

      {/* ── AI generation panel ─────────────────────────────── */}
      <div style={{ marginBottom: 20, borderRadius: 10, border: "1px solid var(--slate-100)", overflow: "hidden" }}>
        <div style={{ padding: "12px 14px", background: "linear-gradient(135deg,rgba(28,155,230,.06),rgba(83,74,183,.06))", display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ color: "var(--brand-blue)", display: "inline-flex" }}><Icon name="writeai" size={18} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 13.5, color: "var(--navy)" }}>Generate with AI</div>
            <div style={{ fontSize: 12, color: "var(--slate-500)", marginTop: 1 }}>
              Uses your résumé data{cl.toCompany ? " · " + cl.toCompany : ""}
              {jd.trim() ? " · JD pasted" : ""}
            </div>
          </div>
          <button
            className="btn btn-ghost btn-sm"
            style={{ fontSize: 12, color: "var(--slate-500)" }}
            onClick={() => setShowJd(s => !s)}
          >
            <Icon name={showJd ? "chev" : "plus"} size={13} style={{ transform: showJd ? "rotate(180deg)" : "" }} />
            {showJd ? "Hide JD" : "Paste JD"}
          </button>
          <button
            className="btn btn-grad btn-sm"
            disabled={generating}
            onClick={generate}
            style={{ gap: 6, minWidth: 110 }}
          >
            {generating
              ? <><span className="spin" style={{ width: 12, height: 12, borderColor: "rgba(255,255,255,.25)", borderTopColor: "#fff" }} /> Writing…</>
              : <><Icon name="writeai" size={14} /> Generate</>}
          </button>
        </div>

        {showJd && (
          <div style={{ padding: "0 14px 14px", borderTop: "1px solid var(--slate-100)" }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: "var(--slate-600)", margin: "12px 0 6px" }}>
              Job description <span style={{ fontWeight: 400, color: "var(--slate-400)" }}>optional — improves targeting</span>
            </div>
            <textarea
              className="ta"
              value={jd}
              onChange={e => setJd(e.target.value)}
              placeholder={"Paste the job description here…\n\nThe AI will mirror its language and highlight your most relevant achievements."}
              style={{ minHeight: 130, fontSize: 12.5, lineHeight: 1.55 }}
            />
          </div>
        )}
      </div>

      {/* ── Manual fields ────────────────────────────────────── */}
      <div className="field">
        <label>Date</label>
        <input className="inp" value={cl.date || ""} placeholder={today}
          onChange={function(e) { set("date", e.target.value); }} />
      </div>

      <div style={{ marginBottom: 12 }}>
        <div className="dz-label">Recipient</div>
        <div className="row2" style={{ marginBottom: 10 }}>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Name</label>
            <input className="inp" value={cl.toName || ""} placeholder="Hiring Manager"
              onChange={function(e) { set("toName", e.target.value); }} />
          </div>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Company</label>
            <input className="inp" value={cl.toCompany || ""} placeholder="Acme Corp"
              onChange={function(e) { set("toCompany", e.target.value); }} />
          </div>
        </div>
        <div className="row2" style={{ marginBottom: 10 }}>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Title <span className="hint">optional</span></label>
            <input className="inp" value={cl.toTitle || ""} placeholder="Director of Engineering"
              onChange={function(e) { set("toTitle", e.target.value); }} />
          </div>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Address <span className="hint">optional</span></label>
            <input className="inp" value={cl.toAddress || ""} placeholder="123 Main St, New York, NY"
              onChange={function(e) { set("toAddress", e.target.value); }} />
          </div>
        </div>
      </div>

      <div className="dz-label" style={{ marginBottom: 12 }}>Letter</div>
      <div className="field">
        <label>Opening salutation</label>
        <input className="inp" value={cl.opening || ""} placeholder="Dear Hiring Manager,"
          onChange={function(e) { set("opening", e.target.value); }} />
      </div>
      <div className="field">
        <label>
          Body
          <span className="hint">separate paragraphs with a blank line</span>
          {generating && <span style={{ marginLeft: 8, fontSize: 11, color: "var(--brand-blue)", fontWeight: 600 }}>● writing…</span>}
        </label>
        <textarea ref={bodyRef} className="ta" style={{ minHeight: 240 }} value={cl.body || ""}
          onChange={function(e) { set("body", e.target.value); }}
          placeholder={"I am writing to express my strong interest in the [Position] role at [Company]…\n\nOr click Generate above to write it with AI."} />
      </div>
      <div className="field">
        <label>Closing</label>
        <input className="inp" value={cl.closing || ""} placeholder="Sincerely,"
          onChange={function(e) { set("closing", e.target.value); }} />
      </div>

      <div className="tip" style={{ marginTop: 8 }}>
        <div className="t"><Icon name="sparkle" size={15} style={{ color: "var(--brand-blue)" }} /> Tips for a strong cover letter</div>
        <p>
          • Open with a specific achievement that directly addresses the role's needs.<br />
          • Mention something concrete you know about the company (a product, recent news, or their mission).<br />
          • Keep it to one page — 250–350 words is the sweet spot.<br />
          • Use "I" sparingly — put the company's needs at the centre, not yourself.
        </p>
      </div>
    </div>
  );
}

window.CL_DEFAULTS = CL_DEFAULTS;
window.CoverLetterEditor = CoverLetterEditor;
window.CoverLetterPreview = CoverLetterPreview;
