/* global React, window */
// =====================================================================
// Drilldown panel: click any metric number → see the exact list of
// people, each linking to their Zoho CRM record.
// =====================================================================

(function () {
  const { useState, useEffect } = React;

  // Zoho CRM lead URL — generic format that works regardless of org slug
  function crmLeadUrl(zohoId) {
    return `https://crm.zoho.com/crm/EntityInfo.do?module=Leads&id=${zohoId}`;
  }

  // ----------- Drilldown state (module-level singleton) -----------
  let modalState = {
    open: false,
    metricKey: null,
    label: "",
    expectedCount: null,
    loading: false,
    rows: [],
    error: null,
  };
  let subs = [];
  const subscribe = (fn) => { subs.push(fn); return () => { subs = subs.filter(s => s !== fn); }; };
  const notify = () => subs.forEach((f) => f(modalState));
  function setState(patch) { modalState = { ...modalState, ...patch }; notify(); }

  // ----------- The open() function (called from anywhere) -----------
  async function openDrilldown(metricKey, label, expectedCount) {
    setState({
      open: true, metricKey, label, expectedCount,
      loading: true, rows: [], error: null,
    });
    try {
      const sb = window.__sb;
      const r = window.__currentRange || {};
      const s = window.__currentScope || {};
      const { data, error } = await sb.rpc("f_drilldown_leads", {
        metric_key: metricKey,
        date_from: r.from,
        date_to: r.to,
        account_ext_ids: s.account_ext_ids || null,
        campaign_regex: s.campaign_regex || null,
      });
      if (error) throw error;
      setState({ loading: false, rows: data || [] });
    } catch (e) {
      console.error("[drilldown]", e);
      setState({ loading: false, error: String(e.message || e) });
    }
  }
  window.openDrilldown = openDrilldown;

  // ----------- Status pill color helper -----------
  const STATUS_COLOR = {
    new: "var(--wm-fg-muted)",
    working: "var(--op-amber)",
    contacted: "var(--op-amber)",
    qualified: "var(--wm-blue)",
    appointment_set: "var(--wm-blue)",
    appointment_held: "#7F9CDF",
    won: "var(--op-green)",
    lost: "var(--op-red)",
    disqualified: "var(--op-red)",
  };

  // ----------- The modal component -----------
  function DrilldownPanel() {
    const [s, setS] = useState(modalState);
    const [filter, setFilter] = useState("");
    useEffect(() => subscribe(setS), []);
    useEffect(() => { if (s.open) setFilter(""); }, [s.open]);
    if (!s.open) return null;

    const filtered = filter.trim()
      ? s.rows.filter((r) => {
          const q = filter.toLowerCase();
          return (
            (r.first_name && r.first_name.toLowerCase().includes(q)) ||
            (r.last_name && r.last_name.toLowerCase().includes(q)) ||
            (r.email && r.email.toLowerCase().includes(q)) ||
            (r.phone && r.phone.includes(q)) ||
            (r.campaign_name && r.campaign_name.toLowerCase().includes(q)) ||
            (r.status_raw && r.status_raw.toLowerCase().includes(q))
          );
        })
      : s.rows;

    return (
      <div className="sheet-overlay" onClick={() => setState({ open: false })}>
        <div className="sheet" onClick={(e) => e.stopPropagation()}>
          <div className="sheet-head">
            <div>
              <div style={{ fontSize: 11, color: "var(--wm-fg-muted)", fontWeight: 800, letterSpacing: "0.08em", textTransform: "uppercase" }}>
                Drilldown
              </div>
              <div style={{ fontSize: 18, fontWeight: 900, color: "var(--wm-blue)", marginTop: 2 }}>
                {s.label}
                {s.expectedCount != null && (
                  <span style={{ marginLeft: 8, fontSize: 13, color: "var(--wm-fg-muted)", fontWeight: 600 }}>
                    {s.rows.length} {s.expectedCount !== s.rows.length && !s.loading && (
                      <span style={{ color: "var(--op-red)" }}>(esperaba {s.expectedCount})</span>
                    )}
                  </span>
                )}
              </div>
            </div>
            <button className="icon-btn" onClick={() => setState({ open: false })}>
              <window.Icon name="x" size={16} />
            </button>
          </div>

          <div style={{ padding: "12px 20px", borderBottom: "1px solid var(--op-chrome-line)" }}>
            <input
              type="text"
              placeholder="Buscar nombre, email, phone, campaña, status…"
              value={filter}
              onChange={(e) => setFilter(e.target.value)}
              style={{
                width: "100%", padding: "8px 12px",
                border: "1px solid var(--op-line-strong)", borderRadius: 8,
                fontSize: 13, fontFamily: "var(--wm-font-sans)",
              }}
            />
          </div>

          <div className="sheet-body" style={{ padding: 0 }}>
            {s.loading && (
              <div className="empty" style={{ padding: 40 }}>Cargando…</div>
            )}
            {s.error && (
              <div style={{ padding: 20, color: "var(--op-red)" }}>{s.error}</div>
            )}
            {!s.loading && !s.error && filtered.length === 0 && (
              <div className="empty" style={{ padding: 40 }}>
                {s.rows.length === 0 ? "Sin resultados en este filtro" : "Sin coincidencias para esa búsqueda"}
              </div>
            )}
            {!s.loading && !s.error && filtered.length > 0 && (
              <table className="table" style={{ width: "100%" }}>
                <thead>
                  <tr>
                    <th>Persona</th>
                    <th>Status</th>
                    <th>Source</th>
                    <th>Campaña</th>
                    <th>Creado</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.map((p) => (
                    <tr key={p.zoho_id}>
                      <td>
                        <b style={{ fontSize: 12 }}>
                          {(p.first_name || "") + " " + (p.last_name || "")}
                        </b>
                        <br />
                        <span className="muted" style={{ fontSize: 10 }}>
                          {p.email || "—"}
                          {p.phone && <> · {p.phone}</>}
                        </span>
                      </td>
                      <td>
                        <span
                          className="pill"
                          style={{
                            background: "transparent",
                            border: "1px solid " + (STATUS_COLOR[p.status] || "var(--op-line)"),
                            color: STATUS_COLOR[p.status] || "var(--wm-fg)",
                            fontSize: 10,
                          }}
                        >
                          {p.status_raw || p.status}
                        </span>
                      </td>
                      <td>
                        <span style={{ fontSize: 11 }}>
                          {p.source || <span className="muted">(sin)</span>}
                        </span>
                        {!p.is_strict_digital && p.has_lead_source_digital && (
                          <div style={{ fontSize: 9, color: "var(--op-amber)", fontWeight: 700 }}>⚠ sin UTMs</div>
                        )}
                      </td>
                      <td>
                        <span style={{ fontSize: 11 }}>
                          {p.campaign_name || (p.utm_campaign ? <span className="muted">{p.utm_campaign}</span> : "—")}
                        </span>
                      </td>
                      <td className="num">
                        <span style={{ fontSize: 11 }}>{(p.created_at_zoho || "").slice(0, 10)}</span>
                      </td>
                      <td>
                        <a
                          href={crmLeadUrl(p.zoho_id)}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="btn btn-ghost btn-sm"
                          style={{ textDecoration: "none" }}
                          title="Abrir en Zoho CRM"
                        >
                          Abrir <window.Icon name="external-link" size={11} />
                        </a>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>

          <div className="sheet-foot">
            <span style={{ fontSize: 11, color: "var(--wm-fg-muted)", marginRight: "auto" }}>
              Cada nombre linkea al record en Zoho CRM (pestaña nueva). Estos son los mismos leads que el número del dashboard cuenta.
            </span>
            <button className="btn btn-ghost btn-sm" onClick={() => setState({ open: false })}>Cerrar</button>
          </div>
        </div>
      </div>
    );
  }
  window.DrilldownPanel = DrilldownPanel;
})();
