---
import AchizitiiLayout from '../layouts/AchizitiiLayout.astro';
import {
  getTopSuppliersRanked,
  getTopSuppliersStats,
} from '../lib/dashboard-queries.js';

export const prerender = false;

const url = Astro.url;
const sortBy: 'total_awarded' | 'contracts_won' =
  url.searchParams.get('sort') === 'contracte' ? 'contracts_won' : 'total_awarded';

const [suppliers, stats] = await Promise.all([
  getTopSuppliersRanked(100, sortBy),
  getTopSuppliersStats(),
]);

const fmt = (n: number | null | undefined) =>
  n == null ? '–' : new Intl.NumberFormat('ro-RO', { maximumFractionDigits: 0 }).format(n);

const maxValue = Math.max(...suppliers.map(s => Number(s.total_awarded) || 0), 1);
---

<AchizitiiLayout
  title="Top 100 firme câștigătoare — ultimele 12 luni · vreaudigital.ro"
  description="Clasamentul firmelor cu cele mai multe contracte publice câștigate în România în ultimele 12 luni."
>
  <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 100 firme câștigătoare</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">F</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 firme câștigătoare
            </h1>
            <p class="font-serif italic text-base md:text-lg text-ink/70 mt-3 max-w-3xl">
              Firmele care au câștigat cele mai multe contracte publice în România în ultimele 12 luni.
            </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-3 gap-0 divide-x-2 divide-ink/20">
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(stats.distinct_suppliers)}</div>
          <div class="stat-label">Firme distincte</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(stats.top_supplier_total)}</div>
          <div class="stat-label">RON · top firmă</div>
        </div>
        <div class="stat-tile px-3 md:px-6 col-span-2 md:col-span-1">
          <div class="stat-num">{fmt(stats.median_total)}</div>
          <div class="stat-label">RON · mediană</div>
        </div>
      </div>
    </section>

    <!-- Sort 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">Sortează după:</span>
        <a href="/top-firme"
           class:list={['chip-brutal', { 'chip-active bg-ink text-paper': sortBy === 'total_awarded' }, { 'hover:bg-stamp': sortBy !== 'total_awarded' }]}>
          Valoare cumulată
        </a>
        <a href="/top-firme?sort=contracte"
           class:list={['chip-brutal', { 'chip-active bg-ink text-paper': sortBy === 'contracts_won' }, { 'hover:bg-stamp': sortBy !== 'contracts_won' }]}>
          Număr contracte
        </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">
        {suppliers.length === 0 && (
          <div class="border-2 border-ink p-12 text-center">
            <div class="label-meta mb-2">Nicio firmă</div>
            <p class="font-display text-xl">Datele se actualizează zilnic.</p>
          </div>
        )}

        <ol class="divide-y-2 divide-ink/20">
          {suppliers.map((s, i) => {
            const cui = (s.supplier_cui || '').replace(/^RO\s*/i, '').trim();
            const pct = Math.max(2, Math.round(100 * (Number(s.total_awarded) || 0) / maxValue));
            return (
              <li>
                <a href={`/firma/${cui}`} class="grid grid-cols-[40px_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="min-w-0">
                    <h2 class="font-display font-semibold text-base md:text-lg text-ink leading-snug mb-1 truncate">
                      {s.supplier_name || s.supplier_cui}
                    </h2>
                    <div class="flex flex-wrap gap-x-3 gap-y-0.5 label-meta normal-case tracking-normal text-ink/70 mb-2">
                      <span>CUI <span class="font-mono">{cui || s.supplier_cui}</span></span>
                      <span class="text-ink/40">·</span>
                      <span><span class="font-mono">{fmt(s.contracts_won)}</span> contracte</span>
                      <span class="text-ink/40">·</span>
                      <span><span class="font-mono">{fmt(s.distinct_clients)}</span> clienți distincți</span>
                    </div>
                    <div class="bar-track h-2" style="background:#E5E1D8">
                      <div class="bar-fill" style={`width:${pct}%`}></div>
                    </div>
                  </div>
                  <div class="text-right shrink-0 self-start">
                    <div class="font-mono font-bold tabular-nums text-lg md:text-2xl text-ink whitespace-nowrap leading-none">
                      {fmt(s.total_awarded)}
                    </div>
                    <div class="font-body text-xs text-ink/60 mt-1">RON</div>
                  </div>
                </a>
              </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="/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>
