---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import {
  getAuthorityProfile,
  getAuthorityContracts,
  getCpvBreakdown,
  getTopCounterparts,
  getDailyHeatmap,
  getCountyDistribution,
  getAuthorityKpi,
  getFirmDetails,
  getEuFundsBeneficiarStatus,
  getRegasStatus,
  getAnafDebtStatus,
} from '../../lib/profile-queries.js';
import {
  getCnscStatus,
  getBugetarStatus,
} from '../../lib/profile-queries-utilities.js';
import { getCurteaContStatus } from '../../lib/profile-queries-financial.js';
import { CalendarHeatmap } from '../../components/profile/CalendarHeatmap';
import { CountyBars } from '../../components/profile/CountyBars';
import '../../components/profile/profile.css';

export const prerender = false;

const cui = Astro.params.cui as string;

const [profile, contracts, cpv, suppliers, heatmap, counties, kpi, firmDetails, euFunds, regas, anafDebt, cnsc, cdc, bugetar] = await Promise.all([
  getAuthorityProfile(cui),
  getAuthorityContracts(cui, 30, 0),
  getCpvBreakdown('authority', cui),
  getTopCounterparts('authority', cui, 10),
  getDailyHeatmap('authority', cui),
  getCountyDistribution('authority', cui),
  getAuthorityKpi(cui),
  getFirmDetails(cui),
  getEuFundsBeneficiarStatus(cui),
  getRegasStatus(cui),
  getAnafDebtStatus(cui),
  getCnscStatus(cui),
  getCurteaContStatus(cui),
  getBugetarStatus(cui),
]);

if (!profile) {
  return Astro.redirect('/404');
}

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;

// Tone calibrations from research (OCP/EU SMSC baselines):
// - direct_pct: <20% normal, 20-40% warn, >40% risk
// - hhi: <1500 ok, 1500-2500 warn, >2500 risk (DOJ thresholds)
// - top supplier: <30% ok, 30-50% warn, >50% risk
// - q4 spike: <1.3 ok, 1.3-1.7 warn, >1.7 risk
const directTone = kpi.direct_pct > 0.40 ? 'risk' : kpi.direct_pct > 0.20 ? 'warn' : 'ok';
const hhiTone = kpi.hhi_suppliers > 2500 ? 'risk' : kpi.hhi_suppliers > 1500 ? 'warn' : 'ok';
const topSupTone = kpi.top_supplier_share > 0.50 ? 'risk' : kpi.top_supplier_share > 0.30 ? 'warn' : 'ok';
const q4Tone = kpi.q4_spike == null ? 'ok' : kpi.q4_spike > 1.7 ? 'risk' : kpi.q4_spike > 1.3 ? 'warn' : 'ok';
const modTone = kpi.modification_count > 50 ? 'warn' : 'ok';

