---
import AchizitiiLayout from '../layouts/AchizitiiLayout.astro';
import {
  getEUFundedSummary,
  getTopEUContracts,
  getPrivateEuSummary,
} from '../lib/dashboard-queries.js';

export const prerender = false;

const [summary, contracts, privateEu] = await Promise.all([
  getEUFundedSummary(),
  getTopEUContracts(100),
  getPrivateEuSummary(),
]);

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

const maxProgram = Math.max(...summary.programs.map(p => p.total_awarded), 1);
const maxPrivateProiect = Math.max(...privateEu.top_proiecte.map(p => p.buget_total), 1);
const maxPrivateJudet = Math.max(...privateEu.top_judete.map(j => j.buget_total), 1);
const proieScrapeProgress = privateEu.proiecte_target > 0
  ? Math.round(100 * privateEu.proiecte_scraped / privateEu.proiecte_target)
  : 0;
---

<AchizitiiLayout
  title="Banii UE în România — fonduri europene · vreaudigital.ro"
  description="Contractele finanțate din fonduri europene în România în ultimele 12 luni: programe, beneficiari, valori."
>
  <main class="bg-paper text-ink min-h-screen">

    <!-- Top strip -->
    <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">Banii UE în România · 12 luni</span>
      </div>
    </div>

    <!-- Header -->
    <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 w-16 h-16 md:w-20 md:h-20 text-3xl md:text-4xl bg-state text-paper">★</div>
          <div class="flex-1 min-w-0">
            <div class="label-meta mb-2">Fonduri europene · ultimele 12 luni</div>
            <h1 class="font-display font-bold text-3xl md:text-5xl leading-[1.05] tracking-tight text-ink">
              Banii UE în România
            </h1>
            <p class="font-serif italic text-base md:text-lg text-ink/70 mt-3 max-w-3xl">
              Contracte publice finanțate din fonduri europene — pe programe, autorități și firme câștigătoare.
            </p>
          </div>
        </div>
      </div>
    </header>

    <!-- Section A label: SEAP-side -->
    <section class="border-b border-ink/30 bg-paper">
      <div class="max-w-content mx-auto px-4 py-3">
        <div class="label-meta text-ink/70">A · Partea SEAP — contracte de la stat finanțate UE (12 luni)</div>
      </div>
    </section>

    <!-- Stats register: SEAP-side -->
    <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(summary.total_awarded)}</div>
          <div class="stat-label">RON din UE</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(summary.contracts)}</div>
          <div class="stat-label">Contracte UE</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(summary.distinct_authorities)}</div>
          <div class="stat-label">Autorități unice</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(summary.distinct_suppliers)}</div>
          <div class="stat-label">Firme câștigătoare</div>
        </div>
      </div>
    </section>

    <!-- Programs + Top beneficiaries (3-up grid) -->
    <section class="border-b-2 border-ink">
      <div class="max-w-content mx-auto grid lg:grid-cols-12 gap-0 divide-y-2 lg:divide-y-0 lg:divide-x-2 divide-ink">

        <!-- Programs with bars -->
        <div class="lg:col-span-5 px-4 md:px-6 py-10">
          <div class="label-meta mb-4">Programe operaționale</div>
          {summary.programs.length === 0 && (
            <div class="font-serif italic text-ink/60">Nu există date despre programe în ultimele 12 luni.</div>
          )}
          <div class="space-y-3">
            {summary.programs.map((p) => {
              const pct = Math.max(2, Math.round(100 * p.total_awarded / maxProgram));
              return (
                <div>
                  <div class="flex items-baseline justify-between gap-3 mb-1">
                    <span class="font-display text-sm md:text-base text-ink truncate">{p.program}</span>
                    <span class="font-mono font-bold tabular-nums text-xs md:text-sm text-ink shrink-0">
                      {fmt(p.total_awarded)}
                    </span>
                  </div>
                  <div class="bar-track h-3" style="background:#E5E1D8">
                    <div class="bar-fill" style={`width:${pct}%`}></div>
                  </div>
                  <div class="label-meta normal-case tracking-normal text-ink/50 mt-0.5">
                    <span class="font-mono">{p.contracts}</span> contracte
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <!-- Top authorities -->
        <div class="lg:col-span-3 px-4 md:px-6 py-10">
          <div class="label-meta mb-4">Top 10 autorități</div>
          {summary.top_authorities.length === 0 && (
            <div class="font-serif italic text-ink/60">Niciun beneficiar.</div>
          )}
          <div class="divide-y divide-ink/20">
            {summary.top_authorities.map((a, i) => (
              <a href={`/autoritate/${a.cui}`} class="flex items-baseline gap-3 py-2 -mx-2 px-2 hover:bg-stamp transition-none">
                <span class="font-mono text-xs text-ink/40 w-5 tabular-nums shrink-0">{String(i + 1).padStart(2, '0')}</span>
                <div class="flex-1 min-w-0">
                  <div class="font-display text-sm text-ink truncate">{a.name || '?'}</div>
                  <div class="label-meta normal-case tracking-normal text-ink/60 mt-0.5">
                    {a.county && <span>{a.county} · </span>}<span class="font-mono">{a.contracts}</span> contracte
                  </div>
                </div>
                <div class="font-mono font-bold tabular-nums text-xs text-ink shrink-0">{fmt(a.total_awarded)}</div>
              </a>
            ))}
          </div>
        </div>

        <!-- Top suppliers -->
        <div class="lg:col-span-4 px-4 md:px-6 py-10">
          <div class="label-meta mb-4">Top 10 firme câștigătoare</div>
          {summary.top_suppliers.length === 0 && (
            <div class="font-serif italic text-ink/60">Niciun câștigător.</div>
          )}
          <div class="divide-y divide-ink/20">
            {summary.top_suppliers.map((s, i) => {
              const cui = (s.cui || '').replace(/^RO\s*/i, '').trim();
              return (
                <a href={`/firma/${cui}`} class="flex items-baseline gap-3 py-2 -mx-2 px-2 hover:bg-stamp transition-none">
                  <span class="font-mono text-xs text-ink/40 w-5 tabular-nums shrink-0">{String(i + 1).padStart(2, '0')}</span>
                  <div class="flex-1 min-w-0">
                    <div class="font-display text-sm text-ink truncate">{s.name || cui}</div>
                    <div class="label-meta normal-case tracking-normal text-ink/60 mt-0.5">
                      {s.county && <span>{s.county} · </span>}<span class="font-mono">{s.contracts}</span> contracte
                    </div>
                  </div>
                  <div class="font-mono font-bold tabular-nums text-xs text-ink shrink-0">{fmt(s.total_awarded)}</div>
                </a>
              );
            })}
          </div>
        </div>

      </div>
    </section>

    <!-- Section B label: Private-side -->
    <section class="border-b border-ink/30 bg-paper">
      <div class="max-w-content mx-auto px-4 py-3 flex items-baseline justify-between gap-3 flex-wrap">
        <div class="label-meta text-ink/70">
          B · Partea privată — beneficiari care își gestionează singur banii UE
          {privateEu.proiecte_scraped < privateEu.proiecte_target && (
            <span class="ml-2 text-stamp normal-case tracking-normal">
              · proiecte: {fmt(privateEu.proiecte_scraped)} / {fmt(privateEu.proiecte_target)} ({proieScrapeProgress}%)
            </span>
          )}
        </div>
        <a href="/fonduri-ue/anunturi" class="chip-brutal bg-stamp text-ink border-ink hover:bg-ink hover:text-paper whitespace-nowrap">
          browse 41K anunțuri →
        </a>
      </div>
    </section>

    <!-- Stats register: Private-side -->
    <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(privateEu.buget_total)}</div>
          <div class="stat-label">RON în loturi private</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(privateEu.anunturi_total)}</div>
          <div class="stat-label">Anunțuri publicate</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(privateEu.proiecte_total)}</div>
          <div class="stat-label">Proiecte distinct</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(privateEu.firme_matched)}</div>
          <div class="stat-label">Firme cu CUI matched</div>
        </div>
      </div>
    </section>

    <!-- Private: Top firme + Top proiecte + Județe + Programe (4-col) -->
    <section class="border-b-2 border-ink">
      <div class="max-w-content mx-auto grid lg:grid-cols-12 gap-0 divide-y-2 lg:divide-y-0 lg:divide-x-2 divide-ink">

        <!-- Top firme private cu fonduri EU -->
        <div class="lg:col-span-5 px-4 md:px-6 py-10">
          <div class="flex items-baseline justify-between mb-4">
            <div class="label-meta">Top 20 firme beneficiari privați</div>
            <span class="label-meta normal-case tracking-normal text-ink/50">după buget loturi</span>
          </div>
          {privateEu.top_firme.length === 0 && (
            <div class="font-serif italic text-ink/60">Nicio firmă matched cu CUI încă.</div>
          )}
          <div class="divide-y divide-ink/20">
            {privateEu.top_firme.map((f, i) => (
              <a href={f.cui ? `/firma/${f.cui}` : '#'} class="flex items-baseline gap-3 py-2 -mx-2 px-2 hover:bg-stamp transition-none">
                <span class="font-mono text-xs text-ink/40 w-6 tabular-nums shrink-0">{String(i + 1).padStart(2, '0')}</span>
                <div class="flex-1 min-w-0">
                  <div class="font-display text-sm text-ink truncate">{f.name}</div>
                  <div class="label-meta normal-case tracking-normal text-ink/60 mt-0.5">
                    {f.county && <span>{f.county} · </span>}<span class="font-mono">{f.anunturi}</span> anunțuri
                  </div>
                </div>
                <div class="font-mono font-bold tabular-nums text-xs text-ink shrink-0">{fmt(f.buget_total)}</div>
              </a>
            ))}
          </div>
        </div>

        <!-- Top proiecte (joinable to beneficiar_proiect once scraped) -->
        <div class="lg:col-span-4 px-4 md:px-6 py-10">
          <div class="flex items-baseline justify-between mb-4">
            <div class="label-meta">Top 20 proiecte după buget</div>
          </div>
          {privateEu.top_proiecte.length === 0 && (
            <div class="font-serif italic text-ink/60">Niciun proiect.</div>
          )}
          <div class="space-y-2">
            {privateEu.top_proiecte.map((p, i) => {
              const pct = Math.max(2, Math.round(100 * p.buget_total / maxPrivateProiect));
              return (
                <a href={`/proiect/${p.id}`} class="block py-1 -mx-2 px-2 hover:bg-stamp transition-none">
                  <div class="flex items-baseline gap-2 mb-0.5">
                    <span class="font-mono text-[10px] text-ink/40 tabular-nums shrink-0">{String(i + 1).padStart(2, '0')}</span>
                    <span class="font-display text-xs text-ink truncate flex-1 min-w-0">{p.titlu || p.beneficiar_name || `#${p.id}`}</span>
                    {p.program_op_cod && (
                      <span class="font-mono text-[10px] text-paper bg-state px-1 shrink-0">{p.program_op_cod}</span>
                    )}
                    <span class="font-mono font-bold tabular-nums text-xs text-ink shrink-0">{fmt(p.buget_total)}</span>
                  </div>
                  <div class="bar-track h-1.5 ml-6" style="background:#E5E1D8">
                    <div class="bar-fill" style={`width:${pct}%`}></div>
                  </div>
                </a>
              );
            })}
          </div>
        </div>

        <!-- Top județe + Programe -->
        <div class="lg:col-span-3 px-4 md:px-6 py-10 space-y-8">
          <div>
            <div class="label-meta mb-4">Top 10 județe</div>
            <div class="space-y-2">
              {privateEu.top_judete.map((j) => {
                const pct = Math.max(2, Math.round(100 * j.buget_total / maxPrivateJudet));
                return (
                  <div>
                    <div class="flex items-baseline justify-between gap-2 mb-0.5">
                      <span class="font-display text-xs text-ink truncate">{j.judet}</span>
                      <span class="font-mono font-bold tabular-nums text-[11px] text-ink shrink-0">{fmt(j.buget_total)}</span>
                    </div>
                    <div class="bar-track h-1.5" style="background:#E5E1D8">
                      <div class="bar-fill" style={`width:${pct}%`}></div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div>
            <div class="label-meta mb-3">Programe operaționale</div>
            {privateEu.programs.length === 0 ? (
              <div class="font-serif italic text-ink/60 text-xs">
                Datele despre programe se completează pe măsură ce scraperul de proiecte rulează ({fmt(privateEu.proiecte_scraped)}/{fmt(privateEu.proiecte_target)}).
              </div>
            ) : (
              <div class="space-y-1.5">
                {privateEu.programs.map((p) => (
                  <div class="flex items-baseline justify-between gap-2">
                    <span class="font-mono text-[11px] text-paper bg-state px-1.5 py-0.5 shrink-0">{p.program_op_cod}</span>
                    <span class="font-display text-xs text-ink/70 truncate flex-1 min-w-0">{p.program_op_text || ''}</span>
                    <span class="font-mono font-bold tabular-nums text-[11px] text-ink shrink-0">{p.proiecte}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </section>

    <!-- Cross-source link: euFundsAndSeap recipe -->
    <section class="border-b-2 border-ink bg-stamp/40">
      <div class="max-w-content mx-auto px-4 md:px-8 py-8">
        <div class="grid md:grid-cols-[1fr_auto] gap-4 items-baseline">
          <div>
            <div class="label-meta mb-2">Cross-source · A ∩ B</div>
            <h2 class="font-display font-bold text-2xl md:text-3xl text-ink mb-2">
              Firme care primesc fonduri UE <em class="font-serif italic">și</em> câștigă contracte de la stat
            </h2>
            <p class="font-serif italic text-base text-ink/70 max-w-2xl">
              Joinul devoalează firmele cu acces la ambele țevi de bani publici — fonduri europene private (B) ⊕ contracte SEAP (A).
            </p>
          </div>
          <a href="/retete/firme-cu-fonduri-eu-si-seap" class="chip-brutal bg-ink text-paper border-ink hover:bg-paper hover:text-ink shrink-0 self-start md:self-center whitespace-nowrap">
            vezi rețeta →
          </a>
        </div>
      </div>
    </section>

    <!-- Top 100 contracts UE -->
    <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">A · Top 100 contracte SEAP-UE după valoare</div>
          <a href="/top-contracte?ue=1" class="label-meta normal-case tracking-normal hover:bg-stamp">
            vezi în clasament general →
          </a>
        </div>

        {contracts.length === 0 && (
          <div class="border-2 border-ink p-12 text-center">
            <div class="label-meta mb-2">Niciun contract UE</div>
            <p class="font-display text-xl">Datele se actualizează zilnic.</p>
          </div>
        )}

        <ol class="divide-y-2 divide-ink/20">
          {contracts.map((c, i) => (
            <li>
              <article class="grid grid-cols-[40px_1fr] md:grid-cols-[40px_110px_1fr_auto] gap-x-4 md:gap-x-5 gap-y-1 py-5 px-2 -mx-2 hover:bg-stamp transition-none items-baseline">
                <div class="font-mono text-sm md:text-base font-bold tabular-nums text-ink/60 self-start">
                  {String(i + 1).padStart(2, '0')}
                </div>
                <div class="font-mono text-xs tabular-nums text-ink/60 hidden md:block self-start">
                  {dateFmt(c.publication_date)}
                </div>
                <div class="min-w-0">
                  <div class="font-mono text-xs tabular-nums text-ink/60 mb-1 md:hidden">
                    {dateFmt(c.publication_date)}
                  </div>
                  <h2 class="font-display font-semibold text-base md:text-lg text-ink leading-snug mb-1">
                    <a href={`/anunt/${c.id}`} class="hover:underline">{c.title || c.ref_number || `#${c.id}`}</a>
                  </h2>
                  <div class="flex flex-wrap gap-x-3 gap-y-0.5 label-meta normal-case tracking-normal text-ink/70">
                    {c.eu_program && (
                      <span class="bg-state text-paper px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-meta">{c.eu_program}</span>
                    )}
                    {c.authority_name && (
                      <span>
                        <a href={`/autoritate/${c.authority_cui}`} class="text-ink hover:underline font-medium">{c.authority_name}</a>
                        {c.authority_county && <span class="text-ink/50"> · {c.authority_county}</span>}
                      </span>
                    )}
                    {c.supplier_name && (
                      <span>→ <a href={`/firma/${(c.supplier_cui || '').replace(/^RO\s*/i, '').trim()}`} class="text-ink hover:underline font-medium">{c.supplier_name}</a></span>
                    )}
                    {c.cpv_division_name && (
                      <a href={`/categoria/${c.cpv_division}`} class="text-ink/70 hover:underline">
                        {c.cpv_emoji && <span class="mr-1">{c.cpv_emoji}</span>}{c.cpv_division_name}
                      </a>
                    )}
                  </div>
                </div>
                <div class="text-right shrink-0 self-start col-start-2 md:col-start-4">
                  <div class="font-mono font-bold tabular-nums text-lg md:text-2xl text-ink whitespace-nowrap leading-none">
                    {fmt(c.awarded_value)}
                  </div>
                  <div class="font-body text-xs text-ink/60 mt-1">RON</div>
                </div>
              </article>
            </li>
          ))}
        </ol>
      </div>
    </section>

    <!-- Footer strip -->
    <footer class="bg-ink text-paper">
      <div class="max-w-content mx-auto px-4 py-8 flex flex-wrap items-baseline justify-between gap-3">
        <div class="label-meta text-paper/60">Dashboard-uri one-click</div>
        <div class="flex flex-wrap gap-2">
          <a href="/azi" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Azi</a>
          <a href="/top-contracte" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Top contracte</a>
          <a href="/top-firme" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Top firme</a>
          <a href="/cauta" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Caută SEAP</a>
          <a href="/fonduri-ue/anunturi" class="chip-brutal bg-stamp text-ink border-stamp hover:bg-paper hover:text-ink">Anunțuri EU</a>
        </div>
      </div>
    </footer>
  </main>
</AchizitiiLayout>
