// Alerts queue view — analyst's daily working surface.

const { useState, useMemo, useEffect, useRef } = React;

function formatAmount(n, cur) {
  const sym = { USD: "$", EUR: "€", GBP: "£", MXN: "MX$" }[cur] || "";
  return sym + n.toLocaleString("en-US");
}

function riskColor(score) {
  if (score >= 70) return "var(--risk-high)";
  if (score >= 45) return "var(--risk-med)";
  return "var(--risk-low)";
}
function riskLabel(score) {
  if (score >= 70) return "high";
  if (score >= 45) return "med";
  return "low";
}

function RiskBar({ score }) {
  const c = riskColor(score);
  return (
    <span className="riskbar">
      <span className="riskbar-track">
        <span className="riskbar-fill"
              style={{ width: `${score}%`, background: c }} />
      </span>
      <span style={{ color: c, minWidth: 22 }}>{score}</span>
    </span>
  );
}

function SeverityDot({ s }) {
  const cls = s === "high" ? "dot-high" : s === "med" ? "dot-med" : "dot-low";
  return <span className={`dot ${cls}`} />;
}

function TypeIcon({ subject }) {
  return (
    <span style={{
      display: "inline-grid", placeItems: "center",
      width: 22, height: 22, borderRadius: 4,
      background: "var(--bg-3)", color: "var(--fg-2)",
      marginRight: 2,
    }}>
      {subject === "business"
        ? <Icon.Building size={12} />
        : <Icon.Person size={12} />}
    </span>
  );
}

function FlagPin({ cc }) {
  // Country code chip
  return (
    <span className="mono" style={{
      fontSize: 10, fontWeight: 500,
      color: "var(--fg-3)", letterSpacing: "0.04em",
    }}>{cc}</span>
  );
}

function Tab({ active, label, count, onClick }) {
  return (
    <button className={`tab ${active ? "active" : ""}`} onClick={onClick}>
      <span>{label}</span>
      {count != null && <span className="tab-count">{count}</span>}
    </button>
  );
}

