---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import {
  getSupplierProfile,
  getSupplierContracts,
  getCpvBreakdown,
  getTopCounterparts,
  getDailyHeatmap,
  getCountyDistribution,
  getSupplierKpi,
  getFirmDetails,
  getFirmFinancials,
  getEuFundsBeneficiarStatus,
  getRegasStatus,
  getAepStatus,
  getAnafDebtStatus,
} from '../../lib/profile-queries.js';
import {
  getAnreStatus,
  getAncomStatus,
  getCnscStatus,
  getBugetarStatus,
} from '../../lib/profile-queries-utilities.js';
import {
  getAsfStatus,
  getAaasStatus,
  getCurteaContStatus,
} from '../../lib/profile-queries-financial.js';
import { CalendarHeatmap } from '../../components/profile/CalendarHeatmap';
import { CountyBars } from '../../components/profile/CountyBars';
import { FinancialTimeline } from '../../components/profile/FinancialTimeline';
import '../../components/profile/profile.css';

export const prerender = false;

const cuiRaw = Astro.params.cui as string;
const cui = cuiRaw.replace(/^RO\s*/i, '').trim();

const [
  seapProfile, contracts, cpv, buyers, heatmap, counties, kpi,
  firmDetails, financials,
  euFunds, regas, aep, anafDebt,
  anre, ancom, cnsc,
  asf, aaas, cdc, bugetar,
] = await Promise.all([
  getSupplierProfile(cui),
  getSupplierContracts(cui, 30, 0),
  getCpvBreakdown('supplier', cui),
  getTopCounterparts('supplier', cui, 10),
  getDailyHeatmap('supplier', cui),
  getCountyDistribution('supplier', cui),
  getSupplierKpi(cui),
  getFirmDetails(cui),
  getFirmFinancials(cui),
  getEuFundsBeneficiarStatus(cui),
  getRegasStatus(cui),
  getAepStatus(cui),
  getAnafDebtStatus(cui),
  getAnreStatus(cui),
  getAncomStatus(cui),
  getCnscStatus(cui),
  getAsfStatus(cui),
  getAaasStatus(cui),
  getCurteaContStatus(cui),
  getBugetarStatus(cui),
]);

// Firms now exists for ANY RO CUI (3.97M from ONRC); SEAP profile only for active suppliers.
// Build a unified profile preferring firmDetails (richer) and falling back to SEAP data for name/county.
if (!seapProfile && !firmDetails) {
  return Astro.redirect('/404');
}

const profile = seapProfile || {
  cui,
  name: firmDetails!.name,
  county: firmDetails!.adr_judet,
  address: firmDetails!.adr_full,
  email: null,
  phone: null,
  url: firmDetails!.web,
  is_sme: null,
  contracts_won: 0,
  total_awarded: 0,
  avg_contract: null,
  first_contract_date: null,
  last_contract_date: null,
  distinct_buyers: 0,
};

