const { useState, useEffect } = React;

/* CRM · Account — company dossier, bound to REAL data only (no representative
 * fallback: showing fabricated records on a real entity would defeat the whole
 * provenance premise). Firmographics + contacts from crm_account_dossier;
 * regulatory/federal panel rendered from the real aiciq_org_federal_panel
 * sections (only sections with data appear). Empty states where there's nothing
 * on file. Default org = Skanska (2322887); override via window.__crmAccountOrgId. */

const AV_PALETTE = ["#b45309", "#2563eb", "#15803d", "#7c3aed", "#be185d", "#0891b2"];
const initialsOf = (n) => (n || "?").split(/\s+/).map((p) => p[0]).slice(0, 2).join("").toUpperCase();
const dash = (x) => (x != null && x !== "" ? x : "—");
const fmtMoney = (n) => { n = Number(n) || 0; const a = Math.abs(n); return a >= 1e9 ? "$" + (n / 1e9).toFixed(2) + "B" : a >= 1e6 ? "$" + (n / 1e6).toFixed(1) + "M" : a >= 1e3 ? "$" + (n / 1e3).toFixed(0) + "K" : "$" + n; };

// federal/regulatory section → display meta. Unknown keys get a generic badge.
const FED_META = {
  irs_990:            { badge: "990",  color: "var(--green)",          label: "IRS 990 (nonprofit)",        unit: "filings" },
  capital_raises:     { badge: "SEC",  color: "var(--accent)",         label: "Form D capital raises",      unit: "raises" },
  investment_adviser: { badge: "ADV",  color: "var(--accent)",         label: "Investment adviser (ADV)",   unit: "filings" },
  osha:               { badge: "OSHA", color: "var(--amber)",          label: "OSHA inspections",           unit: "inspections" },
  aircraft:           { badge: "FAA",  color: "var(--src-government)", label: "Aircraft registrations",     unit: "aircraft" },
  ppp_loans:          { badge: "PPP",  color: "var(--src-sba)",        label: "PPP loans",                  unit: "loans" },
  fec_donors:         { badge: "FEC",  color: "var(--src-hedge)",      label: "Employee political donations", unit: "contributions" },
  federal_contracts:  { badge: "FED",  color: "var(--src-fed)",        label: "Federal contracts",          unit: "awards" },
  lobbying:           { badge: "LDA",  color: "var(--src-hedge)",      label: "Lobbying disclosures",       unit: "filings" },
};
function fedSummary(meta, v) {
  if (!v || typeof v !== "object") return null;
  const count = v.count != null ? v.count : (Array.isArray(v) ? v.length : null);
  let total = null;
  for (const k of Object.keys(v)) { if (/total|amount|spend|sum|raised|value/i.test(k) && typeof v[k] === "number") { total = v[k]; break; } }
  const parts = [];
  if (count != null) parts.push(count.toLocaleString() + " " + (meta.unit || "records"));
  if (total != null) parts.push(fmtMoney(total));
  return parts.join(" · ") || null;
}
function federalRows(federal) {
  if (!federal || typeof federal !== "object") return [];
  return Object.keys(federal).map((k) => {
    const v = federal[k]; if (!v) return null;
    const has = (v.count != null && v.count > 0) || (Array.isArray(v) && v.length) || (typeof v === "object" && Object.keys(v).length);
    if (!has) return null;
    const meta = FED_META[k] || { badge: k.slice(0, 4).toUpperCase(), color: "var(--fg-2)", label: k.replace(/_/g, " "), unit: "records" };
    return { key: k, meta, fact: fedSummary(meta, v) || "on file" };
  }).filter(Boolean);
}

function Field({ l, v }) { return <div className="field"><span className="fl">{l}</span><span className="fv">{dash(v)}</span></div>; }

/* Private notes for a watched company or building. Persisted per-user via
 * crm_get_note / crm_save_note (subject_type = 'org' | 'building'). Auto-saves
 * on blur; also offers an explicit Save while there are unsaved edits. */
