// Watchlist view — sanctions/PEP screening demo.
//
// Shows what a real screening result would look like: fuzzy match scores, the specific
// sanctions list + legal citation matched, and ownership-based ("50% Rule") matches where
// a business is blocked because a designated individual controls a large enough stake.
// Entities are demo fixtures (see watchlist-data.jsx) — not a live screening feed.

const { useState: useWlState, useMemo: useWlMemo, useEffect: useWlEffect } = React;

const WL_DISPOSITION_KEY = "mossad_watchlist_dispositions_v1";

const WL_STATUS_PILL = { escalated: "high", under_review: "med", cleared: "low" };
const WL_STATUS_LABEL = { escalated: "Escalated", under_review: "Under review", cleared: "Cleared" };

function wlScoreColor(v) {
  return v >= 90 ? "var(--risk-high)"
       : v >= 75 ? "oklch(56% 0.20 35)"
       : v >= 50 ? "var(--risk-med)"
       : "var(--risk-low)";
}

function loadDispositions() {
  try {
    const raw = localStorage.getItem(WL_DISPOSITION_KEY);
    if (raw) return JSON.parse(raw);
  } catch (e) {}
  return {};
}

function saveDispositions(d) {
  try { localStorage.setItem(WL_DISPOSITION_KEY, JSON.stringify(d)); } catch (e) {}
}

