// dashboard.jsx — table, filters, regional matrix, parties card

const { Badge, ConfBar, FlagSet, OUTCOME_ORDER, OUTCOME_LABELS, needsAttention } = window.MC_HELPERS;
const { useState: dbUseState, useMemo: dbUseMemo } = React;

function StatsStrip({ counts, total, attnCount }) {
  return (
    <div className="stats">
      <div className="stat required">
        <span className="swatch"></span>
        <div className="label">Required</div>
        <div className="value">{counts.required}</div>
        <div className="sub">filings to prepare</div>
      </div>
      <div className="stat borderline">
        <span className="swatch"></span>
        <div className="label">Borderline</div>
        <div className="value">{counts.borderline}</div>
        <div className="sub">judgement call</div>
      </div>
      <div className="stat info">
        <span className="swatch"></span>
        <div className="label">Info needed</div>
        <div className="value">{counts.info_needed}</div>
        <div className="sub">data to gather</div>
      </div>
      <div className="stat notreq">
        <span className="swatch"></span>
        <div className="label">Not required</div>
        <div className="value">{counts.not_required}</div>
        <div className="sub">cleared</div>
      </div>
      <div className="stat attn">
        <span className="swatch"></span>
        <div className="label">Needs attention</div>
        <div className="value">{attnCount}</div>
        <div className="sub">of {total} total</div>
      </div>
    </div>
  );
}

function PartiesCard({ matter }) {
  return (
    <div className="card parties-card">
      <div className="card-hd">Deal parties</div>
      {matter.parties.map((p, i) => (
        <div key={i} className="row">
          <div className="role">{p.role}</div>
          <div className="name">{p.name}</div>
          <div className="nums">
            <div>WW {p.worldwide}</div>
            {p.eu && <div style={{ color: "var(--fg-faint)" }}>EU {p.eu}</div>}
          </div>
        </div>
      ))}
      <div className="combined">
        <span>Combined worldwide</span>
        <span className="v">{matter.combinedWorldwide}</span>
      </div>
      <div className="combined" style={{ borderTop: "1px dashed var(--border)", color: "var(--fg-muted)", fontWeight: 400 }}>
        <span>FX convention</span>
        <span style={{ fontFamily: "var(--font-ui)", fontSize: "var(--text-xs)" }}>{matter.fxYear}</span>
      </div>
    </div>
  );
}

function Filters({ filters, setFilters, counts, total, shown }) {
  const toggleOutcome = (o) => {
    const cur = filters.outcomes;
    setFilters({ ...filters, outcomes: cur.includes(o) ? cur.filter(x => x !== o) : [...cur, o] });
  };
  const allOutcomes = ["required", "borderline", "info_needed", "not_required", "excluded"];
  const hasActiveFilters = filters.outcomes.length > 0 || filters.attnOnly || filters.overOnly || filters.search.trim();
  const clearAll = () => setFilters({ search: "", outcomes: [], attnOnly: false, overOnly: false });
  return (
    <div className="filters">
      <div className="search">
        <input
          type="text"
          placeholder="Search jurisdiction…"
          value={filters.search}
          onChange={(e) => setFilters({ ...filters, search: e.target.value })}
        />
      </div>
      <div className="chips">
        {allOutcomes.map((o) => (
          <button
            key={o}
            className={`chip ${o} ${filters.outcomes.includes(o) ? "active" : ""}`}
            onClick={() => toggleOutcome(o)}
          >
            <span className="dot" />
            {OUTCOME_LABELS[o]} <span style={{ opacity: 0.6 }}>{counts[o] || 0}</span>
          </button>
        ))}
      </div>
      <label className="toggle">
        <input
          type="checkbox"
          checked={filters.attnOnly}
          onChange={(e) => setFilters({ ...filters, attnOnly: e.target.checked })}
        />
        Needs attention only
      </label>
      <label className="toggle">
        <input
          type="checkbox"
          checked={filters.overOnly}
          onChange={(e) => setFilters({ ...filters, overOnly: e.target.checked })}
        />
        Overridden only
      </label>
      {hasActiveFilters && (
        <button className="clear-btn" onClick={clearAll}>Clear filters</button>
      )}
      <div className="right">
        <span>{shown} of {total}</span>
      </div>
    </div>
  );
}

