/* Inbox fournisseurs — classifie + drafte les réponses d'emails reçus
   POST /api/email/classify-reply (Claude sonnet-4-6) */

const CLASS_META = {
  interesse:    { label: "Intéressé",      tone: "green",  icon: "check"  },
  prix:         { label: "Grille de prix", tone: "accent", icon: "dollar" },
  demande_info: { label: "Demande info",   tone: "amber",  icon: "bell"   },
  refus:        { label: "Refus",          tone: "red",    icon: "x"      },
  absent:       { label: "Out of office",  tone: "muted",  icon: "clock"  },
  spam:         { label: "Spam",           tone: "muted",  icon: "x"      },
  neutre:       { label: "Neutre",         tone: "muted",  icon: "mail"   },
};

const URG_TONE = { high: "red", medium: "amber", low: "muted" };

const SupplierInbox = () => {
  const toast = (window.useToast || (() => () => {}))();
  const [from, setFrom] = useState("");
  const [subject, setSubject] = useState("");
  const [body, setBody] = useState("");
  const [original, setOriginal] = useState("");
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [err, setErr] = useState(null);
  const [history, setHistory] = useState(() => {
    try { return JSON.parse(localStorage.getItem("kcc:inbox-history") || "[]"); }
    catch { return []; }
  });

  // JARVIS hand-off: si l'IA a appelé classify_email_reply, charge le prefill
  useEffect(() => {
    try {
      const raw = localStorage.getItem("kcc:inbox-prefill");
      if (raw) {
        const p = JSON.parse(raw);
        if (p.from) setFrom(p.from);
        if (p.subject) setSubject(p.subject);
        if (p.body) setBody(p.body);
        localStorage.removeItem("kcc:inbox-prefill");
        toast?.({ message: "Email pré-rempli par JARVIS — clique « Classer »", tone: "blue" });
      }
    } catch (_) {}
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const submit = async () => {
    if (!body.trim()) { toast?.({ message: "Corps de l'email requis", tone: "red" }); return; }
    setLoading(true); setErr(null); setResult(null);
    try {
      const r = await fetch("/api/email/classify-reply", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          subject: subject.trim(),
          body: body.trim(),
          fromEmail: from.trim() || undefined,
          originalThread: original.trim() || undefined,
        }),
      });
      const data = await r.json();
      if (!r.ok || data.error || data.blocked) {
        setErr(data.error || data.reason || "Erreur classifieur");
        toast?.({ message: "Erreur: " + (data.error || data.reason || r.status), tone: "red" });
      } else {
        setResult(data);
        const entry = {
          id: "ib-" + Date.now().toString(36),
          at: Date.now(),
          from: from.trim(), subject: subject.trim(),
          classification: data.classification,
          urgency: data.urgency,
        };
        const next = [entry, ...history].slice(0, 30);
        setHistory(next);
        try { localStorage.setItem("kcc:inbox-history", JSON.stringify(next)); } catch (_) {}
        toast?.({ message: `Classé: ${CLASS_META[data.classification]?.label || data.classification}`, tone: "green" });
      }
    } catch (e) {
      setErr(e.message);
      toast?.({ message: "Erreur réseau: " + e.message, tone: "red" });
    } finally {
      setLoading(false);
    }
  };

  const copy = (text, label) => {
    try {
      navigator.clipboard.writeText(text);
      toast?.({ message: `${label} copié`, tone: "green" });
    } catch (_) {
      toast?.({ message: "Copie échouée", tone: "red" });
    }
  };

  const mailReply = (draft) => {
    if (!from.trim()) { toast?.({ message: "Email expéditeur requis", tone: "amber" }); return; }
    const re = subject.toLowerCase().startsWith("re:") ? subject : "Re: " + (subject || "Votre courriel");
    const url = `mailto:${encodeURIComponent(from)}?subject=${encodeURIComponent(re)}&body=${encodeURIComponent(draft)}`;
    window.location.href = url;
  };

  const clear = () => {
    setFrom(""); setSubject(""); setBody(""); setOriginal("");
    setResult(null); setErr(null);
  };

  const c = result?.classification;
  const meta = c ? CLASS_META[c] || CLASS_META.neutre : null;

  return (
    <div className="page" style={{ maxWidth: 1080 }}>
      <div className="page-head">
        <div>
          <div className="page-title">Inbox fournisseurs</div>
          <div className="page-sub">Colle une réponse fournisseur — Claude classe, extrait les points clés et drafte ta réponse FR/EN.</div>
        </div>
        <div className="row" style={{ gap: 6 }}>
          <button className="btn" onClick={clear}><Icon name="x" size={12}/> Vider</button>
          <button className="btn" data-variant="primary" onClick={submit} disabled={loading || !body.trim()}>
            <Icon name="sparkles" size={12}/> {loading ? "Analyse…" : "Classer + drafter"}
          </button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        {/* COLONNE GAUCHE — INPUT */}
        <div className="card" style={{ padding: 16 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: "var(--text-dim)", marginBottom: 10, textTransform: "uppercase", letterSpacing: 0.5 }}>
            Email reçu
          </div>

          <div style={{ marginBottom: 10 }}>
            <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>De</div>
            <div className="input" style={{ height: 32, padding: "0 10px" }}>
              <input value={from} onChange={e => setFrom(e.target.value)} placeholder="sales@fournisseur.ca"
                style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
            </div>
          </div>

          <div style={{ marginBottom: 10 }}>
            <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Sujet</div>
            <div className="input" style={{ height: 32, padding: "0 10px" }}>
              <input value={subject} onChange={e => setSubject(e.target.value)} placeholder="RE: B2B wholesale inquiry"
                style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
            </div>
          </div>

          <div style={{ marginBottom: 10 }}>
            <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Corps *</div>
            <textarea value={body} onChange={e => setBody(e.target.value)}
              placeholder="Colle le corps de l'email du fournisseur…"
              style={{ width: "100%", minHeight: 220, padding: 10, fontSize: 12.5, fontFamily: "inherit", background: "var(--bg-2)", color: "var(--text)", border: "1px solid var(--border)", borderRadius: 6, resize: "vertical" }}/>
          </div>

          <details>
            <summary style={{ fontSize: 11, color: "var(--text-dim)", cursor: "pointer", marginBottom: 6 }}>
              + Contexte (cold email envoyé)
            </summary>
            <textarea value={original} onChange={e => setOriginal(e.target.value)}
              placeholder="Colle ton cold email initial pour donner du contexte (optionnel)"
              style={{ width: "100%", minHeight: 80, padding: 10, fontSize: 12, fontFamily: "inherit", background: "var(--bg-2)", color: "var(--text)", border: "1px solid var(--border)", borderRadius: 6, resize: "vertical" }}/>
          </details>
        </div>

        {/* COLONNE DROITE — RÉSULTAT */}
        <div className="card" style={{ padding: 16, minHeight: 400 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: "var(--text-dim)", marginBottom: 10, textTransform: "uppercase", letterSpacing: 0.5 }}>
            Analyse Claude
          </div>

          {!result && !err && !loading && (
            <div style={{ textAlign: "center", padding: 40, color: "var(--text-faint)", fontSize: 12.5 }}>
              <Icon name="sparkles" size={24}/>
              <div style={{ marginTop: 10 }}>Colle un email puis clique « Classer + drafter ».</div>
            </div>
          )}
          {loading && (
            <div style={{ textAlign: "center", padding: 40, color: "var(--text-dim)", fontSize: 12.5 }}>
              Analyse en cours…
            </div>
          )}
          {err && (
            <div className="card" style={{ padding: 14, background: "color-mix(in srgb, var(--red) 12%, transparent)", border: "1px solid var(--red)" }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--red)", marginBottom: 4 }}>Erreur</div>
              <div className="mono" style={{ fontSize: 11.5 }}>{err}</div>
            </div>
          )}

          {result && (
            <div className="stack" style={{ gap: 14 }}>
              <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
                <Badge tone={meta.tone === "muted" ? undefined : meta.tone} dot>{meta.label}</Badge>
                <Badge tone={URG_TONE[result.urgency]} dot>Urgence: {result.urgency}</Badge>
                <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>
                  Confiance: {result.confidence}
                </span>
              </div>

              {Array.isArray(result.tags) && result.tags.length > 0 && (
                <div className="row" style={{ gap: 4, flexWrap: "wrap" }}>
                  {result.tags.map((t, i) => (
                    <span key={i} className="mono" style={{ fontSize: 10, padding: "2px 6px", background: "var(--bg-3)", borderRadius: 4, color: "var(--text-dim)" }}>{t}</span>
                  ))}
                </div>
              )}

              {Array.isArray(result.keyPoints) && result.keyPoints.length > 0 && (
                <div>
                  <div style={{ fontSize: 11, fontWeight: 600, color: "var(--text-dim)", marginBottom: 4, textTransform: "uppercase", letterSpacing: 0.5 }}>Points clés</div>
                  <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12.5 }}>
                    {result.keyPoints.map((p, i) => <li key={i} style={{ marginBottom: 3 }}>{p}</li>)}
                  </ul>
                </div>
              )}

              {result.nextStep && (
                <div style={{ padding: 10, background: "var(--bg-2)", borderRadius: 6, borderLeft: "3px solid var(--accent)" }}>
                  <div style={{ fontSize: 10.5, fontWeight: 600, color: "var(--text-dim)", marginBottom: 3, textTransform: "uppercase", letterSpacing: 0.5 }}>Prochaine action</div>
                  <div style={{ fontSize: 12.5 }}>{result.nextStep}</div>
                </div>
              )}

              {result.draftReplyFR && (
                <div>
                  <div className="between" style={{ marginBottom: 4 }}>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: 0.5 }}>Brouillon FR</div>
                    <div className="row" style={{ gap: 4 }}>
                      <button className="btn" data-variant="ghost" data-size="sm" onClick={() => copy(result.draftReplyFR, "Brouillon FR")}>
                        <Icon name="copy" size={11}/> Copier
                      </button>
                      <button className="btn" data-variant="primary" data-size="sm" onClick={() => mailReply(result.draftReplyFR)}>
                        <Icon name="mail" size={11}/> Mailto
                      </button>
                    </div>
                  </div>
                  <textarea readOnly value={result.draftReplyFR}
                    style={{ width: "100%", minHeight: 120, padding: 10, fontSize: 12, fontFamily: "inherit", background: "var(--bg-2)", color: "var(--text)", border: "1px solid var(--border)", borderRadius: 6, resize: "vertical" }}/>
                </div>
              )}

              {result.draftReplyEN && (
                <div>
                  <div className="between" style={{ marginBottom: 4 }}>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: 0.5 }}>Draft EN</div>
                    <div className="row" style={{ gap: 4 }}>
                      <button className="btn" data-variant="ghost" data-size="sm" onClick={() => copy(result.draftReplyEN, "Draft EN")}>
                        <Icon name="copy" size={11}/> Copy
                      </button>
                      <button className="btn" data-variant="primary" data-size="sm" onClick={() => mailReply(result.draftReplyEN)}>
                        <Icon name="mail" size={11}/> Mailto
                      </button>
                    </div>
                  </div>
                  <textarea readOnly value={result.draftReplyEN}
                    style={{ width: "100%", minHeight: 120, padding: 10, fontSize: 12, fontFamily: "inherit", background: "var(--bg-2)", color: "var(--text)", border: "1px solid var(--border)", borderRadius: 6, resize: "vertical" }}/>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {history.length > 0 && (
        <div className="card" style={{ padding: 16, marginTop: 16 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: "var(--text-dim)", marginBottom: 10, textTransform: "uppercase", letterSpacing: 0.5 }}>
            Historique ({history.length})
          </div>
          <table className="table" style={{ fontSize: 12 }}>
            <thead>
              <tr>
                <th>Quand</th>
                <th>De</th>
                <th>Sujet</th>
                <th>Classification</th>
                <th>Urgence</th>
              </tr>
            </thead>
            <tbody>
              {history.map(h => (
                <tr key={h.id}>
                  <td className="mono" style={{ fontSize: 11 }}>{new Date(h.at).toLocaleString("fr-CA")}</td>
                  <td>{h.from || "—"}</td>
                  <td style={{ maxWidth: 280, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{h.subject || "—"}</td>
                  <td>{CLASS_META[h.classification]?.label || h.classification}</td>
                  <td>
                    <Badge tone={URG_TONE[h.urgency]} dot>{h.urgency}</Badge>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

window.SupplierInbox = SupplierInbox;