function NotesCard({ subjectType, subjectId }) {
  const { toast } = React.useContext(window.CrmContext);
  const [note, setNote] = useState("");
  const [loaded, setLoaded] = useState(false);
  const [saving, setSaving] = useState(false);
  const [dirty, setDirty] = useState(false);
  useEffect(() => {
    const c = window.ContactIQ && window.ContactIQ.client;
    if (!c || subjectId == null) { setLoaded(true); return; }
    let alive = true; setLoaded(false); setDirty(false); setNote("");
    c.rpc("crm_get_note", { p_subject_type: subjectType, p_subject_id: String(subjectId) })
      .then(({ data, error }) => { if (alive) { if (!error) setNote(data || ""); setLoaded(true); } })
      .catch(() => { if (alive) setLoaded(true); });
    return () => { alive = false; };
  }, [subjectType, subjectId]);
  const save = () => {
    const c = window.ContactIQ && window.ContactIQ.client;
    if (!c || subjectId == null) { toast("Sign in to save notes"); return; }
    setSaving(true);
    c.rpc("crm_save_note", { p_subject_type: subjectType, p_subject_id: String(subjectId), p_note: note })
      .then(({ error }) => { setSaving(false); if (error) { toast("Couldn't save note"); } else { setDirty(false); toast("Note saved"); } })
      .catch(() => { setSaving(false); toast("Couldn't save note"); });
  };
  const noun = subjectType === "building" ? "building" : "company";
  return (
    <section className="card side-card">
      <div className="card-head"><span className="ch-title">Notes</span><span className="ch-spacer"></span>
        {dirty && <button className="btn btn-sm btn-primary" disabled={saving} onClick={save}>{saving ? "Saving…" : "Save"}</button>}
      </div>
      <div style={{ padding: "12px 14px" }}>
        <textarea value={note}
          placeholder={loaded ? "Add a private note about this " + noun + "…" : "Loading…"}
          disabled={!loaded}
          onChange={(e) => { setNote(e.target.value); setDirty(true); }}
          onBlur={() => { if (dirty) save(); }}
          style={{ width: "100%", minHeight: "92px", resize: "vertical", border: "1px solid var(--border-2)", borderRadius: "8px", padding: "9px 11px", font: "inherit", fontSize: "var(--fs-base)", color: "var(--fg-1)", background: "var(--bg)", boxSizing: "border-box" }}/>
        <div className="src" style={{ marginTop: "6px" }}>private to you · saved automatically</div>
      </div>
    </section>
  );
}
window.CrmNotesCard = NotesCard;

/* Web enrichment — fills/corrects a company's data from the public web, gated
 * by per-user credits. Each click spends 1 credit and runs aiciq-enrich-org
 * (async; we poll the job): it (1) verifies the on-file website and corrects it
 * if wrong, (2) extracts firmographics from verified sources (each re-checked
 * server-side), and (3) finds real company/employee emails, derives the email
 * pattern, and writes inferred employee emails. Verified data AUTO-SAVES to the
 * live record; inferred emails are kept separate and clearly labelled. */
