// Compliance Glossary — hoverable terms with definitions, plus a dedicated
// reference surface. Subtle dotted underline; popover on hover/focus.

const GLOSSARY = {
  KYC: {
    title: "KYC",
    full: "Know Your Customer",
    body: "Identity verification for individuals — passport / national ID, address proof, selfie liveness.",
    cite: "SCB-DARE §12",
  },
  KYB: {
    title: "KYB",
    full: "Know Your Business",
    body: "Identity verification for organizations — certificate of incorporation, register of members, UBO chart, source of funds.",
    cite: "SCB-DARE §13",
  },
  UBO: {
    title: "UBO",
    full: "Ultimate Beneficial Owner",
    body: "The natural person(s) who ultimately own or control an organization. ≥10% direct or indirect ownership requires identification.",
    cite: "FATF Rec. 24",
  },
  EDD: {
    title: "EDD",
    full: "Enhanced Due Diligence",
    body: "Deeper scrutiny applied to high-risk customers or large transactions: documented Source of Funds, Source of Wealth, and named-officer attestation.",
    cite: "SCB-DARE §15.2",
  },
  PEP: {
    title: "PEP",
    full: "Politically Exposed Person",
    body: "A person holding (or close to someone holding) a prominent public function. Elevated risk for bribery/corruption exposure; EDD is mandatory.",
    cite: "FATF Rec. 12",
  },
  SoF: {
    title: "SoF",
    full: "Source of Funds",
    body: "Origin of the specific money for this transaction (salary, asset sale, business income).",
  },
  SoW: {
    title: "SoW",
    full: "Source of Wealth",
    body: "Origin of the customer's overall wealth, not just the current transaction. Relevant for high-net-worth onboarding.",
  },
  KYT: {
    title: "KYT",
    full: "Know Your Transaction",
    body: "On-chain monitoring for risk: sanctioned addresses, mixers, high-risk counterparties. Pulled from Chainalysis-equivalent providers.",
  },
  AML: {
    title: "AML",
    full: "Anti-Money Laundering",
    body: "Umbrella framework — KYC, screening, transaction monitoring, reporting — designed to prevent the financial system from being used to launder illicit funds.",
  },
  SLA: {
    title: "SLA",
    full: "Service Level Agreement",
    body: "Internal target for how long a review should take. Rows tint amber after 7 days, red after 30.",
  },
  p95: {
    title: "p95",
    full: "95th percentile",
    body: "Statistical measure — 95% of reviews complete within this duration. Less sensitive to outliers than an average.",
  },
  SCB: {
    title: "SCB",
    full: "Securities Commission of The Bahamas",
    body: "Agio's prudential regulator. Read-only audit views are built for SCB filings and on-site examinations.",
  },
  DARE: {
    title: "DARE",
    full: "Digital Assets and Registered Exchanges Act",
    body: "Bahamas legislation governing digital-asset businesses. Agio is pursuing a DARE license; many controls in this dashboard map to specific DARE clauses.",
  },
  CIMA: {
    title: "CIMA",
    full: "Cayman Islands Monetary Authority",
    body: "Cayman regulator. Drives the −6mo re-KYC cadence override for high-tier Cayman entities.",
  },
  "BVI FSC": {
    title: "BVI FSC",
    full: "British Virgin Islands Financial Services Commission",
    body: "BVI regulator. Quarterly attestation requirement is why the BVI cadence override is set to −6 months.",
  },
  CRS: {
    title: "CRS",
    full: "Common Reporting Standard",
    body: "OECD standard for the automatic exchange of tax-residency information between participating jurisdictions.",
  },
  FATCA: {
    title: "FATCA",
    full: "Foreign Account Tax Compliance Act",
    body: "US law requiring foreign financial institutions to report on US-person account holders.",
  },
  Sanctions: {
    title: "Sanctions screening",
    body: "Continuous check of applicants against OFAC SDN, UN Consolidated, EU, and OFSI consolidated lists. Refreshed on every applicant change and every list update.",
  },
  Attestation: {
    title: "Attestation",
    body: "A signed statement by a named officer that they performed the required review (e.g. EDD attestation on a >$25,000 withdrawal). Auditable and non-repudiable.",
  },
  "Audit trail": {
    title: "Audit trail",
    body: "Append-only log of every compliance action. The Merkle root in the footer is cryptographic proof that no row has been altered after the fact.",
  },
  Mutation: {
    title: "Value-bearing mutation",
    body: "Any system action that moves money or alters a position — transfers, withdrawals, subscriptions, redemptions. Each must traverse a verified KYC gate.",
  },
  Tier: {
    title: "Risk tier",
    body: "Categorization driving how an applicant or transaction is handled. KYC tier (1–3) reflects verification depth; withdrawal tier (Low/Med/High) is set by USD amount.",
  },
  "Risk score": {
    title: "Composite risk score",
    body: "0–100 weighted score from country risk + PEP exposure + SoF clarity + transaction patterns + document quality + behaviour signals.",
  },
  Watchlist: {
    title: "Watchlist",
    body: "Any sanctions, PEP, or adverse-media list being screened against. OFAC, UN, EU, OFSI, and provider-curated PEP lists are included.",
  },
  "Adverse media": {
    title: "Adverse media",
    body: "Negative news tied to the applicant — fraud, regulatory action, criminal proceedings. Hits are reviewed; provenance and recency drive disposition.",
  },
  "Risk declaration": {
    title: "Risk declaration",
    body: "Self-attested questionnaire covering PEP status, sanctions exposure, source of wealth, and a regulatory attestation. Validity expires per the Re-KYC cadence policy.",
  },
};