const fmt = (n: number | null | undefined) => n == null ? '–' : new Intl.NumberFormat('ro-RO', { maximumFractionDigits: 0 }).format(n);
const fmtRon = (v: number | null | undefined) => {
  if (v == null) return '–';
  if (v >= 1_000_000_000) return `${(v / 1_000_000_000).toFixed(1)} mld`;
  if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)} mil`;
  if (v >= 1_000) return `${(v / 1_000).toFixed(0)}K`;
  return Math.round(v).toString();
};
const dateFmt = (d: string | null) => d ? new Date(d).toLocaleDateString('ro-RO', { year: 'numeric', month: 'short' }) : '–';

const totalAwarded = Number(profile.total_awarded) || 0;
const dependencyTone = kpi.top_buyer_share > 0.50 ? 'risk' : kpi.top_buyer_share > 0.30 ? 'warn' : 'ok';
const cpvDiversityTone = kpi.cpv_diversity > 2.5 ? 'warn' : 'ok'; // high entropy = heterogeneous = front-company candidate
const growthHint = kpi.growth_yoy == null ? '–' :
  kpi.growth_yoy > 0 ? `+${(kpi.growth_yoy * 100).toFixed(0)}% vs anul precedent` :
  `${(kpi.growth_yoy * 100).toFixed(0)}% vs anul precedent`;

// Auto-dossier generation
function dossier(): string {
  const parts: string[] = [];
  parts.push(`<strong>${profile!.name}</strong> a încasat ${fmtRon(totalAwarded)} RON din ${fmt(profile!.contracts_won)} anunțuri câștigate cu ${fmt(profile!.distinct_buyers)} autorități contractante`);
  if (profile!.first_contract_date) {
    parts[parts.length - 1] += ` între ${dateFmt(profile!.first_contract_date)} și ${dateFmt(profile!.last_contract_date)}`;
  }
  parts[parts.length - 1] += '.';

  if (kpi.geo_footprint > 0) {
    parts.push(`Activează în <strong>${fmt(kpi.geo_footprint)} județe</strong>${cpv.length > 0 ? `, pe ${cpv.length} categorii CPV` : ''}.`);
  }

  if (kpi.top_buyer_share > 0.30) {
    parts.push(`Concentrare ridicată: <strong>${(kpi.top_buyer_share * 100).toFixed(0)}%</strong> din venit vine de la o singură autoritate.`);
  }

  return parts.join(' ');
}
---

<AchizitiiLayout
  title={`${profile.name} — Profil furnizor · vreaudigital.ro`}
  description={`${profile.name} (CUI ${profile.cui}): ${profile.contracts_won} anunțuri câștigate, ${fmtRon(totalAwarded)} RON valoare.`}
  ogImage={`/api/og/firma/${profile.cui}.png`}
>
  <main class="max-w-content mx-auto px-4 py-6">

    <!-- Header card -->
    <div class="profile-header">
      <div class="profile-header-flag-strip" />
      <div class="flex items-start gap-4">
        <div class="profile-icon">🏭</div>
        <div class="flex-1 min-w-0">
          <h1 class="profile-name">{profile.name}</h1>
          <div class="profile-subline">
            <span class="badge font-mono">CUI {profile.cui}</span>
            {firmDetails?.forma_juridica && <span class="badge badge-stamp">{firmDetails.forma_juridica}</span>}
            {firmDetails?.cod_inmatriculare && <span class="badge font-mono">{firmDetails.cod_inmatriculare}</span>}
            {profile.county && <span class="badge">📍 {profile.county}</span>}
            {firmDetails?.is_radiated_onrc && <span class="badge badge-signal">⚠ Radiată ONRC</span>}
            {profile.is_sme === true && <span class="badge badge-state">IMM</span>}
            {euFunds && <span class="badge badge-state">🇪🇺 beneficiar EU · {euFunds.anunturi} anunț{euFunds.anunturi === 1 ? '' : 'uri'}</span>}
            {regas && <span class="badge badge-state">🏛️ ajutor de stat · {regas.nr_ajutoare} {regas.nr_ajutoare === 1 ? 'ajutor' : 'ajutoare'} · {fmtRon(regas.total_ron)} RON</span>}
            {aep && <span class="badge badge-state">🗳️ donator partide · {aep.nr_donatii} donații · {fmtRon(aep.total_lei)} RON</span>}
            {anafDebt && <span class="badge badge-signal">🚨 datornic ANAF {anafDebt.period_label} · {fmtRon(anafDebt.debt_total)} RON</span>}
            {anre && anre.nr_active > 0 && <span class="badge badge-state">🔌 licență ANRE · {anre.nr_active} {anre.nr_active === 1 ? 'activă' : 'active'}{anre.surse.length > 0 ? ` · ${anre.surse.join(', ')}` : ''}</span>}
            {ancom && <span class="badge badge-state">📡 furnizor ANCOM · {ancom.nr_autorizatii} {ancom.nr_autorizatii === 1 ? 'autorizație' : 'autorizații'}{ancom.servicii.length > 0 ? ` · ${ancom.servicii.slice(0, 4).join('/')}` : ''}</span>}
            {cnsc?.asAuthority && <span class="badge badge-signal">⚖️ {cnsc.asAuthority.contestation_count} contestaț{cnsc.asAuthority.contestation_count === 1 ? 'ie' : 'ii'} CNSC (autoritate)</span>}
            {cnsc?.asContestator && <span class="badge badge-state">⚖️ {cnsc.asContestator.contestations_filed} contestaț{cnsc.asContestator.contestations_filed === 1 ? 'ie' : 'ii'} CNSC (contestator)</span>}
            {asf && (
              <span class={`badge ${asf.has_radiat && !asf.has_active ? 'badge-signal' : 'badge-state'}`}>
                💰 ASF {asf.register_numbers[0] || '—'}
                {asf.register_types.length > 0 && <> · {asf.register_types.join('/')}</>}
                <> · {asf.nr_active}/{asf.nr_total} active</>
                {asf.has_radiat && asf.has_active && <> · {asf.nr_radiate} radiat{asf.nr_radiate === 1 ? 'ă' : 'e'}</>}
                {asf.has_radiat && !asf.has_active && <> · radiat{asf.nr_radiate === 1 ? 'ă' : 'e'}</>}
              </span>
            )}
            {aaas && (
              <span class={`badge ${aaas.statusuri.includes('post_priv_debt') || aaas.statusuri.includes('insolventa') ? 'badge-signal' : 'badge-state'}`}>
                🏛️ stat acționar
                {aaas.max_state_share_pct != null && <> · {Number(aaas.max_state_share_pct).toFixed(1)}%</>}
                <> · {aaas.statusuri.join(', ')}</>
              </span>
            )}
            {cdc && cdc.nr_total > 0 && (
              <span class="badge badge-state">
                📋 audited Curtea Conturi · {cdc.nr_total} rapoart{cdc.nr_total === 1 ? 'e' : 'e'}
                {cdc.nr_fuzzy > 0 && cdc.nr_direct === 0 && <> *</>}
              </span>
            )}
            {bugetar && (
              <span class="badge badge-state">
                📊 raportor MFP · {bugetar.sector_label}{bugetar.is_ordonator_principal ? ' (ordonator principal)' : ''}
              </span>
            )}
          </div>
          <div class="profile-dossier" set:html={dossier()} />

          {firmDetails && (
            <div class="profile-firm-meta" style="margin-top: 14px;">
              {firmDetails.adr_full && (
                <div class="profile-firm-meta-item">
                  <div class="profile-firm-meta-label">Sediu social</div>
                  <div class="profile-firm-meta-value">{firmDetails.adr_full}</div>
                </div>
              )}
              {firmDetails.data_inmatriculare && (
                <div class="profile-firm-meta-item">
                  <div class="profile-firm-meta-label">Înmatriculată</div>
                  <div class="profile-firm-meta-value">{new Date(firmDetails.data_inmatriculare).toLocaleDateString('ro-RO', { year: 'numeric', month: 'long', day: 'numeric' })}</div>
                </div>
              )}
              {firmDetails.caen_count > 0 && (
                <div class="profile-firm-meta-item">
                  <div class="profile-firm-meta-label">CAEN autorizate</div>
                  <div class="profile-firm-meta-value">{firmDetails.caen_count} coduri</div>
                </div>
              )}
              {firmDetails.web && (
                <div class="profile-firm-meta-item">
                  <div class="profile-firm-meta-label">Site</div>
                  <div class="profile-firm-meta-value"><a href={firmDetails.web.startsWith('http') ? firmDetails.web : `https://${firmDetails.web}`} target="_blank" rel="noopener" class="text-stamp">{firmDetails.web}</a></div>
                </div>
              )}
              {firmDetails.tara_firma_mama && (
                <div class="profile-firm-meta-item">
                  <div class="profile-firm-meta-label">Firmă mamă</div>
                  <div class="profile-firm-meta-value">{firmDetails.tara_firma_mama}</div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>

    <!-- KPI strip -->
    <div class="profile-kpi-strip">
      <div class="profile-kpi">
        <div class="profile-kpi-label">Valoare totală</div>
        <div class="profile-kpi-value">{fmtRon(totalAwarded)} <span style="font-size:12px;color:var(--meta);font-weight:500;">RON</span></div>
        <div class="profile-kpi-hint">{fmt(profile.contracts_won)} anunțuri</div>
      </div>
      <div class="profile-kpi" data-tone={dependencyTone}>
        <div class="profile-kpi-label">Dependență top cumpărător</div>
        <div class="profile-kpi-value">{(kpi.top_buyer_share * 100).toFixed(0)}%</div>
        <div class="profile-kpi-hint">{dependencyTone === 'risk' ? '⚠ concentrare ridicată' : dependencyTone === 'warn' ? 'concentrare moderată' : 'distribuit'}</div>
      </div>
      <div class="profile-kpi">
        <div class="profile-kpi-label">Acoperire geografică</div>
        <div class="profile-kpi-value">{fmt(kpi.geo_footprint)}</div>
        <div class="profile-kpi-hint">județe</div>
      </div>
      <div class="profile-kpi" data-tone={cpvDiversityTone}>
        <div class="profile-kpi-label">Diversitate CPV (Shannon)</div>
        <div class="profile-kpi-value">{kpi.cpv_diversity.toFixed(2)}</div>
        <div class="profile-kpi-hint">{cpvDiversityTone === 'warn' ? 'heterogen — verifică' : 'specializat'}</div>
      </div>
      <div class="profile-kpi">
        <div class="profile-kpi-label">Trend YoY</div>
        <div class="profile-kpi-value">{kpi.growth_yoy == null ? '–' : (kpi.growth_yoy > 0 ? '↑' : '↓')}</div>
        <div class="profile-kpi-hint">{growthHint}</div>
      </div>
      {kpi.modification_count > 0 && (
        <div class="profile-kpi" data-tone="warn">
          <div class="profile-kpi-label">Contracte modificate</div>
          <div class="profile-kpi-value">{fmt(kpi.modification_count)}</div>
          <div class="profile-kpi-hint">amendamente</div>
        </div>
      )}
    </div>

    <!-- Financial timeline (5 years) -->
    {financials.length > 0 && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          💰 Date financiare
          <span class="profile-section-title-meta">{financials.length} ani publicați la Min. Finanțelor</span>
        </h2>
        <FinancialTimeline data={financials} />
      </div>
    )}

    {/* ANAF debt — alert section first (most critical signal) */}
    {anafDebt && (
      <div class="profile-section" style="border-color: var(--signal); border-width: 2px;">
        <h2 class="profile-section-title">
          🚨 Datornic ANAF — listă publică {anafDebt.period_label}
          <span class="profile-section-title-meta">
            datorie totală {fmtRon(anafDebt.debt_total)} RON · categorie: {anafDebt.debtor_category || '?'}
          </span>
        </h2>
        <p class="text-sm text-meta mb-3">
          Această firmă apărea pe lista publicată trimestrial de ANAF cu firme cu datorii la bugetul general
          consolidat. Conform Legii 98/2016 art. 165, ofertanții cu obligații restante exigibile sunt
          <strong> excluși</strong> de la procedurile de achiziție publică. Datele provin din snapshot-ul
          oficial publicat pe data.gov.ro pentru {anafDebt.period_label}.
        </p>
        <div class="profile-firm-meta">
          <div class="profile-firm-meta-item">
            <div class="profile-firm-meta-label">Datorie principală</div>
            <div class="profile-firm-meta-value font-mono">{fmtRon(anafDebt.debt_principal || 0)} RON</div>
          </div>
          <div class="profile-firm-meta-item">
            <div class="profile-firm-meta-label">Penalități</div>
            <div class="profile-firm-meta-value font-mono">{fmtRon(anafDebt.debt_penalty || 0)} RON</div>
          </div>
          <div class="profile-firm-meta-item">
            <div class="profile-firm-meta-label">Total</div>
            <div class="profile-firm-meta-value font-mono"><strong>{fmtRon(anafDebt.debt_total)} RON</strong></div>
          </div>
          <div class="profile-firm-meta-item">
            <div class="profile-firm-meta-label">Data publicării</div>
            <div class="profile-firm-meta-value">{anafDebt.publication_date}</div>
          </div>
        </div>
      </div>
    )}

    {/* AEP donații electorale */}
    {aep && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          🗳️ Donator la partide politice
          <span class="profile-section-title-meta">
            {aep.nr_donatii} donații · {fmtRon(aep.total_lei)} RON · {aep.prima_an}-{aep.ultima_an}
          </span>
        </h2>
        <p class="text-sm text-meta mb-3">
          Această firmă a făcut donații către partide politice românești (raportate la AEP conform
          Legii 334/2006). Datele sunt agregate de Expert Forum la <a href="https://www.banipartide.ro/"
          class="text-stamp" target="_blank" rel="noopener">banipartide.ro</a> (sursă originală AEP).
          {aep.partide.length > 0 && <> Partide: {aep.partide.map((p, i) => (
            <span class="font-mono badge badge-stamp" style="margin: 0 4px;">{p}</span>
          ))}</>}
        </p>
        <div>
          {aep.recent.map((d) => (
            <div class="profile-contract">
              <div class="profile-contract-meta">
                <span class="font-mono badge badge-stamp">{d.partid_id || '?'}</span>
                <span>·</span>
                <span>{d.an}</span>
                {d.data_donatie && <><span>·</span><span>{d.data_donatie}</span></>}
              </div>
              <div class="profile-contract-bottom" style="margin-top: 6px;">
                <span></span>
                <span class="profile-contract-value">{fmtRon(d.suma_lei)} RON</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    )}

    <!-- EU funds beneficiary -->
    {euFunds && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          🇪🇺 Beneficiar privat de fonduri europene
          <span class="profile-section-title-meta">
            {euFunds.anunturi} anunț{euFunds.anunturi === 1 ? '' : 'uri'} ·
            {' '}{euFunds.proiecte} proiect{euFunds.proiecte === 1 ? '' : 'e'} ·
            {' '}{fmtRon(euFunds.buget_total)} RON
          </span>
        </h2>
        <p class="text-sm text-meta mb-3">
          Această firmă a publicat anunțuri de achiziție pe portalul beneficiar.fonduri-ue.ro
          ca beneficiar privat al unui proiect cu fonduri europene (POIM/POR/PNRR/PRSM/PRC/etc.).
          Procedurile NU intră în SEAP, dar trebuie publicate transparent conform Manualului
          Beneficiarului. Vezi <a href="/fonduri-ue#partea-privata" class="text-stamp hover:underline">contextul agregat</a>.
        </p>
        {euFunds.programs.length > 0 && (
          <div class="profile-firm-meta" style="margin-bottom: 14px;">
            <div class="profile-firm-meta-item" style="grid-column: span 4;">
              <div class="profile-firm-meta-label">Programe operaționale</div>
              <div class="profile-firm-meta-value" style="display:flex;flex-wrap:wrap;gap:6px;">
                {euFunds.programs.map((p) => (
                  <span class="badge badge-stamp font-mono" title={p.program_op_text || ''}>
                    {p.program_op_cod} · {p.proiecte}
                  </span>
                ))}
              </div>
            </div>
          </div>
        )}
        <div>
          {euFunds.recent.map((a) => (
            <a href={`/beneficiar-privat/${a.id}`} class="profile-contract">
              <div class="profile-contract-meta">
                <span>📄</span>
                <span>{dateFmt(a.data_publicare)}</span>
                {a.smis_proiect_code && <><span>·</span><span class="font-mono">SMIS {a.smis_proiect_code}</span></>}
                {a.program_op_cod && <><span>·</span><span class="font-mono">{a.program_op_cod}</span></>}
              </div>
              <div class="profile-contract-title">#{a.id} · {a.titlu || '?'}</div>
              <div class="profile-contract-bottom">
                <span></span>
                <span class="profile-contract-value">{fmtRon(a.buget_lei)} RON</span>
              </div>
            </a>
          ))}
        </div>
      </div>
    )}

    {/* ANRE energy licenses */}
    {anre && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          🔌 Licență/atestat ANRE · ENERGIE
          <span class="profile-section-title-meta">
            {anre.nr_licente_total} document{anre.nr_licente_total === 1 ? '' : 'e'} ·
            {' '}{anre.nr_active} active · {anre.nr_expirate} expirate{anre.nr_retrase > 0 ? ` · ${anre.nr_retrase} retrase` : ''}
            {anre.prima_emitere && anre.ultima_emitere && (
              <> · {dateFmt(anre.prima_emitere)} → {dateFmt(anre.ultima_emitere)}</>
            )}
          </span>
        </h2>
        <p class="text-sm text-meta mb-3">
          Această firmă apare în <strong>registrele publice ANRE</strong> ca titulară de licențe / autorizații / atestate
          pentru sectorul energetic (electricitate, gaze naturale sau servicii energetice). Sursă publică:
          {' '}<a href="https://portal.anre.ro/PublicLists" target="_blank" rel="noopener" class="text-stamp hover:underline">portal.anre.ro/PublicLists</a>.
        </p>
        {(anre.nr_electricitate > 0 || anre.nr_gaze > 0 || anre.nr_atestate > 0) && (
          <div class="profile-firm-meta" style="margin-bottom: 14px;">
            <div class="profile-firm-meta-item" style="grid-column: span 4;">
              <div class="profile-firm-meta-label">Distribuție pe surse</div>
              <div class="profile-firm-meta-value" style="display:flex;flex-wrap:wrap;gap:6px;">
                {anre.nr_electricitate > 0 && <span class="badge badge-stamp">⚡ electricitate · {anre.nr_electricitate}</span>}
                {anre.nr_gaze > 0 && <span class="badge badge-stamp">🔥 gaze · {anre.nr_gaze}</span>}
                {anre.nr_atestate > 0 && <span class="badge badge-stamp">📜 atestate · {anre.nr_atestate}</span>}
              </div>
            </div>
          </div>
        )}
        {anre.subtipuri.length > 0 && (
          <div class="profile-firm-meta" style="margin-bottom: 14px;">
            <div class="profile-firm-meta-item" style="grid-column: span 4;">
              <div class="profile-firm-meta-label">Tipuri de activitate</div>
              <div class="profile-firm-meta-value" style="display:flex;flex-wrap:wrap;gap:6px;">
                {anre.subtipuri.map((s) => <span class="badge">{s}</span>)}
              </div>
            </div>
          </div>
        )}
        <div>
          {anre.recent.map((l) => (
            <div class="profile-contract">
              <div class="profile-contract-meta">
                <span>📄</span>
                <span class="font-mono">{l.license_source}</span>
                <span>·</span>
                <span class="font-mono">nr. {l.license_no}</span>
                {l.data_emitere && <><span>·</span><span>emis {dateFmt(l.data_emitere)}</span></>}
                {l.data_expirare && <><span>·</span><span>expiră {dateFmt(l.data_expirare)}</span></>}
              </div>
              <div class="profile-contract-title">{l.license_type || '?'}{l.license_subtype ? ` · ${l.license_subtype}` : ''}</div>
              <div class="profile-contract-bottom">
                <span>{l.stare || ''}</span>
                <span></span>
              </div>
            </div>
          ))}
        </div>
      </div>
    )}

    {/* CNSC contestations */}
    {cnsc && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          ⚖️ Contestații la CNSC
          <span class="profile-section-title-meta">
            {cnsc.asAuthority && <>{cnsc.asAuthority.contestation_count} primite ca autoritate</>}
            {cnsc.asAuthority && cnsc.asContestator && <> · </>}
            {cnsc.asContestator && <>{cnsc.asContestator.contestations_filed} depuse ca contestator</>}
          </span>
        </h2>
        <p class="text-sm text-meta mb-3">
          Acest CUI apare în <strong>deciziile Consiliului Național de Soluționare a Contestațiilor</strong> (Legea 101/2016).
          CNSC e instanța administrativ-jurisdicțională care soluționează contestațiile pe procedurile SEAP. Sursă:
          {' '}<a href="http://portal.cnsc.ro/decizii.html" target="_blank" rel="noopener" class="text-stamp hover:underline">portal.cnsc.ro/decizii.html</a>.
        </p>
        {cnsc.asAuthority && cnsc.asAuthority.recent.length > 0 && (
          <>
            <h3 class="text-sm font-semibold mb-2" style="margin-top:14px;">Ca autoritate contractantă (contestată)</h3>
            <div>
              {cnsc.asAuthority.recent.map((d) => (
                <div class="profile-contract">
                  <div class="profile-contract-meta">
                    <span>⚖️</span>
                    <span class="font-mono">decizia {d.decision_no}/{d.decision_year}</span>
                    {d.registration_date && <><span>·</span><span>înreg. {dateFmt(d.registration_date)}</span></>}
                    {d.registration_no_cnsc && <><span>·</span><span class="font-mono">nr. {d.registration_no_cnsc}</span></>}
                    {d.decision_type && <><span>·</span><span>{d.decision_type}</span></>}
                  </div>
                  <div class="profile-contract-title">{d.contestator_names.length > 0 ? `Contestat de: ${d.contestator_names.join(', ')}` : 'Contestator necunoscut'}</div>
                  <div class="profile-contract-bottom">
                    <span>{d.pdf_url ? <a href={d.pdf_url} target="_blank" rel="noopener" class="text-stamp hover:underline">PDF decizie</a> : ''}</span>
                    <span></span>
                  </div>
                </div>
              ))}
            </div>
          </>
        )}
        {cnsc.asContestator && cnsc.asContestator.recent.length > 0 && (
          <>
            <h3 class="text-sm font-semibold mb-2" style="margin-top:14px;">Ca contestator (acțiuni inițiate)</h3>
            <div>
              {cnsc.asContestator.recent.map((d) => (
                <div class="profile-contract">
                  <div class="profile-contract-meta">
                    <span>⚖️</span>
                    <span class="font-mono">decizia {d.decision_no}/{d.decision_year}</span>
                    {d.registration_date && <><span>·</span><span>înreg. {dateFmt(d.registration_date)}</span></>}
                    {d.registration_no_cnsc && <><span>·</span><span class="font-mono">nr. {d.registration_no_cnsc}</span></>}
                    {d.decision_type && <><span>·</span><span>{d.decision_type}</span></>}
                  </div>
                  <div class="profile-contract-title">{d.authority_name ? `Împotriva: ${d.authority_name}` : 'Autoritate necunoscută'}</div>
                  <div class="profile-contract-bottom">
                    <span>{d.pdf_url ? <a href={d.pdf_url} target="_blank" rel="noopener" class="text-stamp hover:underline">PDF decizie</a> : ''}</span>
                    <span></span>
                  </div>
                </div>
              ))}
            </div>
          </>
        )}
      </div>
    )}

    <!-- RegAS state aid -->
    {regas && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          🏛️ Ajutoare de stat primite (RegAS)
          <span class="profile-section-title-meta">
            {regas.nr_ajutoare} {regas.nr_ajutoare === 1 ? 'ajutor' : 'ajutoare'} ·
            {' '}{regas.nr_masuri} măs{regas.nr_masuri === 1 ? 'ură' : 'uri'} ·
            {' '}{fmtRon(regas.total_ron)} RON cumulat
            {regas.prima_acordare && regas.ultima_acordare && (
              <> · {dateFmt(regas.prima_acordare)} → {dateFmt(regas.ultima_acordare)}</>
            )}
          </span>
        </h2>
        <p class="text-sm text-meta mb-3">
          Această firmă apare în <strong>Registrul Ajutoarelor de Stat</strong> ținut de Consiliul
          Concurenței. Sumele includ fonduri nerambursabile, garanții, scutiri fiscale și alte
          forme de ajutor public — separate de contractele de achiziție SEAP. Sursă publică:
          {' '}<a href="https://regas.consiliulconcurentei.ro/transparenta/" target="_blank" rel="noopener" class="text-stamp hover:underline">regas.consiliulconcurentei.ro</a>.
        </p>
        {regas.finantatori.length > 0 && (
          <div class="profile-firm-meta" style="margin-bottom: 14px;">
            <div class="profile-firm-meta-item" style="grid-column: span 4;">
              <div class="profile-firm-meta-label">Finanțatori (autoritatea care a acordat ajutorul)</div>
              <div class="profile-firm-meta-value" style="display:flex;flex-wrap:wrap;gap:6px;">
                {regas.finantatori.slice(0, 8).map((f) => (
                  <span class="badge badge-stamp">{f}</span>
                ))}
              </div>
            </div>
          </div>
        )}
        {regas.instrumente.length > 0 && (
          <div class="profile-firm-meta" style="margin-bottom: 14px;">
            <div class="profile-firm-meta-item" style="grid-column: span 4;">
              <div class="profile-firm-meta-label">Instrumente</div>
              <div class="profile-firm-meta-value" style="display:flex;flex-wrap:wrap;gap:6px;">
                {regas.instrumente.map((i) => (
                  <span class="badge">{i}</span>
                ))}
              </div>
            </div>
          </div>
        )}
        <div>
          {regas.recent.map((a) => (
            <div class="profile-contract">
              <div class="profile-contract-meta">
                <span>📋</span>
                <span>{dateFmt(a.data_acordare)}</span>
                {a.referinta_masura && <><span>·</span><span class="font-mono">{a.referinta_masura}</span></>}
                {a.instrument_acordare && <><span>·</span><span>{a.instrument_acordare}</span></>}
                {a.intensitate != null && <><span>·</span><span>intensitate {Number(a.intensitate).toFixed(0)}%</span></>}
              </div>
              <div class="profile-contract-title">{a.denumire_masura}</div>
              <div class="profile-contract-bottom">
                <span>{a.finantator || ''}</span>
                <span class="profile-contract-value">{fmtRon(Number(a.ajutor_acordat_subcategorie))} RON</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    )}

    {/* AAAS — state still owns shares / firm owes state money */}
    {aaas && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          🏛️ Sub autoritatea AAAS — stat acționar
          <span class="profile-section-title-meta">
            {aaas.statusuri.join(', ')}
            {aaas.max_state_share_pct != null && <> · participație stat {Number(aaas.max_state_share_pct).toFixed(2)}%</>}
            {aaas.total_debt_to_state_lei != null && aaas.total_debt_to_state_lei > 0 && (
              <> · datorii la stat {fmtRon(aaas.total_debt_to_state_lei)} RON</>
            )}
          </span>
        </h2>
        <p class="text-sm text-meta mb-3">
          Această firmă apare în portofoliul <strong>Autorității pentru Administrarea Activelor Statului (AAAS)</strong> — fie statul român deține încă acțiuni, fie există obligații post-privatizare neîndeplinite, fie e în procedură de insolvență administrată de AAAS. Sursă publică:
          {' '}<a href="https://www.aaas.gov.ro/despre-aaas/1-9-guvernanta-corporativa-aaas/1-9-3-companii-sub-autoritatea-aaas/" target="_blank" rel="noopener" class="text-stamp hover:underline">aaas.gov.ro</a>.
        </p>
        <div>
          {aaas.recent.map((f) => (
            <div class="profile-contract">
              <div class="profile-contract-meta">
                <span>🏛️</span>
                <span>{f.aaas_status}</span>
                {f.reg_number && <><span>·</span><span class="font-mono">{f.reg_number}</span></>}
                {f.last_action_date && <><span>·</span><span>{dateFmt(f.last_action_date)}</span></>}
              </div>
              <div class="profile-contract-title">
                {f.name}
                {f.state_share_pct != null && <> — participație stat {Number(f.state_share_pct).toFixed(2)}%</>}
              </div>
              <div class="profile-contract-bottom">
                <span>
                  {f.last_action || ''}
                  {' '}<a href={f.source_url} target="_blank" rel="noopener" class="text-stamp hover:underline">sursă AAAS →</a>
                </span>
                {f.debt_to_state_lei != null && f.debt_to_state_lei > 0 && (
                  <span class="profile-contract-value">{fmtRon(f.debt_to_state_lei)} RON datorie</span>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    )}

    {/* Curtea de Conturi — audit reports */}
    {cdc && cdc.nr_total > 0 && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          📋 Audited de Curtea de Conturi · ENTITATE PUBLICĂ
          <span class="profile-section-title-meta">
            {cdc.nr_total} rapoart{cdc.nr_total === 1 ? 'e' : 'e'}
            {Object.entries(cdc.by_audit_type).map(([k, v]) => (
              <> · {v} {k}</>
            ))}
            {cdc.ani_acoperiti.length > 0 && (
              <> · ani {cdc.ani_acoperiti[cdc.ani_acoperiti.length - 1]}–{cdc.ani_acoperiti[0]}</>
            )}
          </span>
        </h2>
        <p class="text-sm text-meta mb-3">
          Rapoarte de audit publicate de <strong>Curtea de Conturi a României</strong> (audit financiar / conformitate / performanță / follow-up). Sursă publică:
          {' '}<a href="https://www.curteadeconturi.ro/rapoarte-audit" target="_blank" rel="noopener" class="text-stamp hover:underline">curteadeconturi.ro</a>.
          {cdc.nr_fuzzy > 0 && cdc.nr_direct === 0 && (
            <> <em class="text-meta">*identificare aproximativă pe denumire — backfill CUI prin parsare PDF în Stage 2.</em></>
          )}
        </p>
        <div>
          {cdc.recent.map((r) => (
            <a href={r.detail_url} target="_blank" rel="noopener" class="profile-contract">
              <div class="profile-contract-meta">
                <span>📋</span>
                {r.audit_type && <span>{r.audit_type}</span>}
                {r.audit_year && <><span>·</span><span>anul {r.audit_year}</span></>}
                {r.doc_date && <><span>·</span><span>{dateFmt(r.doc_date)}</span></>}
                {r.doc_number && <><span>·</span><span class="font-mono">nr.{r.doc_number}</span></>}
                {r.match_method === 'name_fuzzy' && <><span>·</span><span class="text-meta"><em>~aprox</em></span></>}
              </div>
              <div class="profile-contract-title">{r.title}</div>
              {r.audited_entity_name && (
                <div class="profile-contract-bottom">
                  <span>🏛️ {r.audited_entity_name}</span>
                  <span class="profile-contract-value">deschide PDF →</span>
                </div>
              )}
            </a>
          ))}
        </div>
      </div>
    )}

    {/* ASF — financial supervision register timeline */}
    {asf && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          💰 Registru ASF — entitate financiară supravegheată
          <span class="profile-section-title-meta">
            {asf.nr_total} înregistrar{asf.nr_total === 1 ? 'e' : 'i'} ·
            {' '}{asf.nr_active} activ{asf.nr_active === 1 ? 'ă' : 'e'}
            {asf.nr_radiate > 0 && <> · {asf.nr_radiate} radiat{asf.nr_radiate === 1 ? 'ă' : 'e'}</>}
            {asf.prima_autorizare && <> · din {dateFmt(asf.prima_autorizare)}</>}
          </span>
        </h2>
        <p class="text-sm text-meta mb-3">
          Această firmă este înregistrată în registrele <strong>Autorității de Supraveghere Financiară (ASF)</strong>
          {' '}— asigurători, brokeri, fonduri de pensii, AIFM/UCITS. Sursă publică:
          {' '}<a href="https://data.asfromania.ro/" target="_blank" rel="noopener" class="text-stamp hover:underline">data.asfromania.ro</a>.
        </p>
        <div>
          {asf.recent.map((e) => (
            <div class="profile-contract">
              <div class="profile-contract-meta">
                <span>{e.section_status === 'activ' ? '🟢' : '⚫'}</span>
                <span class="font-mono">{e.register_no}</span>
                <span>·</span>
                <span>{e.register_type}</span>
                {e.tip_companie && <><span>·</span><span>{e.tip_companie}</span></>}
              </div>
              <div class="profile-contract-title">{e.name}</div>
              <div class="profile-contract-bottom">
                <span>
                  {e.data_autorizare && <>autorizat {dateFmt(e.data_autorizare)}</>}
                  {e.data_radiere && <> · radiat {dateFmt(e.data_radiere)}</>}
                  {e.nr_autorizatie && <> · aut. {e.nr_autorizatie}</>}
                </span>
                <span class="profile-contract-value">{e.section_status}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    )}

    {/* Administrators */}
    {firmDetails?.rep_legali && firmDetails.rep_legali.length > 0 && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          👤 Administratori / reprezentanți legali
          <span class="profile-section-title-meta">{firmDetails.rep_legali.length}</span>
        </h2>
        <div class="profile-firm-admins">
          {firmDetails.rep_legali.slice(0, 10).map((r) => (
            <div class="profile-firm-admin">
              <span class="profile-firm-admin-name">{r.persoana || '?'}</span>
              <span>
                <span class="profile-firm-admin-role">{r.calitate || ''}</span>
                {r.localitate && <span style="color: var(--meta); font-size: 11px; margin-left: 8px;">{r.localitate}</span>}
              </span>
            </div>
          ))}
        </div>
      </div>
    )}

    <!-- SEAP activity calendar heatmap -->
    {profile.contracts_won > 0 && (
      <div class="profile-section">
        <CalendarHeatmap data={heatmap} years={5} client:visible />
      </div>
    )}

    <!-- Top buyers + CPV breakdown -->
    <div class="grid lg:grid-cols-3 gap-4 mb-4">
      <div class="profile-section lg:col-span-2">
        <h2 class="profile-section-title">
          🏛️ Top instituții care îi cumpără
          <span class="profile-section-title-meta">{buyers.length}</span>
        </h2>
        <div class="profile-topcps">
          {buyers.map((b, i) => (
            <a href={`/autoritate/${b.cui}`} class="profile-topcp">
              <span class="profile-topcp-rank">{String(i + 1).padStart(2, '0')}</span>
              <div class="profile-topcp-info">
                <div class="profile-topcp-name">{b.name || '?'}</div>
                <div class="profile-topcp-meta">CUI {b.cui} · {b.contracts} anunțuri{b.county && ` · ${b.county}`}</div>
              </div>
              <div class="profile-topcp-value">{fmtRon(Number(b.total_value))}</div>
            </a>
          ))}
        </div>
      </div>

      <div class="profile-section">
        <h2 class="profile-section-title">
          📦 Categorii vândute
          <span class="profile-section-title-meta">{cpv.length}</span>
        </h2>
        <div class="profile-topcps">
          {cpv.slice(0, 8).map((c) => (
            <a href={`/categoria/${c.cpv_division}`} class="profile-topcp">
              <span class="profile-topcp-rank">{c.emoji || '📄'}</span>
              <div class="profile-topcp-info">
                <div class="profile-topcp-name">{c.cpv_division_name || c.cpv_division}</div>
                <div class="profile-topcp-meta">{c.contracts} anunțuri</div>
              </div>
              <div class="profile-topcp-value">{fmtRon(Number(c.total_value))}</div>
            </a>
          ))}
        </div>
      </div>
    </div>

    <!-- County distribution -->
    {counties.length > 0 && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          🗺️ Distribuție geografică (cumpărători)
          <span class="profile-section-title-meta">{counties.length} județe</span>
        </h2>
        <CountyBars data={counties} side="supplier" limit={15} />
      </div>
    )}

    <!-- Recent contracts -->
    <div class="profile-section">
      <h2 class="profile-section-title">
        📋 Anunțuri recente
        <span class="profile-section-title-meta">{contracts.length} din {fmt(profile.contracts_won)}</span>
      </h2>
      <div>
        {contracts.map((c) => (
          <a href={`/anunt/${c.id}`} class="profile-contract">
            <div class="profile-contract-meta">
              <span>{c.cpv_emoji || '📄'}</span>
              <span>{c.cpv_division_name || 'Necategorizat'}</span>
              <span>·</span>
              <span>{dateFmt(c.publication_date)}</span>
              {c.procedure_type && <><span>·</span><span>{c.procedure_type}</span></>}
            </div>
            <div class="profile-contract-title">{c.title || c.ref_number}</div>
            <div class="profile-contract-bottom">
              {c.counterpart_name && (
                <span class="profile-contract-cp">🏛️ {c.counterpart_name}</span>
              )}
              <span class="profile-contract-value">{fmtRon(Number(c.awarded_value))} RON</span>
            </div>
          </a>
        ))}
      </div>
      {contracts.length >= 30 && (
        <div class="text-center mt-3">
          <a href={`/cauta?supplier_cui=${profile.cui}`} class="text-stamp text-sm font-semibold hover:underline">
            Vezi toate cele {fmt(profile.contracts_won)} anunțuri →
          </a>
        </div>
      )}
    </div>

    <!-- Network link -->
    <div class="profile-section">
      <h2 class="profile-section-title">🕸️ Vezi rețeaua de relații</h2>
      <p class="text-sm text-meta mb-3">
        Diagrama interactivă cu top 20 autorități de la care a câștigat contracte, plus pentru fiecare autoritate alte firme care primesc contracte de la ea — pattern de "ecosistem" sau captură.
      </p>
      <a href={`/retea/${profile.cui}`} class="btn-brutal-primary">Deschide rețeaua →</a>
    </div>

    <!-- External enrichment links -->
    <div class="profile-external">
      <div class="profile-external-label">🔍 Verifică firma pe surse externe</div>
      <div class="profile-external-links">
        <a href={`https://www.listafirme.eu/firma/${profile.cui}`} target="_blank" rel="noopener" class="profile-external-link">listafirme.eu</a>
        <a href={`https://termene.ro/firma/${profile.cui}`} target="_blank" rel="noopener" class="profile-external-link">termene.ro</a>
        <a href={`https://www.alertacui.ro/cauta-firma?q=${profile.cui}`} target="_blank" rel="noopener" class="profile-external-link">alertacui.ro</a>
        <a href={`https://www.onrc.ro/index.php/ro/firme/firma?cui=${profile.cui}`} target="_blank" rel="noopener" class="profile-external-link">ONRC</a>
        <a href={`https://www.anaf.ro/inactivi/`} target="_blank" rel="noopener" class="profile-external-link">ANAF inactivi</a>
        <a href={`https://www.google.com/search?q=${encodeURIComponent(profile.name + ' ' + profile.cui)}`} target="_blank" rel="noopener" class="profile-external-link">Google</a>
      </div>
    </div>

  </main>
</AchizitiiLayout>