function JurisdictionTable({ rows, sort, setSort, selectedIso, onSelect, screenedOutCount, onClearFilters }) {
  const headers = [
    { key: "iso",        label: "ISO",       cls: "col-iso" },
    { key: "name",       label: "Jurisdiction", cls: "col-name" },
    { key: "region",     label: "Region",    cls: "col-region" },
    { key: "outcome",    label: "Outcome",   cls: "col-outcome" },
    { key: "toolOutcome",label: "AI view",   cls: "col-tool", hint: "What the AI assessment said before any lawyer override" },
    { key: "confidence", label: "Conf.",     cls: "col-conf" },
    { key: "flags",      label: "Flags",     cls: "col-flags" },
  ];
  const setSortKey = (k) => {
    if (sort.key === k) setSort({ key: k, dir: sort.dir === "asc" ? "desc" : "asc" });
    else setSort({ key: k, dir: "asc" });
  };
  return (
    <div className="card">
      <div className="card-hd">
        Jurisdiction assessment
        <div className="right">
          <span style={{ color: "var(--fg-faint)", fontWeight: 400, fontFamily: "var(--font-ui)", fontSize: "var(--text-xs)", textTransform: "none", letterSpacing: 0 }}>
            sortable · click row to inspect
          </span>
        </div>
      </div>
      {rows.length === 0 ? (
        <div className="empty-state">
          <div className="title">No jurisdictions match these filters</div>
          <div className="hint">Try removing one of the active filters to see results.</div>
          {onClearFilters && <button className="btn" onClick={onClearFilters}>Clear all filters</button>}
        </div>
      ) : (
        <div className="table-wrap">
          <table className="j-table">
            <thead>
              <tr>
                {headers.map((h) => (
                  <th key={h.key} className={`${h.cls} ${sort.key === h.key ? "sorted" : ""}`}
                      title={h.hint || undefined} onClick={() => setSortKey(h.key)}>
                    {h.label}
                    <span className="sort">{sort.key === h.key ? (sort.dir === "asc" ? "▲" : "▼") : "↕"}</span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map((r) => {
                const eff = r.lawyerOutcome || r.outcome;
                return (
                  <tr
                    key={r.iso + r.name}
                    className={selectedIso === r.iso ? "selected" : ""}
                    onClick={() => onSelect(r.iso)}
                  >
                    <td className="col-iso">{r.iso}</td>
                    <td className="col-name">{r.name}{(r.iso === "EU" || r.iso === "COMESA" || r.iso === "CEMAC") && <span style={{ color: "var(--fg-faint)", fontSize: "var(--text-xs)", fontWeight: 400, marginLeft: 6, fontFamily: "var(--font-ui)" }}>supranational</span>}</td>
                    <td className="col-region">{regionShort(r.region)}</td>
                    <td className="col-outcome"><Badge outcome={eff} /></td>
                    <td className="col-tool">{r.toolOutcome === eff ? "—" : window.MC_HELPERS.OUTCOME_LABELS[r.toolOutcome]}</td>
                    <td className="col-conf"><ConfBar confidence={r.confidence} /></td>
                    <td className="col-flags"><FlagSet rec={r} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
      {screenedOutCount > 0 && rows.length > 0 && (
        <div className="excluded-rollup">
          <span>+ <b>{screenedOutCount}</b> jurisdictions deterministically screened out before LLM evaluation (below conservative turnover floor or no local nexus).</span>
        </div>
      )}
    </div>
  );
}

function regionShort(r) {
  return {
    eu: "European Union",
    eea: "Europe (non-EU)",
    americas: "Americas",
    apac: "Asia-Pacific",
    mea: "Middle East & Africa",
  }[r] || r;
}

// Regional matrix "map" — secondary visualization
function RegionalMatrix({ rows, regions, selectedIso, onSelect }) {
  const byRegion = {};
  rows.forEach((r) => {
    if (!byRegion[r.region]) byRegion[r.region] = [];
    byRegion[r.region].push(r);
  });
  return (
    <div className="card map-card">
      <div className="card-hd">Regional overview</div>
      <div className="grid">
        {regions.map((reg) => {
          const items = byRegion[reg.id] || [];
          if (!items.length) return null;
          // Sort: required/borderline first, then info, notreq, excluded
          const order = { required: 0, borderline: 1, info_needed: 2, not_required: 3, excluded: 4 };
          items.sort((a, b) => order[a.outcome] - order[b.outcome] || a.name.localeCompare(b.name));
          return (
            <div key={reg.id} className="region-row">
              <div className="label">{regionShort(reg.id)}</div>
              <div className="tiles">
                {items.map((r) => {
                  const isSupra = r.iso === "EU" || r.iso === "COMESA" || r.iso === "CEMAC";
                  return (
                    <div
                      key={r.iso + r.name}
                      className={`tile ${r.lawyerOutcome || r.outcome} ${selectedIso === r.iso ? "selected" : ""} ${r.iso.length > 2 ? "wide" : ""} ${isSupra ? "supra" : ""}`}
                      title={`${r.name} — ${OUTCOME_LABELS[r.lawyerOutcome || r.outcome]}`}
                      onClick={() => onSelect(r.iso)}
                    >
                      {r.iso}
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
      <div className="legend">
        <div className="item"><span className="sw required" />Required</div>
        <div className="item"><span className="sw borderline" />Borderline</div>
        <div className="item"><span className="sw info_needed" />Info needed</div>
        <div className="item"><span className="sw not_required" />Not required</div>
        <div className="item"><span className="sw excluded" />Screened out</div>
      </div>
    </div>
  );
}

Object.assign(window, { StatsStrip, PartiesCard, Filters, JurisdictionTable, RegionalMatrix });
