---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import {
  resolveCounty,
  getCountyProfile,
  getCountyContracts,
  getCountyTopAuthorities,
  getCountyTopSuppliers,
  getCountyTopCpvs,
} from '../../lib/county-queries.js';

export const prerender = false;

const param = (Astro.params.county as string) || '';
const resolved = resolveCounty(param);

if (!resolved) return Astro.redirect('/404');

const [profile, contracts, authorities, suppliers, cpvs] = await Promise.all([
  getCountyProfile(resolved.code),
  getCountyContracts(resolved.code, 30, 0),
  getCountyTopAuthorities(resolved.code, 10),
  getCountyTopSuppliers(resolved.code, 10),
  getCountyTopCpvs(resolved.code, 10),
]);

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

const fmt = (n: number | null | undefined) =>
  n == null ? '–' : new Intl.NumberFormat('ro-RO', { maximumFractionDigits: 0 }).format(Number(n));
const dateFmt = (d: string | null) =>
  d ? new Date(d).toLocaleDateString('ro-RO', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\./g, '.') : '–';

const stripCui = (cui: string | null | undefined) => (cui || '').replace(/^RO\s*/i, '').trim();
const monogramText = resolved.code.replace('RO', '');
const maxCpvValue = Math.max(...cpvs.map(c => Number(c.total_value) || 0), 1);
---

<AchizitiiLayout
  title={`${resolved.name} — Județ · contracte publice`}
  description={`Județul ${resolved.name} (${resolved.code}): ${profile.total_contracts} contracte, ${fmt(profile.total_awarded)} RON cumulate.`}