function dossier(): string {
  const parts: string[] = [];
  parts.push(`<strong>${profile!.name}</strong> a contractat ${fmtRon(totalAwarded)} RON în ${fmt(profile!.total_contracts)} anunțuri cu ${fmt(profile!.distinct_suppliers)} furnizori distincți.`);

  if (kpi.direct_pct > 0.20) {
    parts.push(`<strong>${(kpi.direct_pct * 100).toFixed(0)}%</strong> din valoare a fost atribuită prin achiziție directă (fără competiție publică).`);
  }
  if (kpi.top_supplier_share > 0.30) {
    parts.push(`Cel mai mare furnizor concentrează <strong>${(kpi.top_supplier_share * 100).toFixed(0)}%</strong> din valoarea totală.`);
  } else if (kpi.hhi_suppliers > 1500) {
    parts.push(`Indice de concentrare HHI = <strong>${Math.round(kpi.hhi_suppliers)}</strong> (${kpi.hhi_suppliers > 2500 ? 'piață concentrată' : 'moderat concentrată'}).`);
  }

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

<AchizitiiLayout
  title={`${profile.name} — Autoritate contractantă · vreaudigital.ro`}
  description={`${profile.name} (CUI ${profile.cui}): ${profile.total_contracts} anunțuri, ${fmtRon(totalAwarded)} RON.`}
  ogImage={`/api/og/autoritate/${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">{firmDetails?.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>}
            {profile.authority_type && <span class="badge">{profile.authority_type}</span>}
            {firmDetails?.is_radiated_onrc && <span class="badge badge-signal">⚠ Radiată ONRC</span>}
            {euFunds && <span class="badge badge-state">🇪🇺 beneficiar EU · {euFunds.anunturi} anunț{euFunds.anunturi === 1 ? '' : 'uri'}</span>}
            {bugetar && <span class="badge badge-state">📊 raportor MFP · {bugetar.sector_label}{bugetar.is_ordonator_principal ? ' (ordonator principal)' : ''}</span>}
            {regas && <span class="badge badge-state">🏛️ ajutor de stat · {regas.nr_ajutoare} · {fmtRon(regas.total_ron)} RON</span>}
            {anafDebt && <span class="badge badge-signal">🚨 datornic ANAF {anafDebt.period_label} · {fmtRon(anafDebt.debt_total)} RON</span>}
            {cnsc?.asAuthority && <span class="badge badge-signal">⚖️ {cnsc.asAuthority.contestation_count} contestaț{cnsc.asAuthority.contestation_count === 1 ? 'ie' : 'ii'} CNSC</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>}
          </div>
          {(firmDetails?.adr_full || profile.address) && <p class="text-sm text-meta mt-2">{firmDetails?.adr_full || profile.address}</p>}
          <div class="profile-dossier" set:html={dossier()} />

          {firmDetails && (
            <div class="profile-firm-meta" style="margin-top: 14px;">
              {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>
              )}
            </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.total_contracts)} anunțuri · {fmt(profile.distinct_suppliers)} furnizori</div>
      </div>
      <div class="profile-kpi" data-tone={directTone}>
        <div class="profile-kpi-label">Achiziție directă</div>
        <div class="profile-kpi-value">{(kpi.direct_pct * 100).toFixed(0)}%</div>
        <div class="profile-kpi-hint">{directTone === 'risk' ? '⚠ peste prag rezonabil' : directTone === 'warn' ? 'moderat' : 'sub prag'}</div>
      </div>
      <div class="profile-kpi" data-tone={topSupTone}>
        <div class="profile-kpi-label">Top furnizor</div>
        <div class="profile-kpi-value">{(kpi.top_supplier_share * 100).toFixed(0)}%</div>
        <div class="profile-kpi-hint">{topSupTone === 'risk' ? '⚠ dependență ridicată' : 'din valoare totală'}</div>
      </div>
      <div class="profile-kpi" data-tone={hhiTone}>
        <div class="profile-kpi-label">HHI furnizori</div>
        <div class="profile-kpi-value">{Math.round(kpi.hhi_suppliers)}</div>
        <div class="profile-kpi-hint">{hhiTone === 'risk' ? 'concentrat' : hhiTone === 'warn' ? 'moderat' : 'competitiv'} ({hhiTone === 'risk' ? '>2500' : hhiTone === 'warn' ? '1500-2500' : '<1500'})</div>
      </div>
      <div class="profile-kpi">
        <div class="profile-kpi-label">Diversitate CPV</div>
        <div class="profile-kpi-value">{kpi.cpv_diversity.toFixed(2)}</div>
        <div class="profile-kpi-hint">{cpv.length} categorii</div>
      </div>
      <div class="profile-kpi" data-tone={q4Tone}>
        <div class="profile-kpi-label">Spike Q4</div>
        <div class="profile-kpi-value">{kpi.q4_spike == null ? '–' : kpi.q4_spike.toFixed(2) + '×'}</div>
        <div class="profile-kpi-hint">{q4Tone === 'risk' ? '⚠ end-of-year rush' : 'an precedent'}</div>
      </div>
      {kpi.modification_count > 0 && (
        <div class="profile-kpi" data-tone={modTone}>
          <div class="profile-kpi-label">Modificate</div>
          <div class="profile-kpi-value">{fmt(kpi.modification_count)}</div>
          <div class="profile-kpi-hint">amendamente</div>
        </div>
      )}
    </div>

    {/* EU funds beneficiary (regii autonome, S.A. de stat etc. care primesc fonduri EU) */}
    {euFunds && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          🇪🇺 Autoritate beneficiară 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ă autoritate (probabil regie autonomă / S.A. de stat / instituție publică)
          a publicat anunțuri de achiziție pe portalul beneficiar.fonduri-ue.ro pentru
          proiecte cu fonduri europene. Procedurile NU intră în SEAP, dar trebuie publicate
          transparent conform Manualului Beneficiarului.
        </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>
    )}

    {/* Administrators / reprezentanți legali (rare on authorities, but state companies have them) */}
    {firmDetails?.rep_legali && firmDetails.rep_legali.length > 0 && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          👤 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>
    )}

    {/* 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ă autoritate apare pe lista publicată trimestrial de ANAF cu entități cu datorii la bugetul general consolidat.
          O autoritate publică datornică pe această listă semnalează un management financiar problematic și risc de blocaj operațional.
          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>
    )}

    {/* CNSC contestations against this authority */}
    {cnsc?.asAuthority && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          ⚖️ Contestații CNSC primite ca autoritate contractantă
          <span class="profile-section-title-meta">
            {cnsc.asAuthority.contestation_count} contestaț{cnsc.asAuthority.contestation_count === 1 ? 'ie' : 'ii'}
            {cnsc.asAuthority.first_contestation_date && cnsc.asAuthority.last_contestation_date && (
              <> · {String(cnsc.asAuthority.first_contestation_date).slice(0,4)}–{String(cnsc.asAuthority.last_contestation_date).slice(0,4)}</>
            )}
          </span>
        </h2>
        <p class="text-sm text-meta mb-3">
          Această autoritate a fost contestată la <strong>Consiliul Național de Soluționare a Contestațiilor</strong> (Legea 101/2016).
          Frecvența ridicată indică probleme procedurale repetate: documentații slabe, criterii părtinitoare, evaluări contestabile.
          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>
        <div>
          {cnsc.asAuthority.recent.slice(0, 10).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 && 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>
      </div>
    )}

    {/* Curtea Conturi audit reports against this authority */}
    {cdc && cdc.nr_total > 0 && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          📋 Audited de Curtea de Conturi
          <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 && 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>. Repetabilitatea — mai ales follow-up — e semnal că anomaliile constatate anterior n-au fost corectate.
          Sursă: <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.slice(0, 10).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>
              <div class="profile-contract-bottom">
                <span></span>
                <span class="profile-contract-value">deschide PDF →</span>
              </div>
            </a>
          ))}
        </div>
      </div>
    )}

    {/* RegAS — state aid received by this authority */}
    {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'} ·
            {' '}{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ă entitate apare în <strong>Registrul Ajutoarelor de Stat</strong> (Consiliul Concurenței).
          Sursă: <a href="https://regas.consiliulconcurentei.ro/transparenta/" target="_blank" rel="noopener" class="text-stamp hover:underline">regas.consiliulconcurentei.ro</a>.
        </p>
        <div>
          {regas.recent.slice(0, 10).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></>}
              </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>
    )}

    <!-- Calendar heatmap -->
    <div class="profile-section">
      <CalendarHeatmap data={heatmap} years={5} client:visible />
    </div>

    <!-- Top suppliers + 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 furnizori
          <span class="profile-section-title-meta">{suppliers.length}</span>
        </h2>
        <div class="profile-topcps">
          {suppliers.map((s, i) => {
            const cuiClean = (s.cui || '').replace(/^RO\s*/i, '').trim();
            return (
            <a href={`/firma/${cuiClean}`} 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">{s.name || '?'}</div>
                <div class="profile-topcp-meta">CUI {s.cui} · {s.contracts} anunțuri{s.county && ` · ${s.county}`}</div>
              </div>
              <div class="profile-topcp-value">{fmtRon(Number(s.total_value))}</div>
            </a>
          )})}
        </div>
      </div>

      <div class="profile-section">
        <h2 class="profile-section-title">
          📦 Categorii cumpărate
          <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">
          🗺️ De unde vin furnizorii
          <span class="profile-section-title-meta">{counties.length} județe</span>
        </h2>
        <CountyBars data={counties} side="authority" 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.total_contracts)}</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></>}
              {c.has_lots && <><span>·</span><span>{c.lots_count || ''} loturi</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?authority_cui=${profile.cui}`} class="text-stamp text-sm font-semibold hover:underline">
            Vezi toate cele {fmt(profile.total_contracts)} anunțuri →
          </a>
        </div>
      )}
    </div>

    <!-- Network link -->
    <div class="profile-section">
      <h2 class="profile-section-title">🕸️ Vezi rețeaua de furnizori</h2>
      <p class="text-sm text-meta mb-3">
        Diagrama interactivă cu top 20 furnizori, plus pentru fiecare furnizor alte autorități cu care lucrează — descoperă pattern-uri de "client repetat" sau prezență națională.
      </p>
      <a href={`/retea/${profile.cui}`} class="btn-brutal-primary">Deschide rețeaua →</a>
    </div>

    <!-- External links -->
    <div class="profile-external">
      <div class="profile-external-label">🔍 Verifică 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>
        {firmDetails && <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.curteadeconturi.ro/rapoarte-audit`} target="_blank" rel="noopener" class="profile-external-link">Curtea de Conturi</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>