function WlMatchFactors({ factors }) {
  const keys = [
    { k: "name", label: "Name" },
    { k: "identity", label: "ID / DOB" },
    { k: "nationality", label: "Nationality" },
    { k: "address", label: "Address" },
  ];
  return (
    <div style={{ display: "flex", gap: 10 }}>
      {keys.map(({ k, label }) => {
        const v = factors[k];
        if (v == null) return null;
        return (
          <div key={k} style={{ flex: 1, minWidth: 0 }}>
            <div style={{ height: 4, background: "var(--bg-3)", borderRadius: 2 }}>
              <div style={{ width: `${v}%`, height: "100%", background: wlScoreColor(v), borderRadius: 2 }} />
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 4 }}>
              <span style={{ fontSize: 10.5, color: "var(--fg-3)" }}>{label}</span>
              <span className="mono" style={{ fontSize: 10.5, color: "var(--fg-2)" }}>{v}%</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function WatchlistDetail({ entity, onBack, disposition, onSetDisposition }) {
  const status = disposition || entity.status;
  const isBusiness = entity.type === "business";
  const relatedParties = isBusiness ? entity.controllingParties : entity.ownership;
  const relatedLabel = isBusiness ? "Controlling parties" : "Entities linked by ownership";

  return (
    <div style={{ padding: 18, overflow: "auto", flex: 1 }}>
      <button className="btn ghost sm" onClick={onBack} style={{ marginBottom: 14 }}>
        <Icon.Chevron size={11} style={{ transform: "rotate(180deg)" }} /> Back to watchlist
      </button>

      <div className="card" style={{ marginBottom: 14 }}>
        <div className="card-body">
          <div style={{ display: "flex", alignItems: "flex-start", gap: 16 }}>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                <h1 style={{ margin: 0, fontSize: 19, fontWeight: 600 }}>{entity.name}</h1>
                <span className={`pill ${isBusiness ? "outline" : "info"}`}>{isBusiness ? "Business" : "Individual"}</span>
                <span className={`pill ${WL_STATUS_PILL[status]}`}>{WL_STATUS_LABEL[status]}</span>
              </div>
              {entity.aliases.length > 0 && (
                <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 6 }}>
                  Also known as: {entity.aliases.join(" · ")}
                </div>
              )}
              <div style={{ fontSize: 12.5, color: "var(--fg-2)", marginTop: 10, lineHeight: 1.6 }}>{entity.notes}</div>
            </div>
            <div style={{ textAlign: "right", flexShrink: 0 }}>
              <div className="kpi-label" style={{ margin: 0 }}>Match score</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 4, justifyContent: "flex-end" }}>
                <span className="mono" style={{ fontSize: 34, fontWeight: 500, color: wlScoreColor(entity.score), lineHeight: 1, letterSpacing: "-0.03em" }}>
                  {entity.score}
                </span>
                <span className="muted" style={{ fontSize: 13 }}>/ 100</span>
              </div>
            </div>
          </div>

          <div style={{ marginTop: 18, paddingTop: 16, borderTop: "1px solid var(--border)" }}>
            <div className="kpi-label" style={{ marginBottom: 10 }}>Match factor breakdown</div>
            <WlMatchFactors factors={entity.matchFactors} />
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
        <div className="card">
          <div className="card-hd"><h3>Identity</h3></div>
          <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 10, fontSize: 12.5 }}>
            {isBusiness ? (
              <>
                <div><span className="kpi-label" style={{ marginBottom: 2 }}>Jurisdiction</span><div>{entity.jurisdiction}</div></div>
                <div><span className="kpi-label" style={{ marginBottom: 2 }}>Incorporated</span><div>{entity.incorporated}</div></div>
              </>
            ) : (
              <>
                <div><span className="kpi-label" style={{ marginBottom: 2 }}>Nationality</span><div>{entity.nationality}</div></div>
                <div><span className="kpi-label" style={{ marginBottom: 2 }}>Date of birth</span><div>{entity.dob}</div></div>
              </>
            )}
            {entity.idNumbers.length > 0 && (
              <div>
                <span className="kpi-label" style={{ marginBottom: 4 }}>Identifiers</span>
                {entity.idNumbers.map((id, i) => (
                  <div key={i} className="mono" style={{ color: "var(--fg-2)" }}>{id.type}: {id.value}</div>
                ))}
              </div>
            )}
            <div><span className="kpi-label" style={{ marginBottom: 2 }}>Risk category</span><div>{entity.riskCategory}</div></div>
          </div>
        </div>

        <div className="card">
          <div className="card-hd"><h3>Sanctions listings</h3></div>
          <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {entity.lists.map((l, i) => (
              <div key={i} style={{ fontSize: 12.5, paddingBottom: i < entity.lists.length - 1 ? 12 : 0, borderBottom: i < entity.lists.length - 1 ? "1px solid var(--border)" : "none" }}>
                <div style={{ fontWeight: 600 }}>{l.authority}</div>
                <div style={{ color: "var(--fg-2)", marginTop: 2 }}>{l.program}</div>
                <div style={{ color: "var(--fg-3)", marginTop: 2, fontSize: 11.5 }}>{l.legalBasis}</div>
                <div className="mono" style={{ color: "var(--fg-3)", marginTop: 4, fontSize: 11 }}>Listed {l.dateListed}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {relatedParties && relatedParties.length > 0 && (
        <div className="card" style={{ marginBottom: 14 }}>
          <div className="card-hd"><h3>{relatedLabel}</h3></div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Entity</th>
                <th>Relationship</th>
                <th className="right">Ownership</th>
                <th>Notes</th>
              </tr>
            </thead>
            <tbody>
              {relatedParties.map((p, i) => (
                <tr key={i}>
                  <td>{p.name}</td>
                  <td>{p.relationship}</td>
                  <td className="right mono">{p.pct}%</td>
                  <td style={{ color: "var(--fg-3)", fontSize: 11.5 }}>
                    {isBusiness && p.pct >= 50 ? "Blocked under OFAC's 50% Rule" : isBusiness ? "Below 50% Rule threshold — discretionary flag" : ""}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <div className="card">
        <div className="card-hd"><h3>Analyst disposition</h3></div>
        <div className="card-body" style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <button className="btn danger sm" onClick={() => onSetDisposition(entity.id, "escalated")}>Escalate to case</button>
          <button className="btn success sm" onClick={() => onSetDisposition(entity.id, "cleared")}>Clear as false positive</button>
          <button className="btn warn sm" onClick={() => onSetDisposition(entity.id, "under_review")}>Mark under review</button>
          {disposition && (
            <button className="btn ghost sm" onClick={() => onSetDisposition(entity.id, null)}>Reset to original</button>
          )}
        </div>
      </div>
    </div>
  );
}

function WatchlistView() {
  const [dispositions, setDispositions] = useWlState(loadDispositions);
  const [selected, setSelected] = useWlState(null);
  const [typeFilter, setTypeFilter] = useWlState("all");
  const [statusFilter, setStatusFilter] = useWlState("all");
  const [query, setQuery] = useWlState("");

  useWlEffect(() => { saveDispositions(dispositions); }, [dispositions]);

  const entities = useWlMemo(() =>
    WATCHLIST_ENTITIES.map(e => ({ ...e, status: dispositions[e.id] || e.status })),
    [dispositions]
  );

  const setDisposition = (id, status) => {
    setDispositions(d => {
      const next = { ...d };
      if (status) next[id] = status; else delete next[id];
      return next;
    });
  };

  const filtered = useWlMemo(() => {
    const q = query.trim().toLowerCase();
    return entities.filter(e => {
      if (typeFilter !== "all" && e.type !== typeFilter) return false;
      if (statusFilter !== "all" && e.status !== statusFilter) return false;
      if (q && !e.name.toLowerCase().includes(q) && !e.aliases.some(a => a.toLowerCase().includes(q))) return false;
      return true;
    });
  }, [entities, typeFilter, statusFilter, query]);

  const stats = useWlMemo(() => ({
    total: entities.length,
    escalated: entities.filter(e => e.status === "escalated").length,
    underReview: entities.filter(e => e.status === "under_review").length,
    cleared: entities.filter(e => e.status === "cleared").length,
  }), [entities]);

  if (selected) {
    const current = entities.find(e => e.id === selected.id) || selected;
    return (
      <WatchlistDetail
        entity={current}
        onBack={() => setSelected(null)}
        disposition={dispositions[current.id]}
        onSetDisposition={(id, status) => { setDisposition(id, status); }}
      />
    );
  }

  return (
    <div style={{ padding: 18, overflow: "auto", flex: 1 }}>
      <div style={{ display: "flex", alignItems: "center", marginBottom: 4, gap: 10 }}>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>Watchlist</h1>
      </div>
      <div style={{ fontSize: 12.5, color: "var(--fg-3)", marginBottom: 16, maxWidth: 780 }}>
        Illustrative sanctions-screening examples — fictional entities matched against real sanctions program citations (OFAC, UN, EU, UK OFSI),
        including ownership-based ("50% Rule") matches where a business is blocked because a designated individual controls a large enough stake.
        Not a live screening feed.
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 16 }}>
        <div className="card" style={{ padding: 18 }}>
          <div className="kpi-label">Monitored entities</div>
          <div className="kpi-value">{stats.total}</div>
        </div>
        <div className="card" style={{ padding: 18 }}>
          <div className="kpi-label">Escalated</div>
          <div className="kpi-value" style={{ color: "var(--risk-high)" }}>{stats.escalated}</div>
        </div>
        <div className="card" style={{ padding: 18 }}>
          <div className="kpi-label">Under review</div>
          <div className="kpi-value" style={{ color: "var(--risk-med)" }}>{stats.underReview}</div>
        </div>
        <div className="card" style={{ padding: 18 }}>
          <div className="kpi-label">Cleared</div>
          <div className="kpi-value" style={{ color: "var(--risk-low)" }}>{stats.cleared}</div>
        </div>
      </div>

      <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 12, flexWrap: "wrap" }}>
        <div className="search" style={{ maxWidth: 280 }}>
          <Icon.Search size={13} className="search-ico" />
          <input placeholder="Search name or alias…" value={query} onChange={e => setQuery(e.target.value)} />
        </div>
        <span style={{ flex: 1 }} />
        {["all", "individual", "business"].map(t => (
          <button key={t} className={`filter-chip ${typeFilter === t ? "set" : ""}`} onClick={() => setTypeFilter(t)} style={{ textTransform: "capitalize" }}>
            {t === "all" ? "All types" : t === "individual" ? "Individuals" : "Businesses"}
          </button>
        ))}
        {["all", "escalated", "under_review", "cleared"].map(s => (
          <button key={s} className={`filter-chip ${statusFilter === s ? "set" : ""}`} onClick={() => setStatusFilter(s)}>
            {s === "all" ? "All statuses" : WL_STATUS_LABEL[s]}
          </button>
        ))}
      </div>

      <div className="card">
        <table className="tbl">
          <thead>
            <tr>
              <th>Entity</th>
              <th>Type</th>
              <th>Matched list</th>
              <th className="right">Score</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(e => (
              <tr key={e.id} onClick={() => setSelected(e)} style={{ cursor: "pointer" }}>
                <td>
                  <div style={{ fontWeight: 500 }}>{e.name}</div>
                  {e.aliases.length > 0 && (
                    <div style={{ fontSize: 11, color: "var(--fg-3)" }}>{e.aliases.join(" · ")}</div>
                  )}
                </td>
                <td>
                  <span className={`pill ${e.type === "business" ? "outline" : "info"}`}>{e.type === "business" ? "Business" : "Individual"}</span>
                </td>
                <td style={{ color: "var(--fg-2)" }}>{e.lists[0]?.authority}</td>
                <td className="right mono" style={{ color: wlScoreColor(e.score), fontWeight: 600 }}>{e.score}</td>
                <td><span className={`pill ${WL_STATUS_PILL[e.status]}`}>{WL_STATUS_LABEL[e.status]}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div style={{ padding: 24, textAlign: "center", color: "var(--fg-3)" }}>No entities match this filter.</div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { WatchlistView });
