/* ai-panel.jsx — AI Resume Coach drawer */

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

  const isPro = !!window.IS_PRO;

  const [messages,   setMessages]  = S([
    { id: 0, role: "assistant", content: "Hi! I'm your BDRecruit AI Assistant. Use the quick actions below or ask me anything about your résumé.", done: true }
  ]);
  const [input,     setInput]      = S("");
  const [busy,      setBusy]       = S(false);
  const [limitHit,  setLimitHit]   = S(false);
  const [remaining, setRemaining]  = S(() => {
    var v = window.getAIUsesRemaining ? window.getAIUsesRemaining() : null;
    return v;
  });
  const msgRef   = R(null);
  const inputRef = R(null);
  const nextId   = R(1);

  const scrollDown = () => {
    setTimeout(() => { if (msgRef.current) msgRef.current.scrollTop = msgRef.current.scrollHeight; }, 30);
  };

  const send = (userContent, applyFn) => {
    if (busy || limitHit) return;
    if (!window.groqStream) return;
    setBusy(true);
    const uid = ++nextId.current;

    setMessages(m => [
      ...m,
      { id: uid - 1, role: "user", content: userContent, done: true },
      { id: uid,     role: "assistant", content: "", done: false, applyFn: applyFn || null },
    ]);
    scrollDown();

    const history = messages.slice(-16).map(x => ({
      role: x.role === "assistant" ? "assistant" : "user",
      content: x.content,
    })).filter(x => x.content);

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

    window.groqStream({
      messages: [
        { role: "system", content: (window.GROQ_SYSTEM || "") + "\n\nUser's current résumé:\n" + ctx },
        ...history,
        { role: "user", content: userContent },
      ],
      maxTokens: 600,
      onChunk: (_, full) => {
        setMessages(m => m.map(x => x.id === uid ? { ...x, content: full } : x));
        scrollDown();
      },
      onDone: (full) => {
        setBusy(false);
        setMessages(m => m.map(x => x.id === uid ? { ...x, content: full, done: true } : x));
        // Update remaining count
        const r = window.getAIUsesRemaining ? window.getAIUsesRemaining() : null;
        setRemaining(r);
        scrollDown();
      },
      onError: (err) => {
        setBusy(false);
        if (err === "free_limit_reached") {
          setLimitHit(true);
          setMessages(m => m.map(x => x.id === uid ? { ...x, content: "", done: true, error: true, limitHit: true, applyFn: null } : x));
        } else {
          setMessages(m => m.map(x => x.id === uid ? { ...x, content: "⚠️ " + err, done: true, error: true, applyFn: null } : x));
        }
      },
    });
  };

  const applyMsg = (msg) => {
    if (msg.applyFn) {
      msg.applyFn(msg.content);
      setMessages(m => m.map(x => x.id === msg.id ? { ...x, applied: true } : x));
    }
  };

  /* ── Quick actions ─────────────────────────────────────────── */
  const qa_summary = () => send(
    "Write a compelling 2–3 sentence professional summary for my résumé. Use strong language, quantify where possible, no first-person pronouns. Return ONLY the summary text.",
    (content) => patch(d => ({ ...d, summary: content.replace(/^["']|["']$/g, "").trim() }))
  );

  const qa_bullets = () => {
    const pairs = ((data.experience || [])).flatMap(x =>
      ((x.bullets || []).filter(b => b.trim()).map(b => (x.role || "") + " at " + (x.company || "") + ': "' + b + '"'))
    );
    if (!pairs.length) { send("There are no experience bullets in the résumé yet — please add some work experience first!", null); return; }
    send(
      "Rewrite each of these experience bullet points to be more impactful — stronger action verbs, quantified results where inferrable. Return EXACTLY the same number of bullets, one per line, no bullet prefix, no numbering:\n\n" + pairs.join("\n"),
      (content) => {
        const improved = content.split("\n").map(l => l.replace(/^[•·\-\*\d.)]+\s*/, "").trim()).filter(Boolean);
        var idx = 0;
        patch(d => ({
          ...d,
          experience: (d.experience || []).map(x => ({
            ...x,
            bullets: (x.bullets || []).filter(b => b.trim()).map(() => improved[idx++] || "").filter(Boolean),
          })),
        }));
      }
    );
  };

  const qa_coverletter = () => send(
    "Write a full cover letter based on my résumé. Use 3 paragraphs separated by blank lines: opening (genuine interest in role + who I am), body (2 specific achievements from my background), closing (call to action). Under 350 words. Professional but warm.",
    (content) => {
      setCoverLetter(cl => ({ ...cl, body: content.trim() }));
      if (showToast) showToast("Cover letter saved — opening tab…");
      if (onGotoCoverLetter) setTimeout(onGotoCoverLetter, 900);
    }
  );

  const qa_review = () => send(
    "Review my entire résumé and give me your top 5 most impactful, specific improvements I can make right now. Be direct and focus on highest-impact changes only — no generic advice."
  );

  const qa_skills = () => send(
    "Based on my experience and background, what 10–15 additional skills or keywords am I missing that would strengthen my résumé for ATS matching? Group them by category (Tools, Methodologies, Soft Skills, etc.)."
  );

  const qa_email = () => send(
    "Write a short, compelling cold outreach email I could send when applying for a role. Under 150 words. Include: subject line on its first line, then the email body. Use my most impressive achievement as the hook."
  );

  const quickActions = [
    { icon: "text",    label: "Write summary",    fn: qa_summary },
    { icon: "sparkle", label: "Improve bullets",  fn: qa_bullets },
    { icon: "letter",  label: "Cover letter",     fn: qa_coverletter },
    { icon: "eye",     label: "Review résumé",    fn: qa_review },
    { icon: "bolt",    label: "Suggest skills",   fn: qa_skills },
    { icon: "mail",    label: "Cold email",       fn: qa_email },
  ];

  const handleSend = () => {
    const txt = input.trim();
    if (!txt || busy || limitHit) return;
    setInput("");
    send(txt, null);
    if (inputRef.current) inputRef.current.style.height = "38px";
  };

  const usageBar = !isPro && remaining !== null && remaining !== Infinity;
  const usedCount = usageBar ? Math.max(0, 10 - remaining) : 0;

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

        {/* Header */}
        <div className="drawer-h ai-drawer-h">
          <div className="ai-drawer-brand">
            <div className="ai-avatar-hdr"><RobotFace size={24} variant="light" /></div>
            <div>
              <h3 className="ai-drawer-title">BDRecruit AI Assistant</h3>
              <p className="ai-drawer-sub">Powered by BDRecruit AI</p>
            </div>
          </div>
          <div style={{ flex: 1 }} />
          {isPro && (
            <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--brand-green)", background: "rgba(52,199,127,.12)", border: "1px solid rgba(52,199,127,.25)", borderRadius: 99, padding: "3px 9px" }}>Pro</span>
          )}
          <button className="x" onClick={onClose} style={{ marginLeft: 4 }}>
            <Icon name="x" size={18} />
          </button>
        </div>

        {/* Usage bar — free users only, after first call */}
        {usageBar && (
          <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: (usedCount / 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>
        )}

        {/* Limit hit banner */}
        {limitHit && (
          <div style={{ margin: "0 16px 0", padding: "12px 14px", background: "#EEEDFE", border: "1px solid #AFA9EC", borderRadius: 10, display: "flex", flexDirection: "column", gap: 6 }}>
            <div style={{ fontWeight: 700, fontSize: 13, color: "#3C3489" }}>You've used all 10 free AI requests</div>
            <div style={{ fontSize: 12.5, color: "#534AB7", lineHeight: 1.5 }}>Upgrade to Pro for unlimited AI coaching, the Tailor to Job feature, and priority support.</div>
            <a href={(window.__LANDING_URL__ || "http://localhost:3401").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>
        )}

        {/* Quick actions */}
        <div className="ai-quick-row">
          {quickActions.map((a, i) => (
            <button key={i} className="ai-qa-btn" disabled={busy || limitHit} onClick={a.fn}>
              <Icon name={a.icon} size={13} style={{ flexShrink: 0 }} />
              {a.label}
            </button>
          ))}
        </div>

        {/* Messages */}
        <div className="ai-msgs scroll" ref={msgRef}>
          {messages.map((msg) => (
            <div key={msg.id} className={"ai-msg-row " + (msg.role === "user" ? "user" : "asst")}>
              {msg.role === "assistant" && <div className="ai-msg-avatar"><RobotFace size={18} variant="light" /></div>}
              <div className={"ai-bubble" + (msg.error ? " ai-bubble-err" : "") + (msg.role === "user" ? " ai-bubble-user" : "")}>
                {msg.limitHit ? (
                  <div className="ai-bubble-txt" style={{ color: "var(--slate-500)", fontStyle: "italic" }}>
                    Free limit reached — upgrade to Pro for unlimited AI.
                  </div>
                ) : (
                  <div className="ai-bubble-txt" style={{ whiteSpace: "pre-wrap" }}>
                    {msg.content}
                    {!msg.done && !msg.error && <span className="ai-cursor" />}
                  </div>
                )}
                {msg.role === "assistant" && msg.done && !msg.error && msg.content && (
                  <div className="ai-apply-row">
                    {msg.applyFn && !msg.applied && (
                      <>
                        <button className="btn btn-grad btn-sm" onClick={() => applyMsg(msg)}>
                          <Icon name="check" size={14} /> Apply to résumé
                        </button>
                        <button className="btn btn-ghost btn-sm" onClick={() =>
                          setMessages(m => m.map(x => x.id === msg.id ? { ...x, applyFn: null } : x))
                        }>Dismiss</button>
                      </>
                    )}
                    {msg.applied && <span className="ai-applied-note" style={{ margin: 0 }}>✅ Applied</span>}
                    <button className="btn btn-ghost btn-sm" style={{ marginLeft: "auto" }}
                      onClick={() => {
                        navigator.clipboard.writeText(msg.content).then(() => {
                          if (showToast) showToast("Copied!");
                        }).catch(() => {});
                      }}>
                      <Icon name="copy" size={13} /> Copy
                    </button>
                  </div>
                )}
              </div>
            </div>
          ))}
          {busy && (
            <div className="ai-msg-row asst">
              <div className="ai-msg-avatar"><RobotFace size={18} variant="light" /></div>
              <div className="ai-bubble">
                <div className="ai-typing-dots"><span /><span /><span /></div>
              </div>
            </div>
          )}
        </div>

        {/* Input area */}
        <div className="ai-input-area">
          <textarea className="ai-input" ref={inputRef} value={input}
            placeholder={limitHit ? "Upgrade to Pro to continue…" : "Ask anything about your résumé… (Enter to send, Shift+Enter for newline)"}
            rows={1}
            disabled={limitHit}
            onChange={e => {
              setInput(e.target.value);
              e.target.style.height = "38px";
              e.target.style.height = Math.min(e.target.scrollHeight, 120) + "px";
            }}
            onKeyDown={e => {
              if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSend(); }
            }}
          />
          <button className="btn btn-grad ai-send-btn" disabled={!input.trim() || busy || limitHit} onClick={handleSend}>
            <Icon name="export" size={15} />
          </button>
        </div>

      </div>
    </>
  );
}

window.AIPanel = AIPanel;
