/* global React, window */
// =====================================================================
// ExecutionsView — "Ejecuciones": cola de acciones sobre leads (propose-only)
// generadas por el lead-actuator desde las decisiones del Command Center.
// Look & feel de project cards + info. Aprobar/Rechazar = solo status (NO toca Zoho).
// Todo vive en windmar-marketing (marketing.lead_actions) + RAG.
// =====================================================================
(function () {
  const { useState, useEffect, useMemo } = React;

  if (window.i18n) {
    if (window.i18n.es && window.i18n.es.tabs) window.i18n.es.tabs.ejecuciones = "Lead Association";
    if (window.i18n.en && window.i18n.en.tabs) window.i18n.en.tabs.ejecuciones = "Lead Association";
  }

  const GREEN = "var(--op-green,#1f9d57)", RED = "var(--op-red,#d23b3b)", AMBER = "var(--op-amber,#F89B24)", NAVY = "var(--wm-blue,#1D429B)";

  // action_type → presentación (project-card)
  const ACTION = {
    reroute_leads:   { icon: "git-branch",   label: "Re-rutear leads",   color: AMBER },
    prioritize_leads:{ icon: "trending-up",  label: "Priorizar leads",   color: GREEN },
    no_action:       { icon: "check",        label: "Mantener (sin cambio)", color: "var(--wm-fg-muted)" },
    review:          { icon: "help-circle",  label: "Revisar",           color: "var(--wm-fg-muted)" },
    associate_zoho:  { icon: "link",         label: "Asociar en Zoho",   color: NAVY },
  };
  const actionOf = (t) => ACTION[t] || (String(t).indexOf("audience") === 0
    ? { icon: "radar", label: "Audiencia", color: NAVY } : { icon: "zap", label: t, color: NAVY });
  const STATUS = {
    proposed: { label: "Propuesta", color: NAVY, bg: "var(--op-blue-50,#EAF0FB)" },
    approved: { label: "Aprobada", color: GREEN, bg: "var(--op-green-50,#E8F4EE)" },
    rejected: { label: "Rechazada", color: RED, bg: "var(--op-red-50,#FBE8E5)" },
    done:     { label: "Hecho en Zoho", color: GREEN, bg: "var(--op-green-50,#E8F4EE)" },
  };

  function ExecutionsView({ lang = "es" }) {
    const es = lang === "es";
    const [rows, setRows] = useState(null);
    const [stolen, setStolen] = useState(null);
    const [filter, setFilter] = useState("all");
    const [busy, setBusy] = useState(null);
    const [toast, setToast] = useState(null);

    const load = () => {
      if (window.wm && window.wm.ready && window.wm.leadActions) window.wm.leadActions().then(r => setRows(Array.isArray(r) ? r : []));
      else setRows([]);
    };
    useEffect(() => { load(); }, []);
    // Leads tuyos sin atribuir (won sin source matcheados a un lead digital) — atribución lead-first.
    const [summary, setSummary] = useState(null);
    const loadStolen = () => {
      if (!window.fetchStolenLeads) { setStolen([]); return; }
      const t = new Date(); const fmt = (d) => d.toISOString().slice(0, 10);
      const from = fmt(new Date(t.getFullYear() - 1, t.getMonth() - 5, 1)); // ~18 meses histórico
      window.fetchStolenLeads(from, fmt(t)).then(r => setStolen(Array.isArray(r) ? r.filter(x => x.digital_channel === "meta" || x.digital_channel === "google") : []));
      if (window.fetchStolenSummary) window.fetchStolenSummary(from, fmt(t)).then(setSummary);
    };
    useEffect(() => { loadStolen(); }, []);
    const zohoLeadUrl = (id) => id ? "https://crm.zoho.com/crm/org699641359/tab/Leads/" + id : null;
    // "Resuelto" = ya lo asocié/corregí en Zoho → loguea y nunca se vuelve a sugerir.
    const resolveStolen = async (zoho_id) => {
      if (!window.resolveAttribution) return;
      setBusy(zoho_id);
      const r = await window.resolveAttribution(zoho_id);
      setBusy(null);
      if (r && r.ok) { setStolen(prev => (prev || []).filter(x => x.won_zoho_id !== zoho_id)); setToast({ k: "ok", m: es ? "✓ Logueado — no se vuelve a sugerir" : "✓ Logged — won't suggest again" }); }
      else setToast({ k: "err", m: "Error" });
    };
    useEffect(() => { if (!toast) return; const id = setTimeout(() => setToast(null), 2600); return () => clearTimeout(id); }, [toast]);

    const decide = async (id, status) => {
      if (!window.wm || !window.wm.leadActionDecide) return;
      setBusy(id);
      const r = await window.wm.leadActionDecide(id, status);
      setBusy(null);
      if (r && r.ok) {
        const msg = ({ approved: es ? "✓ Aprobada" : "✓ Approved", rejected: es ? "Rechazada" : "Rejected", done: es ? "✓ Hecho en Zoho" : "✓ Done", proposed: es ? "Reabierta" : "Reopened" })[status] || status;
        setToast({ k: "ok", m: msg }); load();
      } else setToast({ k: "err", m: (r && r.error) || "Error" });
    };

    const list = useMemo(() => (rows || []).filter(r => filter === "all" || r.status === filter), [rows, filter]);
    const counts = useMemo(() => {
      const c = { all: (rows || []).length, proposed: 0, approved: 0, rejected: 0 };
      (rows || []).forEach(r => { if (c[r.status] != null) c[r.status]++; });
      return c;
    }, [rows]);

    const Pill = ({ k, label }) => (
      <button onClick={() => setFilter(k)} style={{ padding: "4px 12px", borderRadius: 20, fontSize: 12, fontWeight: 800, cursor: "pointer",
        border: "1px solid " + (filter === k ? NAVY : "var(--op-line,#ddd)"), background: filter === k ? NAVY : "transparent",
        color: filter === k ? "#fff" : "var(--wm-fg-muted)" }}>{label}{counts[k] != null ? " · " + counts[k] : ""}</button>
    );

    const loading = rows === null;

    return (
      <div style={{ padding: "4px 2px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
          <window.Icon name="link" size={20} />
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>Lead Association</h2>
          <span style={{ fontSize: 11, fontWeight: 700, color: NAVY, background: "var(--op-blue-50,#EAF0FB)", padding: "3px 9px", borderRadius: 9 }}>atribución lead-first · handoff a Zoho</span>
          <div style={{ marginLeft: "auto", display: "flex", gap: 6, flexWrap: "wrap" }}>
            <Pill k="all" label={es ? "Todas" : "All"} /><Pill k="proposed" label={es ? "Propuestas" : "Proposed"} />
            <Pill k="approved" label={es ? "Aprobadas" : "Approved"} /><Pill k="rejected" label={es ? "Rechazadas" : "Rejected"} />
          </div>
        </div>
        <div style={{ fontSize: 12, color: "var(--wm-fg-muted)", margin: "6px 0 14px" }}>
          {es ? "El command center NO escribe a Zoho. Te trae el lead + los links (lead y deal) para que TÚ hagas la asociación en Zoho CRM — así queda linkeada a tu usuario. Abre los links, asocia, y marca \"Hecho\"."
              : "The command center does NOT write to Zoho. It brings you the lead + links (lead & deal) so YOU make the association in Zoho CRM — so it's tied to your user. Open the links, associate, mark \"Done\"."}
        </div>

        {/* 🚨 Leads tuyos sin atribuir / robados — atribución lead-first (la prioridad de Miguel) */}
        {stolen && stolen.length > 0 && (
          <div style={{ marginBottom: 22 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, margin: "4px 0 4px" }}>
              <window.Icon name="alert-triangle" size={18} />
              <h3 style={{ margin: 0, fontSize: 15, fontWeight: 800 }}>{es ? "Leads tuyos sin atribuir" : "Your leads, unattributed"}</h3>
              <span style={{ fontSize: 11, fontWeight: 800, color: AMBER, background: "var(--op-amber-50,#FCF1DE)", padding: "3px 9px", borderRadius: 9 }}>{stolen.length} {es ? "por reclamar" : "to reclaim"}</span>
            </div>
            <div style={{ fontSize: 12, color: "var(--wm-fg-muted)", marginBottom: 10 }}>
              {es ? "Ventas cerradas SIN lead source que matchean (email/teléfono) a un lead tuyo de Meta/Google. El lead ES tuyo — corrige el source o asócialo en Zoho con tu usuario."
                  : "Won sales with NO lead source that match (email/phone) a Meta/Google lead of yours. The lead IS yours — fix the source / associate it in Zoho with your user."}
            </div>
            {summary && (Object.keys(summary).length > 0) && (
              <div style={{ display: "flex", gap: 12, marginBottom: 12, flexWrap: "wrap" }}>
                {["meta", "google"].map(c => summary[c] ? (
                  <div key={c} style={{ flex: "1 1 200px", background: "var(--op-amber-50,#FCF1DE)", border: "1px solid " + AMBER, borderRadius: 12, padding: "10px 14px" }}>
                    <div style={{ fontSize: 10, fontWeight: 800, color: "#7a4a00", textTransform: "uppercase", letterSpacing: ".4px" }}>{es ? "CM potencial sin atribuir" : "Uncaptured CM"} · {c === "meta" ? "Meta" : "Google"}</div>
                    <div style={{ fontSize: 22, fontWeight: 900, color: "#b56a00" }}>{window.fmt.money(Number(summary[c].cm_est || 0), { compact: true })}</div>
                    <div style={{ fontSize: 11, color: "#7a4a00" }}>{summary[c].leads} {es ? "ventas tuyas sin crédito (~18m, est. blended)" : "of your wins uncredited (~18m, blended est.)"}</div>
                  </div>
                ) : null)}
              </div>
            )}
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 12 }}>
              {stolen.slice(0, 30).map((s, i) => {
                const ch = s.digital_channel === "meta" ? { l: "Meta", c: "#1877F2" } : { l: "Google", c: "#EA4335" };
                return (
                  <div key={i} style={{ background: "var(--op-card,#fff)", border: "1px solid var(--op-line)", borderRadius: 14, padding: 14, borderLeft: "3px solid " + AMBER, display: "flex", flexDirection: "column", gap: 8 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
                      <div style={{ fontWeight: 800, fontSize: 14 }}>{s.name || "(sin nombre)"}</div>
                      <span style={{ fontSize: 10, fontWeight: 800, color: ch.c, background: "rgba(0,0,0,0.045)", padding: "2px 8px", borderRadius: 8 }}>{ch.l}</span>
                    </div>
                    <div style={{ fontSize: 11, color: "var(--wm-fg-muted)", lineHeight: 1.5 }}>
                      <div>{es ? "Match por" : "Matched on"}: <b style={{ color: "var(--wm-fg,#13203f)" }}>{s.matched_on}</b></div>
                      {s.digital_source && <div>{es ? "Source del lead" : "Lead source"}: <b style={{ color: "var(--wm-fg,#13203f)" }}>{s.digital_source}</b></div>}
                      {s.digital_campaign && <div>{es ? "Campaña" : "Campaign"}: {s.digital_campaign}</div>}
                    </div>
                    <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: "auto", borderTop: "1px solid var(--op-line)", paddingTop: 10 }}>
                      <a href={zohoLeadUrl(s.won_zoho_id) || "#"} target="_blank" rel="noopener noreferrer" title={es ? "El lead 'won' SIN source (el registro a corregir)" : "The no-source 'won' lead record (the one to fix)"} style={{ padding: "5px 10px", borderRadius: 8, border: "1px solid " + NAVY, color: NAVY, fontWeight: 700, fontSize: 11, textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 4 }}><window.Icon name="external-link" size={11} /> {es ? "Lead sin source" : "No-source lead"}</a>
                      <a href={zohoLeadUrl(s.digital_zoho_id) || "#"} target="_blank" rel="noopener noreferrer" style={{ padding: "5px 10px", borderRadius: 8, border: "1px solid " + ch.c, color: ch.c, fontWeight: 700, fontSize: 11, textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 4 }}><window.Icon name="external-link" size={11} /> {es ? "Lead digital" : "Digital lead"}</a>
                      <button disabled={busy === s.won_zoho_id} onClick={() => resolveStolen(s.won_zoho_id)} title={es ? "Ya lo corregí/asocié en Zoho — loguear y no volver a sugerir" : "Fixed/associated in Zoho — log & stop suggesting"} style={{ marginLeft: "auto", padding: "5px 10px", borderRadius: 8, border: "1px solid " + GREEN, background: GREEN, color: "#fff", fontWeight: 800, fontSize: 11, cursor: "pointer", opacity: busy === s.won_zoho_id ? 0.6 : 1 }}>{es ? "✓ Resuelto" : "✓ Resolved"}</button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {loading && <div style={{ color: "var(--wm-fg-muted)", padding: 24 }}>{es ? "Cargando…" : "Loading…"}</div>}
        {!loading && !list.length && (
          <div style={{ border: "1px dashed var(--op-line)", borderRadius: 12, padding: 24, color: "var(--wm-fg-muted)", fontSize: 13, textAlign: "center" }}>
            {es ? "Sin propuestas en esta vista. El lead-actuator corre a diario sobre las decisiones nuevas." : "Nothing here yet. The actuator runs daily on new decisions."}
          </div>
        )}

        {/* Project cards */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14 }}>
          {list.map((r, i) => {
            const a = actionOf(r.action_type);
            const st = STATUS[r.status] || STATUS.proposed;
            const sug = r.payload && r.payload.suggest;
            const isAssoc = r.action_type === "associate_zoho";
            const pl = r.payload || {};
            const subtitle = isAssoc ? ((pl.lead_name || "lead") + " → " + String(pl.deal_name || "deal").slice(0, 30))
              : (r.target_campaign || pl.audience || "—");
            return (
              <div key={i} style={{ background: "var(--op-card,#fff)", border: "1px solid var(--op-line,#e7ebf3)", borderRadius: 14, padding: 16, display: "flex", flexDirection: "column", gap: 10, borderTop: "3px solid " + a.color }}>
                <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 8 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                    <span style={{ width: 34, height: 34, borderRadius: 9, background: "var(--wm-bg-muted,#f4f6fb)", display: "grid", placeItems: "center", color: a.color, flexShrink: 0 }}><window.Icon name={a.icon} size={17} /></span>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 800, fontSize: 14, lineHeight: 1.2 }}>{a.label}</div>
                      <div style={{ fontSize: 11, color: "var(--wm-fg-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{subtitle}</div>
                    </div>
                  </div>
                  <span style={{ fontSize: 11, fontWeight: 800, padding: "3px 9px", borderRadius: 9, background: st.bg, color: st.color, whiteSpace: "nowrap" }}>{st.label}</span>
                </div>

                {isAssoc ? (
                  <>
                    {/* CARNE: datos accionables del deal/lead */}
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                      <div style={{ background: "var(--wm-bg-muted,#f7f9fc)", borderRadius: 9, padding: "8px 10px" }}>
                        <div style={{ fontSize: 10, color: "var(--wm-fg-muted)", textTransform: "uppercase", letterSpacing: ".4px" }}>{es ? "Monto del deal" : "Deal amount"}</div>
                        <div style={{ fontSize: 18, fontWeight: 900, color: "var(--wm-fg,#13203f)" }}>{pl.amount ? window.fmt.money(Number(pl.amount), { compact: true }) : "—"}</div>
                      </div>
                      <div style={{ background: "var(--wm-bg-muted,#f7f9fc)", borderRadius: 9, padding: "8px 10px" }}>
                        <div style={{ fontSize: 10, color: "var(--wm-fg-muted)", textTransform: "uppercase", letterSpacing: ".4px" }}>{es ? "Etapa" : "Stage"}</div>
                        <div style={{ fontSize: 13, fontWeight: 800, color: a.color, lineHeight: 1.2, marginTop: 3 }}>{pl.stage || "—"}</div>
                      </div>
                    </div>
                    <div style={{ display: "flex", gap: 6, flexWrap: "wrap", alignItems: "center", fontSize: 11 }}>
                      {pl.product && <span style={{ background: "rgba(29,66,155,0.08)", color: NAVY, padding: "2px 8px", borderRadius: 8, fontWeight: 700 }}>{pl.product}</span>}
                      {pl.lead_created && <span style={{ color: "var(--wm-fg-muted)" }}>{es ? "lead" : "lead"} {String(pl.lead_created).slice(5)}</span>}
                      {pl.deal_created && <span style={{ color: "var(--wm-fg-muted)" }}>· {es ? "deal" : "deal"} {String(pl.deal_created).slice(5)}</span>}
                    </div>
                  </>
                ) : (
                  <>
                    <div style={{ display: "flex", gap: 18, fontSize: 12, color: "var(--wm-fg-muted)" }}>
                      {r.affected_leads != null && <span>{es ? "Leads afectados" : "Affected leads"} <b style={{ color: "var(--wm-fg,#13203f)" }}>{r.affected_leads}</b></span>}
                      {r.decision_verdict && <span>{es ? "Veredicto CC" : "CC verdict"} <b style={{ color: a.color }}>{r.decision_verdict}</b></span>}
                    </div>
                    {sug && <div style={{ fontSize: 12, background: "var(--wm-bg-muted,#f7f9fc)", borderRadius: 9, padding: "8px 10px", lineHeight: 1.4 }}><b>{es ? "Sugerencia:" : "Suggestion:"}</b> {sug}</div>}
                    {r.rationale && <div style={{ fontSize: 11, color: "var(--wm-fg-muted)", lineHeight: 1.4 }}><b>{es ? "Razón (CC):" : "Why (CC):"}</b> {r.rationale}</div>}
                  </>
                )}

                <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: "auto", borderTop: "1px solid var(--op-line)", paddingTop: 10, flexWrap: "wrap" }}>
                  {isAssoc ? (
                    <>
                      <a href={pl.lead_url || "#"} target="_blank" rel="noopener noreferrer" style={{ padding: "5px 10px", borderRadius: 8, border: "1px solid " + NAVY, color: NAVY, fontWeight: 700, fontSize: 11, textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 4, pointerEvents: pl.lead_url ? "auto" : "none", opacity: pl.lead_url ? 1 : 0.4 }}><window.Icon name="external-link" size={11} /> {es ? "Abrir lead" : "Open lead"}</a>
                      <a href={pl.deal_url || "#"} target="_blank" rel="noopener noreferrer" style={{ padding: "5px 10px", borderRadius: 8, border: "1px solid " + NAVY, color: NAVY, fontWeight: 700, fontSize: 11, textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 4, pointerEvents: pl.deal_url ? "auto" : "none", opacity: pl.deal_url ? 1 : 0.4 }}><window.Icon name="external-link" size={11} /> {es ? "Abrir deal" : "Open deal"}</a>
                      <span style={{ marginLeft: "auto" }} />
                      {r.status !== "done" ? (
                        <button disabled={busy === r.id} onClick={() => decide(r.id, "done")} title={es ? "Marca que ya lo asociaste en Zoho (tu usuario queda linkeado)" : "Mark as associated in Zoho"} style={{ padding: "5px 12px", borderRadius: 8, border: "1px solid " + GREEN, background: GREEN, color: "#fff", fontWeight: 800, fontSize: 11, cursor: "pointer", opacity: busy === r.id ? 0.6 : 1 }}>{es ? "✓ Hecho" : "✓ Done"}</button>
                      ) : (
                        <span style={{ fontSize: 11, fontWeight: 700, color: GREEN }}>✓ {es ? "asociado" : "associated"} · {r.decided_by || ""}</span>
                      )}
                    </>
                  ) : (<>
                    <span style={{ fontSize: 10.5, color: "var(--wm-fg-subtle,#9aa)", marginRight: "auto" }}>{r.action_label || (es ? "decisión del CC" : "CC decision")}</span>
                    {r.status === "proposed" ? (
                      <>
                        <button disabled={busy === r.id} onClick={() => decide(r.id, "approved")} style={{ padding: "5px 12px", borderRadius: 8, border: "1px solid " + GREEN, background: GREEN, color: "#fff", fontWeight: 800, fontSize: 11, cursor: "pointer", opacity: busy === r.id ? 0.6 : 1 }}>{es ? "Aprobar" : "Approve"}</button>
                        <button disabled={busy === r.id} onClick={() => decide(r.id, "rejected")} style={{ padding: "5px 12px", borderRadius: 8, border: "1px solid var(--op-line)", background: "transparent", color: RED, fontWeight: 700, fontSize: 11, cursor: "pointer" }}>{es ? "Rechazar" : "Reject"}</button>
                      </>
                    ) : (
                      <span style={{ fontSize: 11, color: "var(--wm-fg-muted)" }}>{r.decided_by || "—"}</span>
                    )}
                  </>)}
                </div>
              </div>
            );
          })}
        </div>

        {toast && <div style={{ position: "fixed", bottom: 22, left: "50%", transform: "translateX(-50%)", background: toast.k === "ok" ? GREEN : RED, color: "#fff", padding: "9px 18px", borderRadius: 10, fontWeight: 700, fontSize: 13, zIndex: 9999 }}>{toast.m}</div>}

        <div style={{ fontSize: 10.5, color: "var(--wm-fg-muted)", marginTop: 16, lineHeight: 1.5 }}>
          {es ? "Fuente: windmar-marketing · marketing.lead_actions (cola propose-only del lead-actuator) + marketing.cro_decisions. También en el RAG (knowledge_docs). Sin ejecución a Zoho."
              : "Source: windmar-marketing · lead_actions queue + cro_decisions. Also in the RAG. No Zoho execution."}
        </div>
      </div>
    );
  }

  window.ExecutionsView = ExecutionsView;
})();