>
  <main class="bg-paper text-ink min-h-screen">

    <div class="bg-ink text-paper">
      <div class="max-w-content mx-auto px-4 py-3 flex items-center justify-between">
        <a href="/" class="font-mono text-xs uppercase tracking-meta hover:text-stamp">← vreaudigital</a>
        <span class="font-mono text-xs uppercase tracking-meta text-paper/60">Județ · {resolved.code}</span>
      </div>
    </div>

    <header class="border-b-2 border-ink">
      <div class="max-w-content mx-auto px-4 py-10 md:py-14">
        <div class="flex items-start gap-5 md:gap-7">
          <div class="monogram monogram-state w-16 h-16 md:w-20 md:h-20 text-2xl md:text-3xl">{monogramText}</div>
          <div class="flex-1 min-w-0">
            <div class="label-meta mb-2">Județ · cod NUTS</div>
            <h1 class="font-display font-bold text-3xl md:text-5xl leading-[1.05] tracking-tight text-ink">
              {resolved.name}
            </h1>
            <div class="flex flex-wrap gap-x-6 gap-y-1 mt-3 label-meta text-ink/70">
              <span>NUTS <span class="font-mono normal-case tracking-normal text-ink">{resolved.code}</span></span>
              {profile.first_contract_date && profile.last_contract_date && (
                <span class="normal-case tracking-normal">
                  {dateFmt(profile.first_contract_date)} → {dateFmt(profile.last_contract_date)}
                </span>
              )}
            </div>
          </div>
        </div>
      </div>
    </header>

    <section class="border-b-2 border-ink">
      <div class="max-w-content mx-auto px-4 py-8 grid grid-cols-2 md:grid-cols-4 gap-0 divide-x-2 divide-ink/20">
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(profile.total_contracts)}</div>
          <div class="stat-label">Contracte</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(profile.total_awarded)}</div>
          <div class="stat-label">RON cumulați</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(profile.distinct_authorities)}</div>
          <div class="stat-label">Autorități</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(profile.distinct_suppliers)}</div>
          <div class="stat-label">Furnizori</div>
        </div>
      </div>
    </section>

    <section class="grid lg:grid-cols-2 gap-0 border-b-2 border-ink">
      <div class="px-4 md:px-8 py-10 lg:border-r-2 lg:border-ink">
        <div class="label-meta mb-4">Top autorități</div>
        <div class="divide-y divide-ink/20">
          {authorities.map((a, i) => (
            <a href={`/autoritate/${a.cui}`} class="flex items-baseline gap-4 py-3 -mx-2 px-2 hover:bg-stamp transition-none">
              <span class="font-mono text-xs text-ink/40 w-6 tabular-nums">{String(i + 1).padStart(2, '0')}</span>
              <div class="flex-1 min-w-0">
                <div class="font-display font-semibold text-base text-ink truncate">{a.name || '?'}</div>
                <div class="label-meta normal-case tracking-normal text-ink/60 mt-0.5">
                  CUI <span class="font-mono">{a.cui}</span> · {a.contracts} contracte
                </div>
              </div>
              <div class="font-mono font-bold tabular-nums text-base text-ink shrink-0">
                {fmt(a.total_value)}
                <span class="font-body text-xs text-ink/60 font-normal ml-1">RON</span>
              </div>
            </a>
          ))}
          {!authorities.length && <div class="label-meta normal-case tracking-normal text-ink/60 py-3">Nicio autoritate.</div>}
        </div>
      </div>

      <div class="px-4 md:px-8 py-10 border-t-2 border-ink lg:border-t-0">
        <div class="label-meta mb-4">Top furnizori</div>
        <div class="divide-y divide-ink/20">
          {suppliers.map((s, i) => (
            <a href={`/firma/${stripCui(s.cui)}`} class="flex items-baseline gap-4 py-3 -mx-2 px-2 hover:bg-stamp transition-none">
              <span class="font-mono text-xs text-ink/40 w-6 tabular-nums">{String(i + 1).padStart(2, '0')}</span>
              <div class="flex-1 min-w-0">
                <div class="font-display font-semibold text-base text-ink truncate">{s.name || '?'}</div>
                <div class="label-meta normal-case tracking-normal text-ink/60 mt-0.5">
                  CUI <span class="font-mono">{s.cui}</span> · {s.contracts} contracte
                </div>
              </div>
              <div class="font-mono font-bold tabular-nums text-base text-ink shrink-0">
                {fmt(s.total_value)}
                <span class="font-body text-xs text-ink/60 font-normal ml-1">RON</span>
              </div>
            </a>
          ))}
          {!suppliers.length && <div class="label-meta normal-case tracking-normal text-ink/60 py-3">Niciun furnizor.</div>}
        </div>
      </div>
    </section>

    {cpvs.length > 0 && (
      <section class="border-b-2 border-ink">
        <div class="max-w-content mx-auto px-4 md:px-8 py-10">
          <div class="label-meta mb-4">Top categorii (CPV diviziune)</div>
          <div class="space-y-3">
            {cpvs.map((c) => {
              const pct = Math.max(2, Math.round(100 * Number(c.total_value || 0) / maxCpvValue));
              return (
                <a href={`/categoria/${c.cpv_division}`} class="block hover:bg-stamp -mx-2 px-2 py-1 transition-none">
                  <div class="flex items-baseline justify-between gap-3 mb-1">
                    <span class="font-display text-sm md:text-base text-ink truncate">
                      <span class="font-mono text-xs text-ink/60 mr-2">{c.cpv_division}</span>
                      {c.cpv_division_name || '—'}
                    </span>
                    <span class="font-mono text-xs text-ink/60 tabular-nums shrink-0">
                      {c.contracts} · {fmt(c.total_value)} RON
                    </span>
                  </div>
                  <div class="bar-track h-3"><div class="bar-fill" style={`width:${pct}%`}></div></div>
                </a>
              );
            })}
          </div>
        </div>
      </section>
    )}

    <section class="border-b-2 border-ink">
      <div class="max-w-content mx-auto px-4 md:px-8 py-10">
        <div class="flex items-baseline justify-between mb-6">
          <div class="label-meta">Contracte recente</div>
          <a href={`/cauta?county_code=${resolved.code}`} class="label-meta normal-case tracking-normal hover:bg-stamp">
            vezi toate {fmt(profile.total_contracts)} →
          </a>
        </div>
        <ol class="divide-y divide-ink/20">
          {contracts.map((c) => (
            <li>
              <a href={`/anunt/${c.id}`} class="grid md:grid-cols-[110px_1fr_auto] gap-x-5 gap-y-1 py-4 px-2 -mx-2 hover:bg-stamp transition-none items-baseline">
                <div class="font-mono text-xs tabular-nums text-ink/60">{dateFmt(c.publication_date)}</div>
                <div class="min-w-0">
                  <div class="font-display font-semibold text-base text-ink leading-snug">{c.title || c.ref_number}</div>
                  <div class="flex flex-wrap gap-x-3 gap-y-0.5 mt-1 label-meta normal-case tracking-normal text-ink/60">
                    {c.authority_name && <span class="text-ink">{c.authority_name}</span>}
                    {c.supplier_name && <span>→ {c.supplier_name}</span>}
                    {c.cpv_division_name && <span>{c.cpv_division_name}</span>}
                    {c.has_lots && <span>{c.lots_count || ''} loturi</span>}
                  </div>
                </div>
                <div class="font-mono font-bold tabular-nums text-base text-ink text-right whitespace-nowrap">
                  {fmt(c.awarded_value)}
                  <span class="font-body text-xs text-ink/60 font-normal ml-1">RON</span>
                </div>
              </a>
            </li>
          ))}
        </ol>
      </div>
    </section>

    <footer class="bg-ink text-paper">
      <div class="max-w-content mx-auto px-4 py-8 flex flex-wrap items-center justify-between gap-4">
        <div class="label-meta text-paper/60">Județul {resolved.name} · NUTS {resolved.code}</div>
        <a href={`/cauta?county_code=${resolved.code}`} class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">
          Caută în acest județ →
        </a>
      </div>
    </footer>
  </main>
</AchizitiiLayout>