const ENRICH_LABEL = { website: "Website", industry: "Industry", description: "Description", employee_count: "Employees", founded_year: "Founded", phone: "Phone", linkedin_url: "LinkedIn", revenue: "Revenue" };
function EnrichCard({ orgId, orgName }) {
  const { toast } = React.useContext(window.CrmContext);
  const [balance, setBalance] = useState(null);
  const [view, setView] = useState({ fields: [], inferred_emails: [], email_pattern: null, website: null });
  const [busy, setBusy] = useState(false);
  const [statusMsg, setStatusMsg] = useState("");

  const client = () => window.ContactIQ && window.ContactIQ.client;
  const refreshBalance = () => { const c = client(); if (c) c.rpc("enrich_credit_balance").then(({ data, error }) => { if (!error && data != null) setBalance(data); }).catch(() => {}); };
  const refreshView = () => { const c = client(); if (!c) return; c.rpc("org_enrichment_view", { p_org_id: orgId }).then(({ data }) => { if (data) setView(data); }).catch(() => {}); };

  useEffect(() => {
    const c = client(); if (!c || orgId == null) return;
    setView({ fields: [], inferred_emails: [], email_pattern: null, website: null }); setBusy(false);
    refreshBalance(); refreshView();
  }, [orgId]);

  // Enrichment is async: the edge fn returns {status:'running'} immediately and
  // does the slow 3-stage web research in the background. We poll the job.
  const pollJob = (tries) => {
    const c = client(); if (!c) { setBusy(false); return; }
    if (tries > 40) { // ~140s — job likely killed; reclaim the credit
      c.rpc("enrich_job_giveup", { p_org_id: orgId })
        .then(({ data }) => { setBusy(false); if (data && data.balance != null) setBalance(data.balance); toast("Research took too long — credit refunded, try again"); })
        .catch(() => { setBusy(false); toast("Enrichment timed out"); });
      return;
    }
    c.rpc("enrich_job_status", { p_org_id: orgId }).then(({ data, error }) => {
      const st = !error && data ? data.status : null;
      if (st === "done") { setBusy(false); setStatusMsg(""); refreshBalance(); refreshView(); toast((data && data.message) ? "Enriched · " + data.message : "Enriched"); return; }
      if (st === "no_data") { setBusy(false); setStatusMsg(""); refreshBalance(); toast((data && data.message) || "Nothing verifiable found — credit refunded"); return; }
      if (st === "failed") { setBusy(false); setStatusMsg(""); refreshBalance(); toast((data && data.message) || "Enrichment failed — credit refunded"); return; }
      if (data && data.message) setStatusMsg(data.message); // live progress
      setTimeout(() => pollJob(tries + 1), 3500); // running | none
    }).catch(() => setTimeout(() => pollJob(tries + 1), 3500));
  };

  const enrich = () => {
    const c = client(); if (!c) { toast("Sign in to enrich"); return; }
    setBusy(true); setStatusMsg("Starting…");
    c.functions.invoke("aiciq-enrich-org", { body: { org_id: orgId } })
      .then(({ data, error }) => {
        if (error || !data) { setBusy(false); toast("Enrichment failed"); return; }
        if (data.balance != null) setBalance(data.balance);
        if (data.status === "insufficient_credits") { setBusy(false); toast("Out of credits — buy more to continue"); return; }
        if (data.status === "running") { toast("Researching the web — verifying site, firmographics & emails (up to a minute)…"); pollJob(0); return; }
        setBusy(false);
      })
      .catch(() => { setBusy(false); toast("Enrichment failed"); });
  };

  const buy = () => {
    const c = client(); if (!c) { toast("Sign in first"); return; }
    c.functions.invoke("stripe_create_checkout", { body: { kind: "credits", packs: 1, return_url: window.location.origin + window.location.pathname } })
      .then(({ data, error }) => { if (error || !data || !data.url) { toast("Checkout unavailable"); return; } window.location = data.url; })
      .catch(() => toast("Checkout unavailable"));
  };

  const fields = (view && view.fields) || [];
  const inferred = (view && view.inferred_emails) || [];
  const pat = view && view.email_pattern;
  const out = balance != null && balance <= 0;
  const hasData = fields.length > 0 || inferred.length > 0 || pat;
  const fieldVal = (f) => f.source_url ? <a href={f.source_url} target="_blank" rel="noopener noreferrer" style={{ cursor: "pointer" }}>{f.value}</a> : f.value;

  return (
    <section className="card side-card">
      <div className="card-head"><span className="ch-title">Web enrichment</span><span className="ch-spacer"></span>
        {balance != null && <span className="pill" title="Enrichment credits remaining"><span className="fact">{balance}</span> credits</span>}
      </div>
      <div style={{ padding: "12px 14px" }}>
        {hasData && (
          <div style={{ marginBottom: "12px" }}>
            {fields.map((f) => (
              <Field key={f.field}
                l={<>{ENRICH_LABEL[f.field] || f.field}{f.entity_match === "name_only" && <span title="same-name match — identity not domain-confirmed" style={{ color: "var(--amber)", marginLeft: 4 }}>⚠</span>}</>}
                v={fieldVal(f)}/>
            ))}
            {pat && (
              <div className="field"><span className="fl">Email pattern</span>
                <span className="fv" style={{ fontFamily: "var(--mono, ui-monospace)" }}>{pat.pattern}@{pat.domain} <span style={{ color: "var(--fg-3)" }}>({pat.confidence_pct}%)</span></span></div>
            )}
            {fields.length > 0 && <div className="src" style={{ marginTop: "6px" }}><span className="sdot" style={{ background: "var(--src-government)" }}></span>web-enriched · saved to record · verified source</div>}

            {inferred.length > 0 && (
              <div style={{ marginTop: "12px", borderTop: "1px solid var(--border-2)", paddingTop: "10px" }}>
                <div style={{ fontWeight: 600, fontSize: "var(--fs-sm)", marginBottom: "6px" }}>Inferred employee emails <span style={{ color: "var(--fg-3)", fontWeight: 400 }}>({inferred.length})</span></div>
                {inferred.map((p, i) => (
                  <div className="field" key={i}><span className="fl" title={p.title || ""}>{p.name}</span><span className="fv">{p.email}</span></div>
                ))}
                <div className="src" style={{ marginTop: "6px", color: "var(--amber)" }}>inferred from the email pattern — not verified addresses</div>
              </div>
            )}
          </div>
        )}

        {out ? (
          <div>
            <div style={{ fontSize: "var(--fs-base)", color: "var(--fg-3)", marginBottom: "10px" }}>You're out of enrichment credits.</div>
            <button className="btn btn-sm btn-primary" onClick={buy}>Buy more credits</button>
          </div>
        ) : (
          <>
            <button className="btn btn-sm btn-primary" disabled={busy} onClick={enrich}>{busy ? "Researching…" : (hasData ? "Re-enrich from web" : "Enrich from web")}</button>
            <div className="src" style={{ marginTop: "8px" }}>
              {busy ? <><span className="sdot" style={{ background: "var(--accent)" }}></span>{statusMsg || "Researching…"}</> : "verifies the website, fills firmographics & infers emails · 1 credit"}
            </div>
          </>
        )}
      </div>
    </section>
  );
}
window.CrmEnrichCard = EnrichCard;

