/* CRM · Account — second batch of company dossier panels, ported 1:1 from the
 * map modal's renderDossier* functions (index.html). Mirrors the contract,
 * helpers, and styling of CrmAccountPanels.jsx: each panel fetches its own RPC
 * keyed by org_id and renders ONLY when real data is on file (returns null
 * otherwise) — no fabricated rows, no placeholders. Registered on
 * window.CrmPanels[key]; reuses the shared kit on window.CrmPanelKit. */

(function () {
  const { useState, useEffect } = React;
  const K = window.CrmPanelKit;
  const { usePanelData, rpcLoad, fnGet, money, num, fmtDate, fmtMonth, SrcBadge, Flag, Panel, RegRow, Field, AddrBlock, Note, fmtAddr } = K;
  window.CrmPanels = window.CrmPanels || {};

  // ───────────────────────── PANELS ─────────────────────────

  // 1. Sanctions & enforcement — OFAC SDN matches (renderDossierSanctions).
  // RPC org_sanctions → { sdn_hits:[{sdn_name, program, ent_num, title, remarks,
  // addresses:[{address, city_state_province_zip, country}]}] }.
  window.CrmPanels.sanctions = function Sanctions({ orgId }) {
    const d = usePanelData(rpcLoad("org_sanctions"), orgId);
    const hits = (d && d.sdn_hits) || [];
    if (!hits.length) return null;
    return (
      <Panel title="Sanctions & enforcement" badge={<SrcBadge bg="#fee2e2" color="#991b1b">OFAC</SrcBadge>} count={hits.length + " SDN hit" + (hits.length > 1 ? "s" : "")}>
        <div className="reg-panel">
          {hits.map((h, i) => {
            const addrs = (h.addresses || []).slice(0, 3).map((a) =>
              [a.address || "", a.city_state_province_zip ? ", " + a.city_state_province_zip : "", a.country ? " · " + a.country : ""].join("")
            ).filter((s) => s.trim());
            return (
              <RegRow key={i} badge="⛔" badgeBg="#991b1b"
                title={h.sdn_name || ""}
                fact={<>
                  {[h.program ? "Program: " + h.program : null, h.ent_num != null ? "SDN #" + h.ent_num : null, h.title || null].filter(Boolean).join(" · ")}
                  {h.remarks && <div style={{ marginTop: 2 }}>{h.remarks}</div>}
                  {addrs.length > 0 && <div style={{ marginTop: 2 }}>{addrs.map((a, j) => <div key={j}>{a}</div>)}</div>}
                </>} />
            );
          })}
        </div>
        <div style={{ padding: "0 14px 12px" }}>
          <Note color="#991b1b">OFAC sanctions match — this org appears on the U.S. Treasury Specially Designated Nationals list. Verify before any dealing.</Note>
        </div>
      </Panel>
    );
  };

  // 2. Regulatory compliance — EPA ECHO facilities (renderDossierEcho).
  // RPC org_echo_regulatory → array of facility rows.
  window.CrmPanels.echo = function Echo({ orgId }) {
    const rows = usePanelData(rpcLoad("org_echo_regulatory"), orgId);
    if (!rows || !rows.length) return null;
    const totalPenalties = rows.reduce((s, r) => s + Number(r.fac_total_penalties || 0), 0);
    const totalInsp = rows.reduce((s, r) => s + Number(r.fac_inspection_count || 0), 0);
    const totalActions = rows.reduce((s, r) => s + Number(r.fac_formal_action_count || 0), 0);
    const sncCount = rows.filter((r) => r.fac_snc_flag === "Y").length;
    const summary = [];
    summary.push(<Flag key="f" bg="#f1f5f9" color="#475569">{rows.length + " " + (rows.length === 1 ? "facility" : "facilities")}</Flag>);
    if (totalInsp > 0) summary.push(<Flag key="i" bg="#f1f5f9" color="#475569">{totalInsp + " inspections"}</Flag>);
    if (totalActions > 0) summary.push(<Flag key="a" bg="#fef3c7" color="#92400e">{totalActions + " formal actions"}</Flag>);
    if (totalPenalties > 0) summary.push(<Flag key="p" bg="#fef3c7" color="#92400e">{money(totalPenalties) + " penalties"}</Flag>);
    if (sncCount > 0) summary.push(<Flag key="s" bg="#fee2e2" color="#991b1b">{sncCount + " SNC (high priority violator)"}</Flag>);
    const progDefs = [["air_flag", "CAA", "#e0e7ff", "#3730a3"], ["npdes_flag", "CWA", "#cffafe", "#155e75"], ["rcra_flag", "RCRA", "#fed7aa", "#9a3412"], ["sdwis_flag", "SDWA", "#bfdbfe", "#1e40af"], ["tri_flag", "TRI", "#fef3c7", "#92400e"], ["ghg_flag", "GHG", "#dcfce7", "#166534"]];
    return (
      <Panel title="Regulatory compliance" badge={<SrcBadge bg="#dcfce7" color="#166534">EPA ECHO</SrcBadge>}>
        <div style={{ padding: "10px 16px 0", display: "flex", gap: 6, flexWrap: "wrap" }}>{summary}</div>
        <div className="reg-panel">
          {rows.slice(0, 8).map((r, i) => {
            const addr = [r.street, r.city, r.state].filter(Boolean).join(", ");
            const progs = progDefs.filter(([k]) => r[k]).map(([k, lbl, bg, color]) => <Flag key={k} bg={bg} color={color}>{lbl}</Flag>);
            return (
              <RegRow key={i}
                title={<>{r.facility_name || "—"} {progs.length > 0 && <span style={{ display: "inline-flex", gap: 4, flexWrap: "wrap", marginLeft: 4 }}>{progs}</span>}</>}
                fact={[addr, "Insp/Actions " + (r.fac_inspection_count || 0) + "/" + (r.fac_formal_action_count || 0)].filter(Boolean).join(" · ")}
                right={r.fac_total_penalties ? money(r.fac_total_penalties) : null} />
            );
          })}
        </div>
        <div style={{ padding: "0 14px 12px" }}><Note>U.S. EPA Enforcement &amp; Compliance History Online (ECHO).</Note></div>
      </Panel>
    );
  };

  // 3. Healthcare — Medicaid providers / health facilities / adult care
  // (renderDossierHealthcare). RPC org_healthcare → { medicaid:[], health_facilities:[], acf:[] }.
  window.CrmPanels.healthcare = function Healthcare({ orgId }) {
    const d = usePanelData(rpcLoad("org_healthcare"), orgId);
    if (!d || (!d.medicaid && !d.health_facilities && !d.acf)) return null;
    const med = d.medicaid || [], hf = d.health_facilities || [], acf = d.acf || [];
    if (!med.length && !hf.length && !acf.length) return null;
    const count = [med.length ? med.length + " Medicaid" : null, hf.length ? hf.length + " facilities" : null, acf.length ? acf.length + " ACF" : null].filter(Boolean).join(" · ");
    return (
      <Panel title="Healthcare" badge={<SrcBadge bg="#dcfce7" color="#166534">NYS DOH · Medicaid</SrcBadge>} count={count}>
        <div className="reg-panel">
          {med.slice(0, 5).map((m, i) => (
            <RegRow key={"m" + i} badge="MED" badgeBg="#166534"
              title={m.mmis_name || ""}
              fact={[m.mmis_id ? "MMIS " + m.mmis_id : null, m.npi ? "NPI " + m.npi : null, m.medicaid_type, m.provider_specialty, m.enrollment_begin_date ? "enrolled " + fmtDate(m.enrollment_begin_date) : null].filter(Boolean).join(" · ")} />
          ))}
          {hf.slice(0, 3).map((f, i) => (
            <RegRow key={"f" + i} badge="DOH" badgeBg="#15803d"
              title={f.description || f.fac_desc_short || ("Facility " + (f.fac_id || ""))}
              fact={[f.fac_id ? "ID " + f.fac_id : null, f.fac_opn_dat ? "opened " + fmtDate(f.fac_opn_dat) : null, f.operator_name ? "operator " + f.operator_name : null, f.ownership_type, f.county].filter(Boolean).join(" · ")} />
          ))}
          {acf.slice(0, 3).map((a, i) => (
            <RegRow key={"a" + i} badge="ACF" badgeBg="#0e7490"
              title={a.facility_type || ("Facility " + (a.facility_id || ""))}
              fact={[a.facility_id ? "ID " + a.facility_id : null, a.classification, a.certificate_number ? "cert " + a.certificate_number : null, a.number_of_beds != null ? num(a.number_of_beds) + " beds" : null, a.operator ? "operator " + a.operator : null].filter(Boolean).join(" · ")} />
          ))}
        </div>
        <div style={{ padding: "0 14px 12px" }}><Note>NYS Department of Health — Medicaid providers, health facilities, adult care facilities.</Note></div>
      </Panel>
    );
  };

  // 4. OSHA workplace safety — establishments + recent annual filings
  // (renderDossierOsha). RPC org_osha_safety → { establishments:[], recent_filings:[] }.
  window.CrmPanels.osha = function Osha({ orgId }) {
    const d = usePanelData(rpcLoad("org_osha_safety"), orgId);
    const est = (d && d.establishments) || [];
    const filings = (d && d.recent_filings) || [];
    if (!est.length && !filings.length) return null;
    return (
      <Panel title="OSHA workplace safety" badge={<SrcBadge bg="#fee2e2" color="#991b1b">OSHA</SrcBadge>} count={est.length + " establishments · " + filings.length + " filings"}>
        <div className="reg-panel">
          {est.slice(0, 5).map((e, i) => (
            <RegRow key={"e" + i} badge="EST" badgeBg="#991b1b"
              title={e.establishment_name || e.company_name || ""}
              fact={<>
                {[e.industry_description, e.naics_code ? "NAICS " + e.naics_code : null, e.latest_year ? "latest " + e.latest_year : null, e.max_employees != null ? num(e.max_employees) + " employees" : null].filter(Boolean).join(" · ")}
                <div style={{ marginTop: 2 }}>
                  {[e.total_injuries_sum != null ? num(e.total_injuries_sum) + " injuries" : null, e.total_deaths_sum && e.total_deaths_sum > 0 ? e.total_deaths_sum + " deaths" : null, e.total_dafw_cases_sum != null ? num(e.total_dafw_cases_sum) + " DAFW cases" : null].filter(Boolean).join(" · ")}
                </div>
              </>} />
          ))}
          {filings.slice(0, 5).map((f, i) => (
            <RegRow key={"f" + i} badge={f.year_filing_for != null ? String(f.year_filing_for) : "FIL"} badgeBg="#7c2d12"
              title={f.establishment_name || ""}
              fact={[f.annual_average_employees != null ? num(f.annual_average_employees) + " employees" : null, f.total_hours_worked != null ? num(f.total_hours_worked) + " hrs" : null, f.total_injuries != null ? num(f.total_injuries) + " injuries" : null, f.total_deaths && f.total_deaths > 0 ? f.total_deaths + " deaths" : null, f.total_dafw_cases != null ? num(f.total_dafw_cases) + " DAFW cases" : null, f.no_injuries_illnesses ? "no injuries" : null].filter(Boolean).join(" · ")} />
          ))}
        </div>
        <div style={{ padding: "0 14px 12px" }}><Note>OSHA establishment-specific injury &amp; illness (ITA) filings.</Note></div>
      </Panel>
    );
  };

  // 5. SEC filings — reporting company / Form ADV / Form D issuances
  // (renderDossierSec). RPC org_sec_filings → { company:{}, form_adv:{}, form_d_issuers:[] }.
  window.CrmPanels.sec = function Sec({ orgId }) {
    const d = usePanelData(rpcLoad("org_sec_filings"), orgId);
    if (!d || (!d.company && !d.form_adv && !d.form_d_issuers)) return null;
    const c = d.company, a = d.form_adv;
    const issuers = d.form_d_issuers || [];
    if (!c && !a && !issuers.length) return null;
    const count = [c ? "Company" : null, a ? "Form ADV" : null, issuers.length ? issuers.length + " Form D" : null].filter(Boolean).join(" · ");
    return (
      <Panel title="SEC filings" badge={<SrcBadge bg="#dbeafe" color="#1e40af">SEC</SrcBadge>} count={count}>
        {c && (
          <div style={{ padding: "6px 16px 4px" }}>
            <div style={{ fontSize: "var(--fs-sm)", color: "var(--fg-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>Reporting company · EDGAR</div>
            <Field l="CIK" v={c.cik} mono />
            <Field l="Ticker" v={c.ticker} mono />
            <Field l="SIC" v={c.sic_desc} />
            <Field l="Entity type" v={c.entity_type} />
            <Field l="State of inc" v={c.state_of_inc} />
            <Field l="Fiscal year end" v={c.fiscal_year_end} />
          </div>
        )}
        {a && (
          <div style={{ padding: "6px 16px 4px" }}>
            <div style={{ fontSize: "var(--fs-sm)", color: "var(--fg-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>Form ADV (Investment Adviser) · IARD</div>
            <Field l="CRD" v={a.crd} mono />
            <Field l="SEC number" v={a.sec_number} />
            <Field l="Primary name" v={a.primary_business_name} />
            <Field l="Firm type" v={a.firm_type} />
            <Field l="SEC status" v={a.sec_status} />
            <Field l="Effective" v={fmtDate(a.sec_status_effective_date)} />
            <Field l="Latest filing" v={fmtDate(a.latest_filing_date)} />
          </div>
        )}
        {issuers.length > 0 && (
          <div className="reg-panel">
            {issuers.slice(0, 5).map((iss, i) => (
              <RegRow key={i} badge="Reg D" badgeBg="#1e40af"
                title={iss.entity_name || ""}
                fact={[iss.filing_date ? "Filed " + fmtDate(iss.filing_date) : null, iss.jurisdiction_of_inc, iss.entity_type, iss.year_of_inc ? "inc " + iss.year_of_inc : null, iss.submission_type].filter(Boolean).join(" · ")} />
            ))}
          </div>
        )}
        <div style={{ padding: "0 14px 12px" }}><Note>SEC EDGAR — reporting company, Form ADV (IARD), Form D issuances.</Note></div>
      </Panel>
    );
  };

  // 6. Federal registrations — FDIC / NCUA / HMDA / FMCSA
  // (renderDossierFinReg). RPC org_financial_regulators → { fdic:{}, ncua:{}, hmda:[], fmcsa:{} }.
  window.CrmPanels.finreg = function FinReg({ orgId }) {
    const d = usePanelData(rpcLoad("org_financial_regulators"), orgId);
    // For a carrier-linked org with no authority/insurance snapshot yet, fire the
    // on-demand FMCSA QCMobile ingest once (session-deduped). It surfaces on next open.
    useEffect(() => {
      if (!d || !d.fmcsa || d.fmcsa.authority || !orgId) return;
      const c = window.ContactIQ && window.ContactIQ.client; if (!c) return;
      try {
        const k = "ciq_fmcsaauth_" + orgId;
        if (sessionStorage.getItem(k)) return;
        sessionStorage.setItem(k, "1");
        c.functions.invoke("ingest-fmcsa-authority", { body: { org_id: orgId } }).catch(() => {});
      } catch (_) {}
    }, [d, orgId]);
    if (!d || (!d.hmda && !d.fdic && !d.ncua && !d.fmcsa)) return null;
    const hmda = d.hmda || [];
    if (!d.fdic && !d.ncua && !hmda.length && !d.fmcsa) return null;
    const count = [d.fdic ? "FDIC" : null, d.ncua ? "NCUA" : null, hmda.length ? "HMDA" : null, d.fmcsa ? "FMCSA" : null].filter(Boolean).join(" · ");
    return (
      <Panel title="Federal registrations" badge={<SrcBadge bg="#fce7f3" color="#9d174d">HMDA · FDIC · FMCSA</SrcBadge>} count={count}>
        {d.fdic && (
          <div style={{ padding: "6px 16px 4px" }}>
            <div style={{ fontSize: "var(--fs-sm)", color: "var(--fg-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>FDIC-insured bank</div>
            <Field l="Cert #" v={d.fdic.cert} mono />
            <Field l="Charter" v={d.fdic.charter} />
            <Field l="Class" v={d.fdic.bk_class} />
            <Field l="Assets" v={d.fdic.asset != null ? money(Number(d.fdic.asset) * 1000) : null} />
            <Field l="Effective" v={fmtDate(d.fdic.eff_date)} />
            <Field l="Holding co." v={d.fdic.name_hcr} />
          </div>
        )}
        {d.ncua && (
          <div style={{ padding: "6px 16px 4px" }}>
            <div style={{ fontSize: "var(--fs-sm)", color: "var(--fg-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>NCUA credit union</div>
            <Field l="CU number" v={d.ncua.cu_number} />
            <Field l="Charter #" v={d.ncua.charter_no} />
            <Field l="Peer group" v={d.ncua.peer_group} />
            <Field l="Type" v={d.ncua.cu_type} />
            <Field l="Members" v={d.ncua.members != null ? num(d.ncua.members) : null} />
            <Field l="Joined" v={fmtDate(d.ncua.joined_date)} />
          </div>
        )}
        {hmda.length > 0 && (
          <div className="reg-panel">
            {hmda.slice(0, 5).map((h, i) => (
              <RegRow key={i} badge="HMDA" badgeBg="#9d174d"
                title={"Reporting year " + h.reporting_year}
                fact={[h.lei ? "LEI " + h.lei : null, h.loan_count != null ? num(h.loan_count) + " loans" : null].filter(Boolean).join(" · ")} />
            ))}
          </div>
        )}
        {d.fmcsa && (
          <div style={{ padding: "6px 16px 4px" }}>
            <div style={{ fontSize: "var(--fs-sm)", color: "var(--fg-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>FMCSA carrier · DOT</div>
            <Field l="DOT #" v={d.fmcsa.dot_number} mono />
            <Field l="MC #" v={d.fmcsa.docket1 ? "MC-" + d.fmcsa.docket1 : null} mono />
            <Field l="Status" v={d.fmcsa.status_code} />
            <Field l="Operation" v={d.fmcsa.carrier_operation} />
            <Field l="Org type" v={d.fmcsa.business_org_desc} />
            <Field l="Power units" v={d.fmcsa.power_units != null ? num(d.fmcsa.power_units) : null} />
            <Field l="Drivers" v={d.fmcsa.total_drivers != null ? num(d.fmcsa.total_drivers) : null} />
            <Field l="HazMat" v={d.fmcsa.hm_ind === "Y" ? "Yes" : null} />
            <Field l="MCS-150" v={fmtDate(d.fmcsa.mcs150_date)} />
            {d.fmcsa.authority && (() => {
              const a = d.fmcsa.authority;
              const authTxt = (s) => (s === "A" ? "Active" : s === "I" ? "Inactive" : s === "N" ? "None" : s || "—");
              const amt = (v) => (v != null && v !== "" && !isNaN(Number(v)) ? money(Number(v) * 1000) : null);
              const authParts = [
                a.common && a.common !== "N" ? "Common " + authTxt(a.common) : null,
                a.contract && a.contract !== "N" ? "Contract " + authTxt(a.contract) : null,
                a.broker && a.broker !== "N" ? "Broker " + authTxt(a.broker) : null,
              ].filter(Boolean).join(" · ");
              return (
                <div style={{ marginTop: 8, paddingTop: 8, borderTop: "1px solid var(--border-1)" }}>
                  <div style={{ fontSize: "var(--fs-sm)", color: "var(--fg-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>Authority &amp; insurance</div>
                  <Field l="Authorized to operate" v={a.allowed_to_operate === "Y" ? <Flag bg="#dcfce7" color="#166534">Yes</Flag> : a.allowed_to_operate === "N" ? <Flag bg="#fee2e2" color="#991b1b">No</Flag> : null} />
                  <Field l="Operating authority" v={authParts || (a.allowed_to_operate ? "None on file" : null)} />
                  <Field l="Liability (BIPD)" v={a.bipd_required === "Y" ? ((amt(a.bipd_on_file) || "$0") + " on file" + (amt(a.bipd_required_amount) ? " / " + amt(a.bipd_required_amount) + " required" : "")) : null} />
                  <Field l="Cargo insurance" v={a.cargo_on_file != null && Number(a.cargo_on_file) > 0 ? amt(a.cargo_on_file) + " on file" : null} />
                  <Field l="Surety bond" v={a.bond_on_file != null && Number(a.bond_on_file) > 0 ? amt(a.bond_on_file) + " on file" : null} />
                  <Note>FMCSA QCMobile — authority status &amp; insurance on file (insurer/policy not published in this feed).</Note>
                </div>
              );
            })()}
          </div>
        )}
        <div style={{ padding: "0 14px 12px" }}><Note>Federal financial-regulator registrations — FDIC, NCUA, HMDA, FMCSA.</Note></div>
      </Panel>
    );
  };

  // 7. Retirement & benefit plans — DOL Form 5500 (loaded into r.form_5500;
  // rendered by f5500*Block in index.html). RPC org_form_5500 (args { p_org_id })
  // → { sponsors:[{sponsor_name, sponsor_ein, ...}], filings:[{plan_name,
  // plan_number, form_type, form_tax_period, plan_year_begin, total_participants,
  // active_participants, total_assets_eoy, ...}], totals:{plan_count,
  // max_participants, total_active} }.
  window.CrmPanels.form5500 = function Form5500({ orgId }) {
    const d = usePanelData(rpcLoad("org_form_5500"), orgId);
    const sponsors = (d && d.sponsors) || [];
    const filings = (d && d.filings) || [];
    if (!sponsors.length && !filings.length) return null;
    const t = (d && d.totals) || {};
    return (
      <Panel title="Retirement & benefit plans" badge={<SrcBadge bg="#e0e7ff" color="#3730a3">DOL 5500</SrcBadge>} count={t.plan_count != null ? t.plan_count + " plan" + (t.plan_count === 1 ? "" : "s") : (filings.length || sponsors.length)}>
        {(t.max_participants != null || t.total_active != null) && (
          <div style={{ padding: "10px 16px 0", display: "flex", gap: 6, flexWrap: "wrap" }}>
            {t.max_participants != null && <Flag bg="#e0e7ff" color="#3730a3">{num(t.max_participants) + " participants (largest plan)"}</Flag>}
            {t.total_active != null && <Flag bg="#eef2ff" color="#3730a3">{num(t.total_active) + " active across plans"}</Flag>}
          </div>
        )}
        <div className="reg-panel">
          {filings.slice(0, 8).map((x, i) => {
            const yr = x.form_tax_period || x.plan_year_begin;
            const yrTxt = yr ? String(yr).slice(0, 4) : "";
            return (
              <RegRow key={"x" + i} badge={x.form_type === "sf" ? "SF" : "5500"} badgeBg="#3730a3"
                title={(x.plan_name || "—") + (x.plan_number ? " #" + x.plan_number : "")}
                fact={[yrTxt ? "Year " + yrTxt : null, (x.total_participants != null ? x.total_participants : x.active_participants) != null ? num(x.total_participants != null ? x.total_participants : x.active_participants) + " participants" : null, x.total_assets_eoy != null ? money(x.total_assets_eoy) + " assets" : null].filter(Boolean).join(" · ")} />
            );
          })}
          {filings.length === 0 && sponsors.slice(0, 5).map((s, i) => (
            <RegRow key={"s" + i} badge="5500" badgeBg="#3730a3"
              title={s.sponsor_name || ""}
              fact={[s.sponsor_ein ? "EIN " + s.sponsor_ein : null, s.business_code ? "NAICS " + s.business_code : null].filter(Boolean).join(" · ")} />
          ))}
        </div>
        <div style={{ padding: "0 14px 12px" }}><Note>DOL Form 5500 — pension &amp; welfare plan filings.</Note></div>
      </Panel>
    );
  };
})();
