---
import AchizitiiLayout from '../layouts/AchizitiiLayout.astro';
import {
  getTopContractsRecent,
  getTopContractsStats,
  type TopContractsFilter,
} from '../lib/dashboard-queries.js';

export const prerender = false;

// CDN cache: anonymous page, 12-month rolling window — 5 min staleness OK.
// stale-while-revalidate lets CF serve stale instantly while refreshing.
Astro.response.headers.set('Cache-Control', 'public, max-age=60, s-maxage=300, stale-while-revalidate=600');

// Read filter from query string
const url = Astro.url;
const eu_only = url.searchParams.get('ue') === '1';
const has_lots = url.searchParams.get('loturi') === '1';
const framework = url.searchParams.get('cadru') === '1';

const filter: TopContractsFilter = { eu_only, has_lots, framework };
const activeFilter = eu_only ? 'ue' : has_lots ? 'loturi' : framework ? 'cadru' : 'toate';

const [contracts, stats] = await Promise.all([
  getTopContractsRecent(100, filter),
  getTopContractsStats(filter),
]);

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, '.') : '–';

// Single-toggle filter (radio-style): clicking a chip selects only it
function tabHref(key: 'toate' | 'ue' | 'loturi' | 'cadru'): string {
  if (key === 'toate') return '/top-contracte';
  return `/top-contracte?${key === 'ue' ? 'ue' : key === 'loturi' ? 'loturi' : 'cadru'}=1`;
}

const tabs: { key: 'toate' | 'ue' | 'loturi' | 'cadru'; label: string }[] = [
  { key: 'toate', label: 'Toate' },
  { key: 'ue', label: 'Doar UE' },
  { key: 'loturi', label: 'Cu loturi' },
  { key: 'cadru', label: 'Acord-cadru' },
];
---

<AchizitiiLayout
  title="Top 100 contracte — ultimele 12 luni · vreaudigital.ro"
  description="Cele mai mari 100 de contracte atribuite în România în ultimele 12 luni. Date oficiale SEAP."
>
  <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">Top contracte 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">€</div>
          <div class="flex-1 min-w-0">
            <div class="label-meta mb-2">Clasament · ultimele 12 luni</div>
            <h1 class="font-display font-bold text-3xl md:text-5xl leading-[1.05] tracking-tight text-ink">
              Top 100 contracte după valoare
            </h1>
            <p class="font-serif italic text-base md:text-lg text-ink/70 mt-3 max-w-3xl">
              Cele mai mari contracte atribuite în România în ultimele 12 luni — sortate descrescător după valoarea atribuită.
            </p>
          </div>
        </div>
      </div>
    </header>

    <!-- Stats register -->
    <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(stats.total_awarded)}</div>
          <div class="stat-label">RON total atribuit</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(stats.contracts)}</div>
          <div class="stat-label">Contracte</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(stats.avg_value)}</div>
          <div class="stat-label">RON medie</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(stats.median_value)}</div>
          <div class="stat-label">RON mediană</div>
        </div>
      </div>
    </section>

    <!-- Filter tabs -->
    <section class="border-b-2 border-ink bg-paper">
      <div class="max-w-content mx-auto px-4 py-5 flex flex-wrap items-center gap-2">
        <span class="label-meta mr-2">Filtru:</span>
        {tabs.map(t => (
          <a href={tabHref(t.key)}
             class:list={[
               'chip-brutal',
               { 'chip-active bg-ink text-paper': activeFilter === t.key },
               { 'hover:bg-stamp': activeFilter !== t.key },
             ]}>
            {t.label}
          </a>
        ))}
      </div>
    </section>

    <!-- Top 100 register -->
    <section class="border-b-2 border-ink">
      <div class="max-w-content mx-auto px-4 md:px-8 py-10">
        {contracts.length === 0 && (
          <div class="border-2 border-ink p-12 text-center">
            <div class="label-meta mb-2">Niciun contract</div>
            <p class="font-display text-xl">Schimbă filtrul pentru rezultate.</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 col-span-1 md:col-span-1">
                  <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.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>
                    )}
                    {c.eu_funded && c.eu_funded.toLowerCase().startsWith('da') && (
                      <span class="bg-state text-paper px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-meta">UE</span>
                    )}
                    {c.has_lots && c.lots_count && (
                      <span class="text-ink/60"><span class="font-mono">{c.lots_count}</span> loturi</span>
                    )}
                    {c.framework_agreement && (
                      <span class="text-ink/60">acord-cadru</span>
                    )}
                  </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-firme" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Top firme</a>
          <a href="/fonduri-ue" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Fonduri UE</a>
          <a href="/cauta" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Caută</a>
        </div>
      </div>
    </footer>
  </main>
</AchizitiiLayout>
