/* CRM · Account — third batch of company-dossier panels, ported 1:1 from the
 * map modal's renderDossier* functions (index.html). 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. Registers onto
 * window.CrmPanels[key]; reuses the shared kit on window.CrmPanelKit.
 *
 * Source layout: the matching renderDossier* in index.html. Many of these use
 * the map's `_ds_subsec` helper (a bold uppercase label above a group of rows);
 * that is reproduced here as a small uppercase <div> sub-label. Field/value
 * sub-rows (the map's `_ds_row`) become a stack of <Field> components. */

(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 || {};

  // Sub-section header (mirrors the map's _ds_subsec): a bold uppercase label.
  function Sub({ children }) {
    return (
      <div style={{ fontSize: "var(--fs-sm)", color: "var(--fg-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em", margin: "10px 0 6px", padding: "0 14px" }}>{children}</div>
    );
  }

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

  // NY real estate licenses — brokers, appraisers, AMC (NYS DOS).
  window.CrmPanels.relicenses = function ReLicenses({ orgId }) {
    const d = usePanelData(rpcLoad("org_re_licenses"), orgId);
    if (!d) return null;
    const br = Array.isArray(d.brokers) ? d.brokers : [];
    const ap = Array.isArray(d.appraisers) ? d.appraisers : [];
    const amc = Array.isArray(d.amc) ? d.amc : [];
    if (!br.length && !ap.length && !amc.length) return null;
    return (
      <Panel title="NY real estate licenses" badge={<SrcBadge bg="#fef3c7" color="#92400e">NYS DOS</SrcBadge>} count={br.length + ap.length + amc.length}>
        {br.length > 0 && <Sub>Brokers ({br.length})</Sub>}
        {br.slice(0, 5).map((b, i) => (
          <div key={"b" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="License #" v={b.license_number} mono />
            <Field l="Type" v={b.license_type} />
            <Field l="Business" v={b.business_name} />
            <Field l="License holder" v={b.license_holder_name} />
            <Field l="Expires" v={fmtDate(b.license_expiration_date)} />
            <Field l="County" v={b.county} />
          </div>
        ))}
        {ap.length > 0 && <Sub>Appraisers ({ap.length})</Sub>}
        {ap.slice(0, 5).map((a, i) => (
          <div key={"a" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="UID" v={a.uid} mono />
            <Field l="Type" v={a.license_type} />
            <Field l="Business" v={a.prin_bus_name} />
            <Field l="Applicant" v={a.applicant_name} />
            <Field l="Certified" v={fmtDate(a.cert_date)} />
            <Field l="Expires" v={fmtDate(a.exp_date)} />
            <Field l="County" v={a.county} />
          </div>
        ))}
        {amc.length > 0 && <Sub>AMC ({amc.length})</Sub>}
        {amc.map((a, i) => (
          <div key={"m" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="License #" v={a.license_number} mono />
            <Field l="Business" v={a.business_name} />
            <Field l="Designated" v={[a.designated_first_name, a.designated_last_name].filter(Boolean).join(" ")} />
            <Field l="Issued" v={fmtDate(a.license_issue_date)} />
            <Field l="Expires" v={fmtDate(a.license_expiration_date)} />
          </div>
        ))}
        <div style={{ padding: "0 14px 12px" }}><Note>{br.length}B · {ap.length}A · {amc.length}AMC · NYS Department of State licensing.</Note></div>
      </Panel>
    );
  };

  // NYC business permits — DCWP LOB/apps, TLC FHV + medallions, cannabis, outdoor dining.
  window.CrmPanels.nycpermits = function NycPermits({ orgId }) {
    const d = usePanelData(rpcLoad("org_nyc_permits"), orgId);
    if (!d) return null;
    const lo = Array.isArray(d.legally_operating) ? d.legally_operating : [];
    const dcwp = Array.isArray(d.dcwp) ? d.dcwp : [];
    const fhv = Array.isArray(d.tlc_fhv) ? d.tlc_fhv : [];
    const med = Array.isArray(d.tlc_medallions) ? d.tlc_medallions : [];
    const can = Array.isArray(d.cannabis) ? d.cannabis : [];
    const restos = Array.isArray(d.open_restaurants) ? d.open_restaurants : [];
    if (!lo.length && !dcwp.length && !fhv.length && !med.length && !can.length && !restos.length) return null;
    return (
      <Panel title="NYC business permits" badge={<SrcBadge bg="#e0e7ff" color="#3730a3">DCWP · TLC · OCM</SrcBadge>}>
        {lo.length > 0 && <Sub>Legally Operating Businesses ({lo.length})</Sub>}
        {lo.slice(0, 5).map((l, i) => {
          const active = l.license_status === "Active";
          return (
            <div key={"lo" + i} style={{ padding: "0 16px 8px" }}>
              <Field l="Business" v={<span>{l.business_name} {l.license_status && <Flag bg={active ? "#dcfce7" : "#fef3c7"} color={active ? "#166534" : "#92400e"}>{l.license_status}</Flag>}</span>} />
              <Field l="License #" v={l.license_nbr} mono />
              <Field l="Type" v={l.license_type} />
              <Field l="DBA" v={l.dba_trade_name} />
              <Field l="Created" v={fmtDate(l.license_creation_date)} />
              <Field l="Expires" v={fmtDate(l.license_expiration_date)} />
            </div>
          );
        })}
        {dcwp.length > 0 && <Sub>DCWP applications ({dcwp.length})</Sub>}
        {dcwp.slice(0, 3).map((a, i) => (
          <div key={"dc" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Application" v={a.application_id} />
            <Field l="License #" v={a.license_number} />
            <Field l="Business" v={a.business_name} />
            <Field l="Type" v={a.license_type} />
            <Field l="Status" v={a.status} />
            <Field l="Submitted" v={fmtDate(a.submission_date)} />
          </div>
        ))}
        {fhv.length > 0 && <Sub>TLC for-hire vehicles ({fhv.length})</Sub>}
        {fhv.slice(0, 3).map((t, i) => (
          <div key={"fhv" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Permit #" v={t.permit_license_number} />
            <Field l="Base" v={t.base_name} />
            <Field l="Base #" v={t.base_number} />
            <Field l="Type" v={t.base_type || t.license_type} />
            <Field l="Expires" v={fmtDate(t.expiration_date)} />
          </div>
        ))}
        {med.length > 0 && <Sub>TLC medallions ({med.length})</Sub>}
        {med.slice(0, 3).map((m, i) => (
          <div key={"md" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="License #" v={m.license_number} />
            <Field l="Name" v={m.name} />
            <Field l="Status" v={m.current_status} />
            <Field l="Type" v={m.medallion_type} />
            <Field l="Agent" v={m.agent_name} />
            <Field l="Expires" v={fmtDate(m.expiration_date)} />
          </div>
        ))}
        {can.length > 0 && <Sub>Cannabis licenses ({can.length})</Sub>}
        {can.slice(0, 3).map((c, i) => (
          <div key={"cn" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="License #" v={c.license_number} mono />
            <Field l="Type" v={c.license_type} />
            <Field l="Status" v={c.license_status} />
            <Field l="Operational" v={c.operational_status} />
            <Field l="DBA" v={c.dba} />
            <Field l="Tier" v={c.tier_type} />
            <Field l="Issued" v={fmtDate(c.issued_date)} />
            <Field l="Expires" v={fmtDate(c.expiration_date)} />
          </div>
        ))}
        {restos.length > 0 && <Sub>Outdoor dining permits ({restos.length})</Sub>}
        {restos.slice(0, 3).map((r, i) => (
          <div key={"or" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Restaurant" v={r.restaurant_name} />
            <Field l="Legal name" v={r.legal_business_name} />
            <Field l="Sidewalk" v={r.approved_for_sidewalk ? "Yes" : "No"} />
            <Field l="Roadway" v={r.approved_for_roadway ? "Yes" : "No"} />
            <Field l="Alcohol" v={r.qualify_alcohol ? "Yes" : "No"} />
          </div>
        ))}
        <div style={{ padding: "0 14px 12px" }}><Note>NYC DCWP, TLC, OCM and DOT permit registrations.</Note></div>
      </Panel>
    );
  };

  // Other gov registrations — SCA / IDA / ICAP / DMV / DEC / lottery / Green Book /
  // certified payroll / DCWP / active licenses / TLC / cannabis / dining / FL GP /
  // FL DABT / H-1B LCA.
  window.CrmPanels.otherreg = function OtherReg({ orgId }) {
    const d = usePanelData(rpcLoad("org_other_registrations"), orgId);
    if (!d) return null;
    const sca = Array.isArray(d.sca_prequalified) ? d.sca_prequalified : [];
    const icap = Array.isArray(d.icap) ? d.icap : [];
    const ida = Array.isArray(d.ida_projects) ? d.ida_projects : [];
    const lot = Array.isArray(d.lottery) ? d.lottery : [];
    const dmv = Array.isArray(d.dmv) ? d.dmv : [];
    const dec = Array.isArray(d.dec_pesticide) ? d.dec_pesticide : [];
    const gb = Array.isArray(d.greenbook) ? d.greenbook : [];
    const dcwp = Array.isArray(d.dcwp_licenses) ? d.dcwp_licenses : [];
    const legop = Array.isArray(d.legally_operating) ? d.legally_operating : [];
    const tlcF = Array.isArray(d.tlc_fhv) ? d.tlc_fhv : [];
    const tlcM = Array.isArray(d.tlc_medallions) ? d.tlc_medallions : [];
    const cannabis = Array.isArray(d.cannabis) ? d.cannabis : [];
    const openR = Array.isArray(d.open_restaurants) ? d.open_restaurants : [];
    const flPart = Array.isArray(d.fl_partnerships) ? d.fl_partnerships : [];
    const payroll = Array.isArray(d.nys_payroll) ? d.nys_payroll : [];
    const payrollTotal = Number(d.nys_payroll_total || 0);
    const lca = Array.isArray(d.h1b_lca) ? d.h1b_lca : [];
    const lcaTotal = Number(d.h1b_lca_total || 0);
    const dabt = Array.isArray(d.dabt) ? d.dabt : [];
    const dabtTotal = Number(d.dabt_total || 0);
    if (!sca.length && !icap.length && !ida.length && !lot.length && !dmv.length && !dec.length && !gb.length
      && !dcwp.length && !legop.length && !tlcF.length && !tlcM.length && !cannabis.length && !openR.length
      && !flPart.length && !payroll.length && !lca.length && !dabt.length) return null;
    return (
      <Panel title="Other gov registrations" badge={<SrcBadge bg="#f1f5f9" color="#475569">SCA · IDA · DMV · DEC</SrcBadge>}>
        {sca.length > 0 && <Sub>NYC SCA prequalified ({sca.length})</Sub>}
        {sca.slice(0, 3).map((s, i) => (
          <div key={"sca" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Trade" v={s.trade_description + (s.trade_code ? " (" + s.trade_code + ")" : "")} />
            <Field l="Vendor" v={s.vendor_name} />
            <Field l="Prequalified" v={fmtDate(s.prequalified_date)} />
            <Field l="MBE/WBE/LBE" v={[s.mbe === "Y" ? "MBE" : null, s.wbe === "Y" ? "WBE" : null, s.lbe === "Y" ? "LBE" : null].filter(Boolean).join(" · ") || null} />
            <Field l="$1M+ revenue" v={s.over_million_revenue === "Y" ? "Yes" : null} />
          </div>
        ))}
        {ida.length > 0 && <Sub>IDA projects ({ida.length})</Sub>}
        {ida.slice(0, 3).map((p, i) => (
          <div key={"ida" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Authority" v={p.authority_name} />
            <Field l="Project" v={p.project_name} />
            <Field l="Purpose" v={p.project_purpose} />
            <Field l="Total $" v={p.total_project_amount != null ? money(p.total_project_amount) : null} />
            <Field l="Bond/note" v={p.bond_note_amount != null ? money(p.bond_note_amount) : null} />
            <Field l="Annual lease" v={p.annual_lease_payment != null ? money(p.annual_lease_payment) : null} />
            <Field l="FY end" v={fmtDate(p.fiscal_year_end_date)} />
          </div>
        ))}
        {icap.length > 0 && <Sub>ICAP / industrial tax abatement ({icap.length})</Sub>}
        {icap.slice(0, 3).map((i2, i) => (
          <div key={"icap" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Date" v={fmtDate(i2.date)} />
            <Field l="Company" v={i2.contracting_company} />
            <Field l="Site" v={i2.site_address} />
            <Field l="Borough" v={i2.borough} />
          </div>
        ))}
        {dmv.length > 0 && <Sub>DMV facilities ({dmv.length})</Sub>}
        {dmv.slice(0, 3).map((f, i) => (
          <div key={"dmv" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Facility ID" v={f.facility_id} />
            <Field l="Name" v={f.facility_name} />
            <Field l="Type" v={f.business_type_label} />
            <Field l="Owner" v={f.owner_name} />
            <Field l="Issued" v={fmtDate(f.origional_issuance_date)} />
            <Field l="Expires" v={fmtDate(f.expiration_date)} />
          </div>
        ))}
        {dec.length > 0 && <Sub>Pesticide applicators ({dec.length})</Sub>}
        {dec.slice(0, 3).map((p, i) => (
          <div key={"dec" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Registration" v={p.registration_number} />
            <Field l="Category" v={p.pesticide_category_desc} />
            <Field l="Region" v={p.dec_region} />
            <Field l="Effective" v={fmtDate(p.registration_effective_date)} />
            <Field l="Expires" v={fmtDate(p.registration_expiration_date)} />
          </div>
        ))}
        {lot.length > 0 && <Sub>Lottery retailers ({lot.length})</Sub>}
        {lot.slice(0, 3).map((l, i) => (
          <div key={"lot" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Retailer ID" v={l.retailer_id} />
            <Field l="Name" v={l.name} />
            <Field l="Address" v={[l.street, l.city].filter(Boolean).join(", ")} />
          </div>
        ))}
        {gb.length > 0 && <Sub>NYC Green Book ({gb.length})</Sub>}
        {gb.slice(0, 5).map((g, i) => (
          <div key={"gb" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Agency" v={g.agency_name + (g.agency_acronym ? " (" + g.agency_acronym + ")" : "")} />
            <Field l="Division" v={g.division_name} />
            <Field l="Office title" v={g.office_title} />
            <Field l="Contact" v={[g.first_name, g.last_name].filter(Boolean).join(" ")} />
            <Field l="Phone" v={g.phone_1} />
          </div>
        ))}
        {payroll.length > 0 && <Sub>NYS certified payroll ({payrollTotal.toLocaleString()})</Sub>}
        {payroll.map((p, i) => (
          <div key={"pay" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Project" v={<span>{p.project_name || "Project"} {p.project_status && <Flag bg="#dcfce7" color="#0e7c66">{p.project_status}</Flag>}</span>} />
            <Field l="PRC #" v={p.prc_number} mono />
            <Field l="Work" v={p.work_category + (p.job_title ? " · " + p.job_title : "")} />
            <Field l="Site" v={[p.project_street_1, p.project_city, p.project_zipcode].filter(Boolean).join(", ")} />
            <Field l="Jurisdiction" v={p.department_of_jurisdiction} />
            <Field l="ST rate" v={p.st_hourly_rate != null ? "$" + Number(p.st_hourly_rate).toFixed(2) + "/hr" : null} />
            <Field l="Dates" v={[fmtDate(p.project_start_date), fmtDate(p.project_end_date)].filter(Boolean).join(" → ")} />
          </div>
        ))}
        {dcwp.length > 0 && <Sub>NYC DCWP licenses ({dcwp.length})</Sub>}
        {dcwp.slice(0, 5).map((l, i) => (
          <div key={"dcwp" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="License #" v={l.license_number} mono />
            <Field l="Business" v={l.business_name} />
            <Field l="Type" v={l.license_type + (l.business_category ? " · " + l.business_category : "")} />
            <Field l="Application" v={l.application_type} />
            <Field l="Status" v={l.status} />
            <Field l="Submitted" v={fmtDate(l.submission_date)} />
            <Field l="Closed" v={l.date_closed ? fmtDate(l.date_closed) : null} />
          </div>
        ))}
        {legop.length > 0 && <Sub>NYC active licenses ({legop.length})</Sub>}
        {legop.slice(0, 5).map((l, i) => (
          <div key={"leg" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="License #" v={l.license_nbr} mono />
            <Field l="Business" v={l.business_name + (l.dba_trade_name && l.dba_trade_name !== l.business_name ? " · DBA " + l.dba_trade_name : "")} />
            <Field l="Type" v={l.license_type + (l.business_category ? " · " + l.business_category : "")} />
            <Field l="Status" v={l.license_status} />
            <Field l="Phone" v={l.contact_phone} />
            <Field l="Address" v={[l.address, l.borough || l.city, l.zip].filter(Boolean).join(", ")} />
            <Field l="Expires" v={fmtDate(l.license_expiration_date)} />
          </div>
        ))}
        {tlcF.length > 0 && <Sub>NYC TLC FHV ({tlcF.length})</Sub>}
        {tlcF.slice(0, 5).map((t, i) => (
          <div key={"tlcf" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Base #" v={t.base_number} mono />
            <Field l="Base" v={t.base_name + (t.base_type ? " · " + t.base_type : "")} />
            <Field l="Phone" v={t.base_telephone} />
            <Field l="Website" v={t.website} />
            <Field l="Address" v={t.base_address} />
          </div>
        ))}
        {tlcM.length > 0 && <Sub>NYC TLC medallions ({tlcM.length})</Sub>}
        {tlcM.slice(0, 5).map((t, i) => (
          <div key={"tlcm" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="License #" v={t.license_number} mono />
            <Field l="Name" v={t.name} />
            <Field l="Status" v={t.current_status} />
            <Field l="Medallion" v={t.medallion_type} />
            <Field l="Vehicle" v={[t.vehicle_type, t.model_year].filter(Boolean).join(" · ")} />
            <Field l="Agent" v={t.agent_name} />
            <Field l="Expires" v={fmtDate(t.expiration_date)} />
          </div>
        ))}
        {cannabis.length > 0 && <Sub>NY cannabis licenses ({cannabis.length})</Sub>}
        {cannabis.slice(0, 5).map((c, i) => (
          <div key={"can" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="License #" v={c.license_number} mono />
            <Field l="Entity" v={c.entity_name + (c.dba ? " · DBA " + c.dba : "")} />
            <Field l="Type" v={c.license_type} />
            <Field l="Status" v={c.license_status + (c.operational_status ? " · " + c.operational_status : "")} />
            <Field l="Contact" v={c.primary_contact_name} />
            <Field l="Website" v={c.business_website} />
            <Field l="Purpose" v={c.business_purpose} />
            <Field l="Address" v={[c.address, c.city, c.county].filter(Boolean).join(", ")} />
            <Field l="Issued" v={fmtDate(c.issued_date)} />
          </div>
        ))}
        {openR.length > 0 && <Sub>NYC open restaurants ({openR.length})</Sub>}
        {openR.slice(0, 5).map((r, i) => (
          <div key={"openr" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Restaurant" v={r.restaurant_name + (r.legal_business_name && r.legal_business_name !== r.restaurant_name ? " · " + r.legal_business_name : "")} />
            <Field l="Address" v={[r.business_address, r.borough].filter(Boolean).join(", ")} />
            <Field l="Sidewalk" v={r.approved_for_sidewalk === "yes" ? "Yes" : null} />
            <Field l="Roadway" v={r.approved_for_roadway === "yes" ? "Yes" : null} />
            <Field l="Alcohol" v={r.qualify_alcohol || null} />
          </div>
        ))}
        {flPart.length > 0 && <Sub>FL general partnerships ({flPart.length})</Sub>}
        {flPart.slice(0, 5).map((p, i) => (
          <div key={"flp" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Name" v={p.gr_name} />
            <Field l="Address" v={p.address} />
          </div>
        ))}
        {dabt.length > 0 && <Sub>FL alcohol &amp; tobacco licenses ({dabtTotal})</Sub>}
        {dabt.map((b, i) => (
          <div key={"dabt" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Name" v={<span>{b.business_dba_name || b.owner_primary_name || "License"} {b.profession_label || b.profession_code ? <Flag bg="#dcfce7" color="#0e7c66">{b.profession_label || b.profession_code}</Flag> : null} {b.primary_status_code === "20" ? <Flag bg="#dcfce7" color="#0e7c66">Active</Flag> : (b.primary_status_code ? <Flag bg="#f1f5f9" color="#475569">{b.primary_status_code}</Flag> : null)}</span>} />
            <Field l="License #" v={b.license_number} mono />
            <Field l="Owner" v={b.owner_primary_name} />
            <Field l="Series" v={b.series_rank} />
            <Field l="Address" v={[b.loc_address, b.loc_city, b.loc_state, b.loc_zip].filter(Boolean).join(", ")} />
            <Field l="Issued" v={b.original_issue_date ? fmtDate(b.original_issue_date) : null} />
            <Field l="Expires" v={b.expiration_date ? fmtDate(b.expiration_date) : null} />
          </div>
        ))}
        {lca.length > 0 && <Sub>H-1B LCA filings ({lcaTotal})</Sub>}
        {lca.map((l, i) => (
          <div key={"lca" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Position" v={<span>{l.job_title || l.soc_title || "H-1B position"} {l.case_status && <Flag bg="#dcfce7" color="#0e7c66">{l.case_status}</Flag>} {l.visa_class && <Flag bg="#f1f5f9" color="#475569">{l.visa_class}</Flag>}</span>} />
            <Field l="Case #" v={l.case_number} mono />
            <Field l="SOC" v={l.soc_title} />
            <Field l="Workers" v={l.total_workers != null ? num(l.total_workers) : null} />
            <Field l="Period" v={[fmtDate(l.begin_date), fmtDate(l.end_date)].filter(Boolean).join(" → ")} />
            <Field l="Decision" v={fmtDate(l.decision_date)} />
            <Field l="Employer" v={l.employer_name} />
            <Field l="POC" v={[l.employer_poc_first_name, l.employer_poc_last_name].filter(Boolean).join(" ") + (l.employer_poc_title ? " · " + l.employer_poc_title : "")} />
            <Field l="POC email" v={l.employer_poc_email} />
            <Field l="POC phone" v={l.employer_poc_phone} />
            <Field l="Attorney firm" v={l.agent_attorney_firm} />
            <Field l="Worksite" v={[l.worksite_city, l.worksite_state, l.worksite_postal_code].filter(Boolean).join(", ")} />
            <Field l="Wage" v={l.wage_rate_of_pay_from != null ? "$" + Number(l.wage_rate_of_pay_from).toLocaleString() + (l.wage_rate_of_pay_to ? "–$" + Number(l.wage_rate_of_pay_to).toLocaleString() : "") + " / " + (l.wage_unit_of_pay || "") : null} />
            <Field l="Prevailing wage" v={l.prevailing_wage != null ? "$" + Number(l.prevailing_wage).toLocaleString() + " / " + (l.pw_unit_of_pay || "") : null} />
          </div>
        ))}
        <div style={{ padding: "0 14px 12px" }}><Note>State &amp; city agency registrations across NY and FL.</Note></div>
      </Panel>
    );
  };

  // NY assumed names (DBA) — NYS Certificate of Assumed Name + amendments + discontinuances.
  window.CrmPanels.nydba = function NyDba({ orgId }) {
    const d = usePanelData(rpcLoad("org_ny_dba_list"), orgId);
    if (!d) return null;
    const dbas = Array.isArray(d.dbas) ? d.dbas : [];
    if (!dbas.length) return null;
    const initial = dbas.filter((x) => x.documenttype === "CERTIFICATE OF ASSUMED NAME");
    const amended = dbas.filter((x) => x.documenttype === "CERTIFICATE OF ASSUMED NAME AMENDMENT");
    const disc = dbas.filter((x) => x.documenttype === "CERTIFICATE OF ASSUMED NAME DISCONTINUANCE");
    return (
      <Panel title="NY assumed names (DBA)" badge={<SrcBadge bg="#ddd6fe" color="#5b21b6">NYS DOS</SrcBadge>} count={dbas.length}>
        {initial.length > 0 && <Sub>Doing Business As ({initial.length})</Sub>}
        {initial.map((b, i) => (
          <div key={"in" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="DBA name" v={<strong>{b.corp_name}</strong>} />
            <Field l="Filing #" v={b.film_num} mono />
            <Field l="Entity type" v={b.entitytype} />
            <Field l="Filed" v={fmtDate(b.date_filed)} />
            <Field l="Effective" v={fmtDate(b.eff_date)} />
            <Field l="Duration" v={b.dura_date} />
          </div>
        ))}
        {amended.length > 0 && <Sub>Amendments ({amended.length})</Sub>}
        {amended.map((b, i) => (
          <div key={"am" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Amended DBA" v={b.corp_name} />
            <Field l="Filed" v={fmtDate(b.date_filed)} />
            <Field l="Filing #" v={b.film_num} mono />
          </div>
        ))}
        {disc.length > 0 && <Sub>Discontinued ({disc.length})</Sub>}
        {disc.map((b, i) => (
          <div key={"di" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Discontinued DBA" v={b.corp_name} />
            <Field l="Filed" v={fmtDate(b.date_filed)} />
          </div>
        ))}
        <div style={{ padding: "0 14px 12px" }}><Note>NYS Certificate of Assumed Name filings.</Note></div>
      </Panel>
    );
  };

  // Trade names & DBAs — FL fictitious-name registrations (Sunbiz).
  window.CrmPanels.tradenames = function TradeNames({ orgId }) {
    const d = usePanelData(rpcLoad("org_trade_names"), orgId);
    if (!d) return null;
    const f = Array.isArray(d.fictitious) ? d.fictitious : [];
    if (!f.length) return null;
    return (
      <Panel title="Trade names & DBAs" badge={<SrcBadge bg="#ddd6fe" color="#5b21b6">Sunbiz</SrcBadge>} count={f.length}>
        <div style={{ padding: "6px 16px 0" }}>
          {f.slice(0, 10).map((n, i) => {
            const active = n.status === "A";
            return (
              <div key={i} style={{ marginBottom: 8 }}>
                <Field l="Name" v={<span>{n.fictitious_name} <Flag bg={active ? "#dcfce7" : "#fef3c7"} color={active ? "#166534" : "#92400e"}>{active ? "Active" : (n.status || "Inactive")}</Flag></span>} />
                <Field l="Doc #" v={n.document_number} mono />
                <Field l="County" v={n.county} />
                <Field l="Filed" v={fmtDate(n.filing_date)} />
                <Field l="Expires" v={fmtDate(n.expiration_date)} />
                <Field l="Cancelled" v={n.cancellation_date ? fmtDate(n.cancellation_date) : null} />
              </div>
            );
          })}
        </div>
        <div style={{ padding: "0 14px 12px" }}><Note>{f.length} name{f.length > 1 ? "s" : ""} · FL Sunbiz fictitious-name registry.</Note></div>
      </Panel>
    );
  };

  // FL professional licenses — DBPR licenses + premises.
  window.CrmPanels.fllic = function FlLicenses({ orgId }) {
    const d = usePanelData(rpcLoad("org_fl_licenses"), orgId);
    if (!d) return null;
    const licenses = Array.isArray(d.licenses) ? d.licenses : [];
    const premises = Array.isArray(d.premises) ? d.premises : [];
    if (!licenses.length && !premises.length) return null;
    return (
      <Panel title="FL professional licenses" badge={<SrcBadge bg="#fef3c7" color="#92400e">DBPR</SrcBadge>} count={licenses.length + premises.length}>
        {licenses.length > 0 && <Sub>Licenses ({licenses.length})</Sub>}
        {licenses.slice(0, 10).map((l, i) => {
          const active = ["CURR", "Current", "A"].includes(l.primary_status);
          return (
            <div key={"lic" + i} style={{ padding: "0 16px 8px" }}>
              <Field l="Division" v={<span>{l.division || "License"} {l.primary_status && <Flag bg={active ? "#dcfce7" : "#fef3c7"} color={active ? "#166534" : "#92400e"}>{l.primary_status}</Flag>}</span>} />
              <Field l="License #" v={l.license_number} mono />
              <Field l="Licensee" v={l.licensee_name} />
              <Field l="DBA" v={l.dba_name} />
              <Field l="Issued" v={fmtDate(l.original_license_date)} />
              <Field l="Expires" v={fmtDate(l.expiration_date)} />
            </div>
          );
        })}
        {premises.length > 0 && <Sub>Premises ({premises.length})</Sub>}
        {premises.slice(0, 5).map((p, i) => (
          <div key={"prm" + i} style={{ padding: "0 16px 8px" }}>
            <Field l="Business" v={p.business_name} />
            <Field l="License" v={[p.license_type_code, p.license_number].filter(Boolean).join(" · #")} mono />
            <Field l="Address" v={[p.location_address_1, p.location_city, p.location_state, p.location_zip].filter(Boolean).join(", ")} />
            <Field l="Last inspection" v={fmtDate(p.last_inspection_date)} />
            <Field l="Expires" v={fmtDate(p.expiration_date)} />
          </div>
        ))}
        <div style={{ padding: "0 14px 12px" }}><Note>FL Dept. of Business &amp; Professional Regulation licenses.</Note></div>
      </Panel>
    );
  };
})();