// Dropdown-backed filter chip. `options` is [{ value, label }]; a null-valued
// option represents "Any" / clear. `value` is the currently applied option value.
function FilterMenu({ label, value, options, formatValue, onSelect }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    if (!open) return;
    const onDocClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onDocClick);
    return () => document.removeEventListener("mousedown", onDocClick);
  }, [open]);

  const set = value != null;

  return (
    <div className="filter-menu-wrap" ref={ref}>
      <button className={`filter-chip ${set ? "set" : ""}`} onClick={() => setOpen(o => !o)}>
        <Icon.Plus size={11} />
        <b>{label}</b>
        {set && (<>
          <span className="filter-sep">·</span>
          <span>{formatValue ? formatValue(value) : value}</span>
          <span className="filter-x" onClick={(e) => { e.stopPropagation(); onSelect(null); setOpen(false); }}>
            <Icon.X size={10} />
          </span>
        </>)}
      </button>
      {open && (
        <div className="filter-menu">
          {options.map(opt => (
            <button key={String(opt.value)}
                    className={`filter-menu-item ${value === opt.value ? "active" : ""}`}
                    onClick={() => { onSelect(opt.value); setOpen(false); }}>
              {opt.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

const OPENED_WINDOWS = { "24h": 1, "7d": 7, "30d": 30 };
const AMOUNT_PRESETS = [
  { value: 10000, label: "≥ $10k" },
  { value: 50000, label: "≥ $50k" },
  { value: 100000, label: "≥ $100k" },
  { value: 250000, label: "≥ $250k" },
];
const RISK_PRESETS = [
  { value: 40, label: "≥ 40" },
  { value: 55, label: "≥ 55" },
  { value: 70, label: "≥ 70" },
];

function AlertsView({ onOpenCase, rowStyle = "hairline", data, selectedAlertIds, onSelectionChange }) {
  const alerts = data?.alerts || window.ALERTS || [];
  const selected = selectedAlertIds || new Set();
  const setSelected = onSelectionChange || (() => {});
  const [tab, setTab] = useState("all");
  const [sortBy, setSortBy] = useState("risk");
  const [page, setPage] = useState(1);
  const [filters, setFilters] = useState({
    tenant: null, riskMin: null, opened: null,
    channel: null, geography: null, amountMin: null,
  });
  const pageSize = 50;

  const setTabAndReset = (t) => { setPage(1); setTab(t); };
  const setSortAndReset = (s) => { setPage(1); setSortBy(s); };
  const setFilter = (key, value) => { setPage(1); setFilters(f => ({ ...f, [key]: value })); };

  const counts = useMemo(() => ({
    all: alerts.length,
    critical: alerts.filter(a => a.severity === "critical").length,
    high: alerts.filter(a => a.severity === "high").length,
    medium: alerts.filter(a => a.severity === "med" || a.severity === "medium").length,
    unassigned: alerts.filter(a => a.assignee === "Unassigned").length,
  }), [alerts]);

  const tenantOptions = useMemo(() => (window.TENANTS || []).map(t => ({ value: t.id, label: t.short })), []);
  const channelOptions = useMemo(() => (
    [...new Set(alerts.map(a => a.channel).filter(Boolean))].sort().map(v => ({ value: v, label: v }))
  ), [alerts]);
  const geographyOptions = useMemo(() => {
    const set = new Set();
    alerts.forEach(a => {
      if (a.subjectCountry && a.subjectCountry !== "—") set.add(a.subjectCountry);
      if (a.cpCountry && a.cpCountry !== "—") set.add(a.cpCountry);
    });
    return [...set].sort().map(v => ({ value: v, label: v }));
  }, [alerts]);
  const openedOptions = [
    { value: "24h", label: "Last 24h" },
    { value: "7d", label: "Last 7d" },
    { value: "30d", label: "Last 30d" },
  ];

  const filtered = useMemo(() => {
    let r = alerts;
    if (tab === "critical") r = r.filter(a => a.severity === "critical");
    else if (tab === "high") r = r.filter(a => a.severity === "high");
    else if (tab === "medium") r = r.filter(a => a.severity === "med" || a.severity === "medium");
    else if (tab === "unassigned") r = r.filter(a => a.assignee === "Unassigned");

    if (filters.tenant) r = r.filter(a => tenantForCustomer(a.subject).id === filters.tenant);
    if (filters.riskMin != null) r = r.filter(a => a.risk >= filters.riskMin);
    if (filters.opened) {
      const cutoff = Date.now() - OPENED_WINDOWS[filters.opened] * 24 * 60 * 60 * 1000;
      r = r.filter(a => new Date(a.created_at || a.opened).getTime() >= cutoff);
    }
    if (filters.channel) r = r.filter(a => a.channel === filters.channel);
    if (filters.geography) r = r.filter(a => a.subjectCountry === filters.geography || a.cpCountry === filters.geography);
    if (filters.amountMin != null) r = r.filter(a => a.amount >= filters.amountMin);

    r = [...r].sort((a, b) => sortBy === "risk" ? b.risk - a.risk : new Date(b.created_at || b.opened) - new Date(a.created_at || a.opened));
    return r;
  }, [tab, sortBy, alerts, filters]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const safePage = Math.min(page, totalPages);
  const paged = filtered.slice((safePage - 1) * pageSize, safePage * pageSize);

  const toggle = (id) => {
    const n = new Set(selected); n.has(id) ? n.delete(id) : n.add(id); setSelected(n);
  };
  const toggleAll = () => {
    setSelected(selected.size === paged.length ? new Set() : new Set(paged.map(a => a.id)));
  };

  return (
    <>
      <div className="tabs">
        <Tab label="All open" count={counts.all}  active={tab==="all"}        onClick={() => setTabAndReset("all")} />
        <Tab label="Critical" count={counts.critical} active={tab==="critical"} onClick={() => setTabAndReset("critical")} />
        <Tab label="High"      count={counts.high} active={tab==="high"}      onClick={() => setTabAndReset("high")} />
        <Tab label="Medium"    count={counts.medium} active={tab==="medium"}  onClick={() => setTabAndReset("medium")} />
        <Tab label="Unassigned" count={counts.unassigned} active={tab==="unassigned"} onClick={() => setTabAndReset("unassigned")} />
      </div>

      <div className="filters">
        <FilterMenu label="Tenant" value={filters.tenant} options={tenantOptions}
                    formatValue={v => tenantOptions.find(o => o.value === v)?.label}
                    onSelect={v => setFilter("tenant", v)} />
        <FilterMenu label="Risk" value={filters.riskMin} options={RISK_PRESETS}
                    formatValue={v => RISK_PRESETS.find(o => o.value === v)?.label ?? `≥ ${v}`}
                    onSelect={v => setFilter("riskMin", v)} />
        <FilterMenu label="Opened" value={filters.opened} options={openedOptions}
                    formatValue={v => openedOptions.find(o => o.value === v)?.label.toLowerCase()}
                    onSelect={v => setFilter("opened", v)} />
        <FilterMenu label="Channel" value={filters.channel} options={channelOptions}
                    onSelect={v => setFilter("channel", v)} />
        <FilterMenu label="Geography" value={filters.geography} options={geographyOptions}
                    onSelect={v => setFilter("geography", v)} />
        <FilterMenu label="Amount" value={filters.amountMin} options={AMOUNT_PRESETS}
                    formatValue={v => AMOUNT_PRESETS.find(o => o.value === v)?.label ?? `≥ $${v}`}
                    onSelect={v => setFilter("amountMin", v)} />
        <div style={{ flex: 1 }} />
        <select className="field" value={sortBy} onChange={e => setSortAndReset(e.target.value)} style={{ width: 150 }}>
          <option value="risk">Sort: Risk score</option>
          <option value="opened">Sort: Recently opened</option>
        </select>
      </div>

      {selected.size > 0 && (
        <div className="banner" style={{
          background: "var(--accent-tint)",
          color: "var(--accent)",
          borderBottom: "1px solid var(--border)",
        }}>
          <span><b>{selected.size}</b> selected</span>
          <span style={{ color: "var(--fg-3)" }}>·</span>
          <span style={{ fontSize: 12 }}>Create one case from the {selected.size} selected alert{selected.size === 1 ? "" : "s"}</span>
          <span style={{ flex: 1 }} />
          <button className="btn ghost sm" onClick={() => setSelected(new Set())}>
            <Icon.X size={11} /> Clear selection
          </button>
        </div>
      )}

      <div style={{ flex: 1, overflow: "auto" }}>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 36, paddingRight: 0 }}>
                <input type="checkbox"
                       checked={paged.length > 0 && selected.size === paged.length}
                       onChange={toggleAll}
                       style={{ accentColor: "var(--fg)" }} />
              </th>
              <th style={{ width: 134 }}>Alert</th>
              <th style={{ width: 120 }}>Customer</th>
              <th style={{ width: 110 }}>Tenant</th>
              <th style={{ width: 110 }}>Risk</th>
              <th style={{ width: 130 }}>Rule</th>
              <th>Subject → Counterparty</th>
              <th className="right" style={{ width: 130 }}>Amount</th>
              <th style={{ width: 80 }}>Channel</th>
              <th style={{ width: 110 }}>Assignee</th>
              <th style={{ width: 100 }}>SLA</th>
            </tr>
          </thead>
          <tbody>
            {paged.map(a => (
              <tr key={a.id}
                  className={`${selected.has(a.id) ? "selected" : ""} ${a.flagged ? "flagged" : ""}`}
                  onClick={() => onOpenCase?.(a)}>
                <td style={{ paddingRight: 0 }} onClick={e => e.stopPropagation()}>
                  <input type="checkbox" checked={selected.has(a.id)}
                         onChange={() => toggle(a.id)}
                         style={{ accentColor: "var(--fg)" }} />
                </td>
                <td>
                  <span className="mono" style={{ fontSize: 12, fontWeight: 500 }}>{a.external_id}</span>
                  <div className="mono" style={{ fontSize: 10.5, color: "var(--fg-3)", marginTop: 1 }}>
                    {a.case}
                  </div>
                </td>
                <td>
                  <span className="mono" style={{ color: "var(--accent)", fontWeight: 500, fontSize: 12 }}>{a.customerId || "—"}</span>
                </td>
                <td>
                  <TenantChip tenant={tenantForCustomer(a.subject)} />
                </td>
                <td>
                  <RiskBar score={a.risk} />
                </td>
                <td>
                  <SeverityDot s={a.severity} />
                  <span>{a.rule}</span>
                </td>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                    <TypeIcon subject={a.subjectType} />
                    <div style={{ minWidth: 0, display: "flex", flexDirection: "column", lineHeight: 1.3 }}>
                      <span style={{ fontWeight: 500 }}>
                        {a.subject}
                        <span style={{ color: "var(--fg-3)", marginLeft: 6, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 400 }}>
                          {a.subjectCountry}
                        </span>
                      </span>
                      <span style={{ color: "var(--fg-3)", fontSize: 11.5, display: "flex", alignItems: "center", gap: 5 }}>
                        <Icon.ArrowR size={10} />
                        {a.counterparty}
                        <span className="mono faint" style={{ fontSize: 10.5 }}>{a.cpCountry !== "—" && a.cpCountry}</span>
                      </span>
                    </div>
                  </div>
                </td>
                <td className="right mono" style={{ fontWeight: 500 }}>
                  {formatAmount(a.amount, a.currency)}
                  <span style={{ color: "var(--fg-3)", marginLeft: 4, fontSize: 10.5 }}>{a.currency}</span>
                  {a.txnCount > 1 && (
                    <div className="mono" style={{ fontSize: 10.5, color: "var(--fg-3)", marginTop: 1 }}>
                      {a.txnCount} txns
                    </div>
                  )}
                </td>
                <td>
                  <span className="pill outline">{a.channel}</span>
                </td>
                <td>
                  {a.assignee === "Unassigned" ? (
                    <span className="muted" style={{ fontSize: 12 }}>—</span>
                  ) : a.assignee === "Auto-rules" ? (
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, color: "var(--fg-3)", fontSize: 12 }}>
                      <Icon.Bolt size={11} /> Auto
                    </span>
                  ) : (
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                      <span style={{
                        width: 18, height: 18, borderRadius: "50%",
                        background: "var(--bg-3)",
                        color: "var(--fg-2)",
                        display: "grid", placeItems: "center",
                        fontSize: 9, fontWeight: 600,
                      }}>
                        {a.assignee.split(" ").map(x => x[0]).join("").slice(0,2)}
                      </span>
                      <span style={{ fontSize: 12 }}>{a.assignee.split(" ")[0]}</span>
                    </span>
                  )}
                </td>
                <td>
                  <span className="mono" style={{
                    fontSize: 11.5,
                    color: a.slaWarn ? "var(--risk-high)" : "var(--fg-2)",
                    display: "inline-flex", alignItems: "center", gap: 5,
                  }}>
                    {a.slaWarn && <span className="dot dot-high live-dot" style={{ margin: 0 }} />}
                    {a.sla}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div style={{
        display: "flex", alignItems: "center",
        padding: "8px 18px",
        borderTop: "1px solid var(--border)",
        background: "var(--bg)",
        fontSize: 11.5, color: "var(--fg-3)",
        gap: 8,
      }}>
        <span>Showing <b style={{ color: "var(--fg)" }}>{paged.length}</b> of <b style={{ color: "var(--fg)" }}>{filtered.length}</b> alerts</span>
        <span>·</span>
        <span>Last updated <span className="mono">14s</span> ago</span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <span className="dot dot-low live-dot" style={{ margin: 0 }} /> Live
        </span>
        <span style={{ flex: 1 }} />
        <button className="btn ghost sm" onClick={() => setPage(p => Math.max(1, p - 1))} disabled={safePage <= 1}>
          <Icon.Chevron size={11} style={{ transform: "rotate(180deg)" }} /> Prev
        </button>
        <span>Page <b className="mono" style={{ color: "var(--fg)" }}>{safePage}</b> / <span className="mono">{totalPages}</span></span>
        <button className="btn ghost sm" onClick={() => setPage(p => Math.min(totalPages, p + 1))} disabled={safePage >= totalPages}>
          Next <Icon.Chevron size={11} />
        </button>
      </div>
    </>
  );
}

Object.assign(window, { AlertsView, formatAmount, riskColor, riskLabel, RiskBar });