// ── <Term> — wraps text with dotted underline + hover popover ───────────
function Term({ id, children }) {
  const def = GLOSSARY[id];
  const [coords, setCoords] = React.useState(null); // {x, y, flip}
  const ref = React.useRef(null);

  const onEnter = () => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    const flipY = rect.bottom + 220 > window.innerHeight;
    const flipX = rect.left + 320 > window.innerWidth;
    setCoords({
      x: flipX ? rect.right - 320 : rect.left,
      y: flipY ? rect.top - 8 : rect.bottom + 6,
      flipY,
    });
  };
  const onLeave = () => setCoords(null);

  if (!def) return <span>{children}</span>;
  return (
    <>
      <span ref={ref} className="term"
        tabIndex={0}
        onMouseEnter={onEnter} onMouseLeave={onLeave}
        onFocus={onEnter}      onBlur={onLeave}>
        {children}
      </span>
      {coords && ReactDOM.createPortal(
        <div className="term-tip" style={{
          left: coords.x, top: coords.y,
          transform: coords.flipY ? "translateY(-100%)" : "none",
        }}>
          <div className="term-tip-hd">
            <span className="term-tip-title">{def.title}</span>
            {def.full && <span className="term-tip-full">{def.full}</span>}
          </div>
          <div className="term-tip-body">{def.body}</div>
          {def.cite && <div className="term-tip-cite">{def.cite}</div>}
        </div>,
        document.body
      )}
    </>
  );
}

// ── Glossary surface — full reference table ───────────────────────────
function GlossarySurface() {
  const [q, setQ] = React.useState("");
  const entries = Object.entries(GLOSSARY).filter(([id, def]) => {
    if (!q.trim()) return true;
    const ql = q.toLowerCase();
    return id.toLowerCase().includes(ql)
        || def.title.toLowerCase().includes(ql)
        || (def.full && def.full.toLowerCase().includes(ql))
        || def.body.toLowerCase().includes(ql);
  });

  return (
    <>
      <div className="app-subheader">
        <div className="subheader-title">Compliance Glossary</div>
        <div className="subheader-meta">{entries.length} terms · referenced inline across the dashboard</div>
        <div className="subheader-spacer" />
        <div style={{position:"relative", width:280}}>
          <span style={{position:"absolute", left:8, top:"50%", transform:"translateY(-50%)", color:"var(--fg-4)"}}>
            <ISearch size={12} />
          </span>
          <input value={q} onChange={e => setQ(e.target.value)}
            placeholder="Filter terms…"
            style={{
              width:"100%", height:26, padding:"0 8px 0 26px",
              border:"1px solid var(--line)", background:"var(--bg-elev)",
              borderRadius:6, font:"12px var(--font-sans)", color:"var(--fg)",
              outline:"none",
            }} />
        </div>
      </div>
      <div className="page-scroll">
        <div className="gloss-wrap">
          <div className="gloss-grid">
            {entries.map(([id, def]) => (
              <article key={id} className="gloss-card">
                <header className="gloss-hd">
                  <span className="gloss-title">{def.title}</span>
                  {def.full && <span className="gloss-full">{def.full}</span>}
                </header>
                <p className="gloss-body">{def.body}</p>
                {def.cite && (
                  <div className="gloss-cite">
                    <ILock size={11} />
                    <span className="mono">{def.cite}</span>
                  </div>
                )}
              </article>
            ))}
            {entries.length === 0 && (
              <div style={{gridColumn:"1/-1"}}>
                <Empty title="No terms match" hint={`Nothing matched "${q}". Try a shorter search.`} />
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { Term, GLOSSARY, GlossarySurface });
