/* CRM · Account — sixth 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 data
 * 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. Registered aircraft — FAA registry (renderDossierAircraft, RPC org_aircraft).
  // Returns a flat array of aircraft rows; guard = rows.length.
  window.CrmPanels.aircraft = function Aircraft({ orgId }) {
    const rows = usePanelData(rpcLoad("org_aircraft"), orgId);
    if (!rows || !rows.length) return null;
    return (
      <Panel title="Registered aircraft" badge={<SrcBadge bg="#dbeafe" color="#1e40af">FAA</SrcBadge>}
        count={rows.length + (rows.length === 50 ? "+" : "") + " aircraft"}>
        <div className="reg-panel">
          {rows.slice(0, 12).map((r, i) => (
            <RegRow key={i} badge="N" badgeBg="#1e40af"
              title={"N" + (r.n_number || "")}
              fact={[r.year_mfr || null, r.type_registrant_label || null, [r.city, r.state].filter(Boolean).join(", ") || null].filter(Boolean).join(" · ")}
              right={r.expiration_date || null} />
          ))}
        </div>
        <div style={{ padding: "0 14px 12px" }}><Note>FAA aircraft registry — tail number, year of manufacture, owner type, registration location.</Note></div>
      </Panel>
    );
  };

  // 2. FCC licenses — FCC ULS (renderDossierFcc). Map fetches RPC org_fcc_licenses
  // (NOT org_fcc); returns a flat array of license rows; guard = rows.length.
  window.CrmPanels.fcc = function Fcc({ orgId }) {
    const rows = usePanelData(rpcLoad("org_fcc_licenses"), orgId);
    if (!rows || !rows.length) return null;
    const SVC = { CL: "Cellular", LP: "Private LM", LC: "Commercial LM", MW: "Microwave", PG: "Paging", BL: "Broadcast Aux", MK: "Market-based", AM: "Amateur", CS: "Coastal", SH: "Ship" };
    const byService = {};
    rows.forEach((r) => { byService[r.service_code] = (byService[r.service_code] || 0) + 1; });
    const chips = Object.entries(byService).map(([code, n]) => <Flag key={code} bg="#fae8ff" color="#86198f">{(SVC[code] || code) + ": " + n}</Flag>);
    return (
      <Panel title="FCC licenses" badge={<SrcBadge bg="#fae8ff" color="#86198f">FCC ULS</SrcBadge>} count={rows.length}>
        <div style={{ padding: "10px 16px 0", display: "flex", gap: 6, flexWrap: "wrap" }}>{chips}</div>
        <div className="reg-panel">
          {rows.slice(0, 12).map((r, i) => (
            <RegRow key={i} badge={r.service_code || "FCC"} badgeBg="#86198f"
              title={r.call_sign || "—"}
              fact={[SVC[r.service_code] || r.service_code || null, r.frn ? "FRN " + r.frn : null, [r.city, r.state].filter(Boolean).join(", ") || null].filter(Boolean).join(" · ")} />
          ))}
        </div>
        <div style={{ padding: "0 14px 12px" }}><Note>FCC Universal Licensing System — call sign, radio service, FRN, location.</Note></div>
      </Panel>
    );
  };

  // 3. UK company — UK Companies House (renderDossierUkCompany). Live on-demand
  // edge-fn GET enrich-uk-companies?org_id=…; guard = d.company_number. Shows
  // active officers, persons with significant control (PSC), and registered charges.
  window.CrmPanels.ukco = function UkCompany({ orgId }) {
    const d = usePanelData(fnGet("/functions/v1/enrich-uk-companies"), orgId);
    if (!d || !d.company_number) return null;
    const officers = (d.officers || []).filter((o) => !o.resigned);
    const psc = (d.psc || []).filter((p) => !p.ceased);
    const flags = [];
    if (d.status) flags.push(<Flag key="st" bg={d.status === "active" ? "#dcfce7" : "#f1f5f9"} color={d.status === "active" ? "#166534" : "#64748b"}>{d.status}</Flag>);
    if (d.charges_count) flags.push(<Flag key="ch" bg="#fee2e2" color="#991b1b">{d.charges_count + " charge" + (d.charges_count > 1 ? "s" : "")}</Flag>);
    return (
      <Panel title="UK company" badge={<SrcBadge bg="#dbeafe" color="#1e3a8a">CO HOUSE</SrcBadge>}>
        <div style={{ padding: "6px 16px 14px" }}>
          <Field l="Company #" v={d.company_number} mono />
          {d.incorporated && <Field l="Incorporated" v={String(d.incorporated).slice(0, 4)} />}
          {flags.length > 0 && <Field l="Status" v={<span style={{ display: "inline-flex", gap: 4, flexWrap: "wrap" }}>{flags}</span>} />}
          {d.address && <Field l="Address" v={d.address} />}
          {psc.length > 0 && (
            <div style={{ marginTop: 8 }}>
              <div style={{ fontSize: "var(--fs-sm)", color: "var(--fg-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>Beneficial owners (PSC)</div>
              {psc.map((p, i) => (
                <div key={i} style={{ fontSize: "var(--fs-base)", color: "var(--fg-2)", marginTop: 3 }}>
                  <span style={{ fontWeight: 600, color: "#1e3a8a" }}>★ {p.name}</span> <span style={{ color: "var(--fg-3)" }}>({p.kind})</span>
                  {p.controls && p.controls.length > 0 && <div style={{ color: "var(--fg-3)", marginLeft: 12 }}>{p.controls.join(" · ")}</div>}
                  {p.reg && <div style={{ color: "var(--fg-3)", marginLeft: 12 }}>{p.reg}</div>}
                </div>
              ))}
            </div>
          )}
          {officers.length > 0 && (
            <div style={{ marginTop: 8 }}>
              <div style={{ fontSize: "var(--fs-sm)", color: "var(--fg-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>Officers ({officers.length})</div>
              {officers.slice(0, 12).map((o, i) => (
                <div key={i} style={{ fontSize: "var(--fs-base)", color: "var(--fg-2)", marginTop: 2 }}>
                  <span style={{ fontWeight: 600, color: "var(--fg-1)" }}>{o.name}</span> · {o.role || ""}{o.nationality ? " · " + o.nationality : ""}{o.dob ? " · b." + o.dob : ""}
                </div>
              ))}
            </div>
          )}
          <Note>UK Companies House — officers, persons with significant control, and registered charges.</Note>
        </div>
      </Panel>
    );
  };

  // 4. Relationships — LittleSis (renderDossierLittleSis). Live on-demand edge-fn
  // GET enrich-littlesis?org_id=…; guard = d.ls_entity_id && relationships.length.
  window.CrmPanels.littlesis = function LittleSis({ orgId }) {
    const d = usePanelData(fnGet("/functions/v1/enrich-littlesis"), orgId);
    if (!d || !d.ls_entity_id || !(d.relationships || []).length) return null;
    const rels = (d.relationships || []).slice(0, 25);
    return (
      <Panel title="Relationships" badge={<SrcBadge bg="#fae8ff" color="#86198f">LITTLESIS</SrcBadge>}>
        <div style={{ padding: "6px 16px 4px" }}>
          {d.blurb && <Note>{d.blurb}</Note>}
        </div>
        <div className="reg-panel">
          {rels.map((r, i) => {
            const cat = r.category && !/^\d+$/.test(String(r.category)) ? r.category : null;
            return (
              <RegRow key={i}
                title={<>{r.text}{r.amount ? <span style={{ color: "#166534", fontWeight: 600 }}> ${Number(r.amount).toLocaleString()}</span> : null}{cat ? <span style={{ marginLeft: 6 }}><Flag bg="#fae8ff" color="#86198f">{cat}</Flag></span> : null}</>} />
            );
          })}
        </div>
        <div style={{ padding: "0 14px 12px" }}>
          <Note>LittleSis — who-knows-who of power: owners, board, subsidiaries, business ties.</Note>
        </div>
      </Panel>
    );
  };

  // 5. SBA PPP loans — renderDossierPpp, RPC org_ppp_loans → { loans:[] }.
  window.CrmPanels.ppp = function Ppp({ orgId }) {
    const d = usePanelData(rpcLoad("org_ppp_loans"), orgId);
    const loans = (d && d.loans) || [];
    if (!loans.length) return null;
    const total = loans.reduce((s, l) => s + Number(l.initial_approval_amount || 0), 0);
    return (
      <Panel title="SBA PPP loans" badge={<SrcBadge bg="#dcfce7" color="#166534">SBA</SrcBadge>}
        count={loans.length + " loan" + (loans.length > 1 ? "s" : "") + " · " + money(total) + " total"}>
        <div className="reg-panel">
          {loans.slice(0, 10).map((l, i) => {
            const fpct = l.forgiveness_amount && l.initial_approval_amount ? Math.round(100 * Number(l.forgiveness_amount) / Number(l.initial_approval_amount)) : null;
            const paid = l.loan_status === "Paid in Full";
            return (
              <RegRow key={i} badge={money(l.initial_approval_amount)} badgeBg={paid ? "#059669" : "#b45309"}
                title={<>{l.borrower_name || ""} <span style={{ marginLeft: 4 }}><Flag bg={(paid ? "#059669" : "#b45309") + "18"} color={paid ? "#059669" : "#b45309"}>{l.loan_status || "Unknown"}</Flag></span></>}
                fact={[
                  l.forgiveness_amount != null ? "Forgiven " + money(l.forgiveness_amount) + (fpct != null ? " (" + fpct + "%)" : "") : null,
                  l.jobs_reported ? num(l.jobs_reported) + " jobs" : null,
                  l.servicing_lender_name ? "Lender " + l.servicing_lender_name : null,
                  l.naics_code ? "NAICS " + l.naics_code : null,
                ].filter(Boolean).join(" · ")}
                right={[l.state, fmtDate(l.date_approved)].filter(Boolean).join(" · ") || null} />
            );
          })}
        </div>
        <div style={{ padding: "0 14px 12px" }}><Note>SBA Paycheck Protection Program loan disbursements.</Note></div>
      </Panel>
    );
  };

  // 6. IRS Form 990 — renderDossierIrs990, RPC org_irs_990 → { filings:[] }.
  window.CrmPanels.irs990 = function Irs990({ orgId }) {
    const d = usePanelData(rpcLoad("org_irs_990"), orgId);
    const filings = (d && d.filings) || [];
    if (!filings.length) return null;
    return (
      <Panel title="IRS Form 990" badge={<SrcBadge bg="#e0e7ff" color="#3730a3">IRS</SrcBadge>}
        count={filings.length + " filing" + (filings.length > 1 ? "s" : "")}>
        <div className="reg-panel">
          {filings.slice(0, 5).map((f, i) => {
            const officers = (f.officers || []).slice(0, 3);
            return (
              <div className="reg-row" key={i} style={{ alignItems: "flex-start" }}>
                <span className="reg-badge" style={{ background: "#3730a3" }}>{f.return_type || "990"}</span>
                <div className="reg-main">
                  <div className="reg-title" style={{ whiteSpace: "normal" }}>{"Form " + (f.return_type || "")} <span style={{ color: "var(--fg-3)", fontSize: 10, fontWeight: 400 }}>FY end {fmtDate(f.tax_period_end_date)}</span></div>
                  <div className="reg-fact" style={{ whiteSpace: "normal" }}>
                    {[
                      f.total_revenue != null ? "Revenue " + money(f.total_revenue) : null,
                      f.total_expenses != null ? "Expenses " + money(f.total_expenses) : null,
                      f.total_assets_eoy != null ? "Assets " + money(f.total_assets_eoy) : null,
                      f.net_assets_eoy != null ? "Net assets " + money(f.net_assets_eoy) : null,
                      f.num_employees != null ? num(f.num_employees) + " employees" : null,
                      f.ein ? "EIN " + f.ein : null,
                    ].filter(Boolean).join(" · ")}
                  </div>
                  {f.mission_text && <div style={{ fontSize: "var(--fs-sm)", color: "var(--fg-2)", marginTop: 6, paddingTop: 6, borderTop: "1px solid var(--border)" }}>{f.mission_text}</div>}
                  {officers.length > 0 && (
                    <div style={{ marginTop: 6 }}>
                      <div style={{ fontSize: "var(--fs-sm)", color: "var(--fg-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 2 }}>Officers</div>
                      {officers.map((o, j) => (
                        <div key={j} style={{ fontSize: "var(--fs-base)", color: "var(--fg-1)", padding: "1px 0" }}>{o.name || "—"}{o.title ? <span style={{ color: "var(--fg-3)", fontSize: "var(--fs-sm)" }}> {o.title}</span> : null}</div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ padding: "0 14px 12px" }}><Note>IRS Form 990 — non-profit annual returns (revenue, assets, officers).</Note></div>
      </Panel>
    );
  };
})();