function AccountDossier({ go, orgId }) {
  const { toast } = React.useContext(window.CrmContext);
  const Ico = window.CrmIco;
  const [scope, setScope] = useState("shared");
  const [d, setD] = useState(null);
  const [loaded, setLoaded] = useState(false);
  const [following, setFollowing] = useState(false);

  const toggleFollow = () => {
    const orgId = (d && d.org && d.org.id) || window.__crmAccountOrgId || 2322887;
    const next = !following; setFollowing(next);
    const c = window.ContactIQ && window.ContactIQ.client;
    if (c) (next ? c.rpc("crm_save_org", { p_org_id: orgId, p_share: false }) : c.rpc("crm_unsave_org", { p_org_id: orgId })).catch(() => {});
    toast(next ? "Following — this company's filings & events will surface in Today" : "Unfollowed");
  };

  useEffect(() => {
    const c = window.ContactIQ && window.ContactIQ.client;
    if (!c) { setLoaded(true); return; }
    let alive = true; setLoaded(false); setD(null); setFollowing(false);
    const id = orgId || window.__crmAccountOrgId;
    if (!id) { setLoaded(true); return; }
    c.rpc("crm_account_dossier", { p_org_id: id })
      .then(({ data, error }) => { if (alive) { if (!error && data && data.org) setD(data); setLoaded(true); } })
      .catch(() => { if (alive) setLoaded(true); });
    return () => { alive = false; };
  }, [orgId]);

  const org = (d && d.org) || {};
  const contacts = (d && Array.isArray(d.contacts)) ? d.contacts : [];
  const regRows = d ? federalRows(d.federal) : [];
  const web = org.website ? org.website.replace(/^https?:\/\//, "").replace(/\/$/, "") : null;
  const fec = d && d.federal && d.federal.fec_donors;
  // Parity sections (same data the extension surfaces)
  const portfolio = (d && Array.isArray(d.portfolio)) ? d.portfolio : [];
  const litigation = (d && Array.isArray(d.litigation)) ? d.litigation : [];
  const principals = (d && Array.isArray(d.principals)) ? d.principals : [];
  const recentFilings = (d && Array.isArray(d.recent_filings)) ? d.recent_filings : [];
  const timeline = (d && Array.isArray(d.timeline)) ? d.timeline : [];
  const family = (d && d.corporate_family) || null;
  const famParents = (family && Array.isArray(family.parents)) ? family.parents : [];
  const famChildren = (family && Array.isArray(family.children)) ? family.children : [];
  const aliases = (d && Array.isArray(d.aliases)) ? d.aliases.filter((a) => a && a.toUpperCase() !== String(org.name || "").toUpperCase()) : [];
  const fmtDt = (s) => (s ? String(s).slice(0, 10) : "");
  const shortBbl = (s) => (s ? String(s).replace(/^BBL:(\d{1,2})(\d{5})(\d{4})$/, "BBL $1-$2-$3").replace("BBL:", "BBL ") : s);
  // Resolve the mapped parcel to a human address (the portfolio carries street/city
  // for it) so the hero shows "229 W 43rd St, New York, NY" instead of a raw BBL.
  const mappedProp = portfolio.find((p) => p.parcel_ref && p.parcel_ref === org.parcel_ref) || (org.parcel_ref && portfolio.length ? portfolio[0] : null);
  const mappedAddr = mappedProp ? [mappedProp.street, [mappedProp.city, mappedProp.state].filter(Boolean).join(", ")].filter(Boolean).join(" · ") : (org.hq || null);

  return (
    <div className="page">
      <div style={{ display: "flex", alignItems: "center", gap: "7px", fontSize: "var(--fs-sm)", color: "var(--fg-3)", marginBottom: "14px" }}>
        <a onClick={() => go("crm_account")} style={{ color: "var(--fg-2)", cursor: "pointer" }}>Accounts</a><span>/</span>
        <span style={{ color: "var(--fg-1)", fontWeight: 500 }}>{dash(org.name)}</span>
      </div>

      {/* HERO */}
      <div className="bldg-hero">
        <div className="bh-top">
          <span className="bh-mark" style={{ background: "#b4530910", borderColor: "#fde68a", color: "var(--amber)", fontSize: 24, display: "flex", alignItems: "center", justifyContent: "center" }}>🏢</span>
          <div className="bh-main">
            <h1 className="bh-name">{dash(org.name)}</h1>
            <div className="bh-addr">{mappedAddr ? "Mapped at " + mappedAddr : (org.parcel_ref ? "Mapped at " + shortBbl(org.parcel_ref) : "No mapped building")} <span className="bbl">{org.id ? "org_" + org.id : ""}</span></div>
            {aliases.length > 0 && <div className="src" style={{ marginTop: "3px" }}>also known as: {aliases.slice(0, 4).join(" · ")}</div>}
            <div className="bh-tags">
              {org.industry && <span className="pill" style={{ background: "#47556914", color: "var(--src-government)", borderColor: "transparent" }}>{org.industry}</span>}
              {org.employees != null && <span className="pill"><span className="fact">{Number(org.employees).toLocaleString()}</span> employees</span>}
              {org.state && <span className="pill">{org.state}</span>}
              {!loaded && <span className="pill">Loading…</span>}
            </div>
          </div>
          <div className="bh-actions">
            <div className="scope-toggle" title="Private or shared">
              <button className={scope === "private" ? "on" : ""} title="Private to me" onClick={() => { setScope("private"); toast("Set to private — only you can see this"); }}><Ico.Lock/></button>
              <button className={scope === "shared" ? "on" : ""} title="Shared with team" onClick={() => { setScope("shared"); toast("Shared with your team"); }}><Ico.Team/></button>
            </div>
            <button className={"btn" + (following ? " btn-primary on" : "")} onClick={toggleFollow}>
              <svg width="14" height="14" viewBox="0 0 16 16" fill={following ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1" strokeLinejoin="round"><path d="M8 2l1.8 3.8 4.2.6-3 3 .7 4.2L8 11.6l-3.7 2 .7-4.2-3-3 4.2-.6z"/></svg>
              {following ? "Following" : "Follow"}
            </button>
            <button className="btn btn-primary" onClick={() => go("crm_deals")}><Ico.Plus s={13}/>New deal</button>
          </div>
        </div>
        <div className="bh-facts" style={{ gridTemplateColumns: "repeat(5,1fr)" }}>
          {[["Founded", org.founded], ["Employees", org.employees != null ? Number(org.employees).toLocaleString() : null], ["Revenue", org.revenue != null ? fmtMoney(org.revenue) : null], ["State", org.state], ["Industry", org.industry]].map(([l, val]) => (
            <div className="bh-fact" key={l}><span className="bf-l">{l}</span><span className="bf-v">{dash(val)}</span></div>
          ))}
        </div>
      </div>

      <div className="acct-layout">
        {/* LEFT: firmographics + regulatory */}
        <div>
          <section className="card" style={{ marginBottom: "20px" }}>
            <div className="card-head"><span className="ch-title">Firmographics</span><span className="ch-spacer"></span><span className="src">from the entity graph</span></div>
            <div style={{ padding: "6px 16px 14px" }}>
              <Field l="Legal name" v={org.name}/>
              <Field l="Website" v={web ? <a onClick={() => toast(web)} style={{ cursor: "pointer" }}>{web}</a> : null}/>
              <Field l="Phone" v={org.phone}/>
              <Field l="Headcount" v={org.employees != null ? Number(org.employees).toLocaleString() : null}/>
              <Field l="Industry" v={org.industry}/>
              <Field l="State" v={org.state}/>
              <Field l="Mapped parcel" v={org.parcel_ref ? org.parcel_ref.replace("BBL:", "BBL ") : null}/>
            </div>
          </section>

          <section className="card">
            <div className="card-head"><span className="ch-title">Regulatory &amp; provenance panels</span><span className="ch-spacer"></span><span className="src">verified records only</span></div>
            <div className="reg-panel">
              {regRows.length ? regRows.map((r) => (
                <div className="reg-row" key={r.key}>
                  <span className="reg-badge" style={{ background: r.meta.color }}>{r.meta.badge}</span>
                  <div className="reg-main"><div className="reg-title">{r.meta.label}</div><div className="reg-fact">{r.fact}</div></div>
                  <div className="reg-right"><span className="src" style={{ justifyContent: "flex-end" }}><span className="sdot" style={{ background: r.meta.color }}></span>federal source</span></div>
                </div>
              )) : (
                <div style={{ padding: "22px 16px", color: "var(--fg-3)", fontSize: "var(--fs-base)" }}>{loaded ? "No federal or regulatory records on file for this entity." : "Loading…"}</div>
              )}
            </div>
          </section>

          {litigation.length > 0 && (
            <section className="card" style={{ marginTop: "20px" }}>
              <div className="card-head"><span className="ch-title">Litigation</span><span className="pill" style={{ padding: "1px 7px" }}><span className="fact">{litigation.length}</span></span><span className="ch-spacer"></span><span className="src">CourtListener</span></div>
              <div className="reg-panel">
                {litigation.map((c, i) => (
                  <div className="reg-row" key={i}>
                    <span className="reg-badge" style={{ background: "var(--src-hedge)" }}>CASE</span>
                    <div className="reg-main"><div className="reg-title">{c.case_name || "(unnamed case)"}</div><div className="reg-fact">{[c.court, c.date_filed ? fmtDt(c.date_filed) : null, c.role].filter(Boolean).join(" · ")}</div></div>
                  </div>
                ))}
              </div>
            </section>
          )}

          {recentFilings.length > 0 && (
            <section className="card" style={{ marginTop: "20px" }}>
              <div className="card-head"><span className="ch-title">Recent filings</span><span className="pill" style={{ padding: "1px 7px" }}><span className="fact">{recentFilings.length}</span></span><span className="ch-spacer"></span><span className="src">SEC · WARN</span></div>
              <div className="reg-panel">
                {recentFilings.map((r, i) => (
                  <div className="reg-row" key={i}>
                    <span className="reg-badge" style={{ background: "var(--accent)" }}>{(r.form || r.type || "DOC").toString().slice(0, 5)}</span>
                    <div className="reg-main"><div className="reg-title">{r.title || r.description || r.form || r.type || "filing"}</div><div className="reg-fact">{[r.filing_date ? fmtDt(r.filing_date) : (r.date ? fmtDt(r.date) : null), r.source].filter(Boolean).join(" · ")}</div></div>
                  </div>
                ))}
              </div>
            </section>
          )}
        </div>

        {/* RIGHT */}
        <div>
          {d && d.sec && d.sec.ticker && (
            <section className="card side-card">
              <div className="card-head"><span className="ch-title">Public company</span><span className="ch-spacer"></span><span className="src">SEC · EDGAR</span></div>
              <div style={{ padding: "12px 14px" }}>
                <div style={{ display: "flex", gap: "8px", flexWrap: "wrap", marginBottom: d.financials ? "10px" : 0 }}>
                  <span className="pill"><span className="fact">{d.sec.ticker}</span></span>
                  {d.sec.sic_desc && <span className="pill">{d.sec.sic_desc}</span>}
                  {d.sec.hq && <span className="pill">{d.sec.hq}</span>}
                </div>
                {d.financials && (
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px" }}>
                    <div className="stat-tile" style={{ padding: "10px 12px" }}><span className="st-label">Revenue</span><span className="st-val accent" style={{ fontSize: "var(--fs-lg)" }}>{fmtMoney(d.financials.revenue)}</span><span className="st-foot">FY {String(d.financials.fy_end || "").slice(0, 4)}</span></div>
                    {d.financials.net_income != null && <div className="stat-tile" style={{ padding: "10px 12px" }}><span className="st-label">Net income</span><span className="st-val" style={{ fontSize: "var(--fs-lg)" }}>{fmtMoney(d.financials.net_income)}</span></div>}
                    {d.financials.total_assets != null && <div className="stat-tile" style={{ padding: "10px 12px" }}><span className="st-label">Total assets</span><span className="st-val" style={{ fontSize: "var(--fs-lg)" }}>{fmtMoney(d.financials.total_assets)}</span></div>}
                  </div>
                )}
              </div>
            </section>
          )}
          {(famParents.length > 0 || famChildren.length > 0) && (
            <section className="card side-card">
              <div className="card-head"><span className="ch-title">Corporate family</span><span className="ch-spacer"></span><span className="src">ownership graph</span></div>
              <div style={{ padding: "10px 14px" }}>
                {famParents.length > 0 && (
                  <div style={{ marginBottom: famChildren.length ? "10px" : 0 }}>
                    <div className="src" style={{ marginBottom: "5px" }}>Owned by</div>
                    {famParents.map((p, i) => (
                      <div className="debt-row" key={"p" + i} style={{ cursor: p.org_id ? "pointer" : "default" }} onClick={() => p.org_id && go("crm_account?org=" + p.org_id)}>
                        <div className="debt-main"><div className="debt-label">{p.name}</div><div className="debt-sub">{(p.source || "").replace(/_/g, " ")}</div></div>
                        {p.org_id && <a className="row-action">Open →</a>}
                      </div>
                    ))}
                  </div>
                )}
                {famChildren.length > 0 && (
                  <div>
                    <div className="src" style={{ marginBottom: "5px" }}>Subsidiaries &amp; brands <span className="fact">{famChildren.length}</span></div>
                    {famChildren.map((c, i) => (
                      <div className="debt-row" key={"c" + i} style={{ cursor: c.org_id ? "pointer" : "default" }} onClick={() => c.org_id && go("crm_account?org=" + c.org_id)}>
                        <div className="debt-main"><div className="debt-label">{c.name}</div><div className="debt-sub">{(c.source || "").replace(/_/g, " ")}</div></div>
                        {c.org_id && <a className="row-action">Open →</a>}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </section>
          )}
          {(org.id || orgId) && <EnrichCard orgId={org.id || orgId} orgName={org.name}/>}
          {(org.id || orgId) && <NotesCard subjectType="org" subjectId={org.id || orgId}/>}
          {principals.length > 0 && (
            <section className="card side-card">
              <div className="card-head"><span className="ch-title">Principals</span><span className="pill" style={{ padding: "1px 7px" }}><span className="fact">{principals.length}</span></span><span className="ch-spacer"></span><span className="src">DOS filings</span></div>
              {principals.map((p, i) => (
                <div className="contact-row" key={i}>
                  <span className="avatar" style={{ background: AV_PALETTE[i % AV_PALETTE.length] + "18", color: AV_PALETTE[i % AV_PALETTE.length], borderColor: AV_PALETTE[i % AV_PALETTE.length] + "30" }}>{initialsOf(p.name || p.full_name)}</span>
                  <div className="contact-main"><div className="contact-name">{p.name || p.full_name}</div><div className="contact-title">{[p.role, p.status, p.filing_date ? "filed " + fmtDt(p.filing_date) : null].filter(Boolean).join(" · ") || "—"}</div></div>
                </div>
              ))}
            </section>
          )}

          <section className="card side-card">
            <div className="card-head"><span className="ch-title">Contacts</span><span className="pill" style={{ padding: "1px 7px" }}><span className="fact">{contacts.length}</span></span><span className="ch-spacer"></span><button className="btn btn-sm" onClick={() => toast("Claim contact from building roster")}>Claim from roster</button></div>
            {contacts.length ? contacts.map((c, i) => (
              <div className="contact-row" key={i}>
                <span className="avatar" style={{ background: AV_PALETTE[i % AV_PALETTE.length] + "18", color: AV_PALETTE[i % AV_PALETTE.length], borderColor: AV_PALETTE[i % AV_PALETTE.length] + "30" }}>{initialsOf(c.name)}</span>
                <div className="contact-main"><div className="contact-name">{c.name}</div><div className="contact-title">{dash(c.title)}</div></div>
                <button className="icon-btn" style={{ width: 28, height: 28 }} title={c.email || "No email on file"} onClick={() => toast(c.email || "No email on file")}><svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><path d="M2 4h12v8H2zM2 4l6 5 6-5"/></svg></button>
              </div>
            )) : <div style={{ padding: "22px 14px", color: "var(--fg-3)", fontSize: "var(--fs-base)" }}>{loaded ? "No contacts on file." : "Loading…"}</div>}
            {contacts.length > 0 && <div style={{ padding: "9px 14px" }}><span className="src"><span className="sdot" style={{ background: "var(--src-npi)" }}></span>contacts · people graph</span></div>}
          </section>

          <section className="card side-card">
            <div className="card-head"><span className="ch-title">Intelligence</span></div>
            <div style={{ padding: "14px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px" }}>
              <div className="stat-tile" style={{ padding: "11px 13px" }}><span className="st-label">Open deals</span><span className="st-val accent" style={{ fontSize: "var(--fs-lg)" }}>{d ? (d.open_deals || 0) : "—"}</span><span className="st-foot">in pipeline</span></div>
              <div className="stat-tile" style={{ padding: "11px 13px" }}><span className="st-label">Revenue</span><span className="st-val" style={{ fontSize: "var(--fs-lg)" }}>{org.revenue != null ? fmtMoney(org.revenue) : "—"}</span><span className="st-foot">on file</span></div>
              {fec && <div className="stat-tile" style={{ padding: "11px 13px" }}><span className="st-label">Political donations</span><span className="st-val" style={{ fontSize: "var(--fs-lg)" }}>{fmtMoney(fec.total_amount)}</span><span className="st-foot"><span className="src"><span className="sdot" style={{ background: "var(--src-hedge)" }}></span>FEC · {fec.count}</span></span></div>}
              <div className="stat-tile" style={{ padding: "11px 13px" }}><span className="st-label">Contacts</span><span className="st-val" style={{ fontSize: "var(--fs-lg)" }}>{contacts.length}</span><span className="st-foot">known people</span></div>
            </div>
          </section>

          <section className="card side-card">
            <div className="card-head"><span className="ch-title">Properties</span>{portfolio.length > 0 && <span className="pill" style={{ padding: "1px 7px" }}><span className="fact">{portfolio.length}</span></span>}<span className="ch-spacer"></span><span className="src">via parcel link</span></div>
            {portfolio.length > 0
              ? portfolio.map((p, i) => (
                  <div className="debt-row" key={i} style={{ cursor: "pointer" }} onClick={() => go("crm_building")}>
                    <div className="debt-main">
                      <div className="debt-label">{p.street || shortBbl(p.parcel_ref) || "(property)"}{p.is_primary && <span className="pill" style={{ marginLeft: 6, padding: "0 6px" }}>HQ</span>}</div>
                      <div className="debt-sub">{[[p.city, p.state].filter(Boolean).join(", "), shortBbl(p.parcel_ref), p.bldg_sqft ? Number(p.bldg_sqft).toLocaleString() + " sqft" : null, p.year_built ? "built " + p.year_built : null].filter(Boolean).join(" · ")}</div>
                    </div>
                    <a className="row-action">Open →</a>
                  </div>
                ))
              : org.parcel_ref
              ? <div className="debt-row"><div className="debt-main"><div className="debt-label">{org.parcel_ref.replace("BBL:", "BBL ")}</div><div className="debt-sub">mapped location</div></div><a className="row-action" onClick={() => go("crm_building")}>Open →</a></div>
              : <div style={{ padding: "18px 14px", color: "var(--fg-3)", fontSize: "var(--fs-base)" }}>{loaded ? "No properties on file." : "Loading…"}</div>}
          </section>

          {timeline.length > 0 && (
            <section className="card side-card">
              <div className="card-head"><span className="ch-title">Recent activity</span><span className="pill" style={{ padding: "1px 7px" }}><span className="fact">{timeline.length}</span></span><span className="ch-spacer"></span><span className="src">unified timeline</span></div>
              <div style={{ padding: "4px 0" }}>
                {timeline.slice(0, 25).map((e, i) => (
                  <div className="contact-row" key={i} style={{ alignItems: "flex-start" }}>
                    <span className="avatar" style={{ background: "#47556914", color: "var(--src-government)", borderColor: "transparent", fontSize: 10 }}>{(e.kind || "•").toString().slice(0, 3).toUpperCase()}</span>
                    <div className="contact-main">
                      <div className="contact-name" style={{ whiteSpace: "normal" }}>{e.url ? <a href={e.url} target="_blank" rel="noopener noreferrer">{e.title || e.kind || "event"}</a> : (e.title || e.kind || "event")}</div>
                      <div className="contact-title" style={{ whiteSpace: "normal" }}>{[fmtDt(e.occurred_at), e.subtitle].filter(Boolean).join(" · ").slice(0, 120)}</div>
                    </div>
                  </div>
                ))}
              </div>
            </section>
          )}
        </div>
      </div>
    </div>
  );
}

/* Accounts list — the user's followed companies + companies they have deals with.
 * Shown when no specific account is selected (replaces the old hardcoded default). */
function AccountsList({ go }) {
  const { toast } = React.useContext(window.CrmContext);
  const [rows, setRows] = useState([]);
  const [loaded, setLoaded] = useState(false);
  useEffect(() => {
    const c = window.ContactIQ && window.ContactIQ.client;
    if (!c) { setLoaded(true); return; }
    let alive = true;
    c.rpc("crm_my_accounts", {})
      .then(({ data, error }) => { if (alive && !error) setRows(data || []); })
      .catch(() => {}).then(() => { if (alive) setLoaded(true); });
    return () => { alive = false; };
  }, []);
  return (
    <div className="page">
      <div className="page-head" style={{ marginBottom: "16px" }}>
        <div className="ph-text"><div className="eyebrow">CRM · Accounts</div><h1 className="page-title">Accounts</h1>
          <div className="page-sub">Companies you follow or have an open deal with.</div></div>
      </div>
      <section className="card">
        {!loaded ? <div className="muted" style={{ padding: "28px", textAlign: "center" }}>Loading…</div>
          : !rows.length ? (
            <div className="muted" style={{ padding: "32px 20px", textAlign: "center", fontSize: "var(--fs-base)", lineHeight: 1.6 }}>
              No accounts yet.<br/>Follow a company from its profile (the ☆ on any company), open one from the <a className="row-action" style={{ display: "inline-flex" }} onClick={() => go("map")}>map</a>, or start a <a className="row-action" style={{ display: "inline-flex" }} onClick={() => go("crm_deals")}>deal</a> — it'll show up here.
            </div>
          ) : (
            <div>
              {rows.map((r) => (
                <div key={r.org_id} className="contact-row" style={{ cursor: "pointer", padding: "12px 16px" }}
                  onClick={() => go("crm_account?org=" + r.org_id)}>
                  <span className="avatar" style={{ background: "#b4530918", color: "var(--amber)", borderColor: "#fde68a" }}>🏢</span>
                  <div className="contact-main" style={{ flex: 1 }}>
                    <div className="contact-name">{r.name}</div>
                    <div className="contact-title">{[r.industry, r.state].filter(Boolean).join(" · ") || "—"}{r.parcel_ref ? " · " + r.parcel_ref.replace("BBL:", "BBL ") : ""}</div>
                  </div>
                  {r.open_deals > 0 && <span className="pill" style={{ marginRight: "8px" }}><span className="fact">{r.open_deals}</span> open</span>}
                  {r.saved && <span className="pill" title="Following">★</span>}
                  <span style={{ color: "var(--fg-3)" }}><window.CrmIco.Arrow/></span>
                </div>
              ))}
            </div>
          )}
      </section>
    </div>
  );
}

function CrmAccountPage({ go, user, orgId }) {
  return (
    <window.CrmShell go={go} user={user} current="accounts">
      {orgId ? <AccountDossier go={go} orgId={orgId}/> : <AccountsList go={go}/>}
    </window.CrmShell>
  );
}
window.CrmAccountPage = CrmAccountPage;
