---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import {
  getSingleBidderContracts,
  getSingleBidderCount,
  getSingleBidderTopAuthorities,
} from '../../lib/risk-queries.js';

export const prerender = false;

const url = Astro.url;
const limit = 30;
const offset = parseInt(url.searchParams.get('offset') || '0', 10) || 0;

const [contracts, total, topAuth] = await Promise.all([
  getSingleBidderContracts(limit, offset),
  getSingleBidderCount(),
  getSingleBidderTopAuthorities(10),
]);

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 pageBase = '/risc/single-bidder';
const prevHref = offset > 0 ? `${pageBase}?offset=${Math.max(0, offset - limit)}` : null;
const nextHref = offset + limit < total ? `${pageBase}?offset=${offset + limit}` : null;
---

<AchizitiiLayout
  title="Single bidder — un singur ofertant — vreaudigital.ro"
  description={`${fmt(total)} contracte câștigate cu un singur ofertant. Risc înalt de necompetitivitate.`}
>
  <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="/risc" class="font-mono text-xs uppercase tracking-meta hover:text-stamp">← indicatori de risc</a>
        <span class="font-mono text-xs uppercase tracking-meta text-paper/60">Single bidder</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-signal w-16 h-16 md:w-20 md:h-20 text-3xl md:text-4xl">1</div>
          <div class="flex-1 min-w-0">
            <div class="flex flex-wrap items-baseline gap-3 mb-2">
              <span class="chip-brutal bg-signal text-paper border-ink">Critic</span>
              <span class="label-meta">Indicator 1 / 5</span>
            </div>
            <h1 class="font-display font-bold text-3xl md:text-5xl leading-[1.05] tracking-tight text-ink">
              Un singur ofertant
            </h1>
            <p class="font-serif italic text-base md:text-lg text-ink/80 mt-3 max-w-3xl">
              Contracte câștigate cu o singură ofertă primită. Procedurile cu un singur ofertant nu mai sunt
              competitive — fie cerințele sunt prea înguste, fie alți potențiali ofertanți au fost descurajați.
            </p>
          </div>
        </div>
      </div>
    </header>

    <!-- Stat strip -->
    <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 text-signal">{fmt(total)}</div>
          <div class="stat-label">Contracte single-bidder</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(contracts.reduce((s, c) => s + (Number(c.awarded_value) || 0), 0))}</div>
          <div class="stat-label">RON pe pagina curentă</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{topAuth.length}</div>
          <div class="stat-label">Autorități cu ≥3 cazuri</div>
        </div>
      </div>
    </section>

    <div class="max-w-content mx-auto grid lg:grid-cols-12 gap-0">
      <!-- Sidebar: top authorities -->
      <aside class="lg:col-span-4 lg:border-r-2 lg:border-ink px-4 md:px-6 py-8">
        <h3 class="label-meta mb-4">Top autorități după rată</h3>
        <ol class="divide-y divide-ink/20">
          {topAuth.map((a, i) => (
            <li>
              <a href={`/autoritate/${a.authority_cui}`} class="block py-3 px-2 -mx-2 hover:bg-stamp transition-none">
                <div class="flex items-baseline justify-between gap-2 mb-1">
                  <span class="font-mono text-xs text-ink/40 tabular-nums">{String(i + 1).padStart(2, '0')}</span>
                  <span class="font-mono font-bold text-sm tabular-nums text-signal">{Math.round(Number(a.share) * 100)}%</span>
                </div>
                <div class="font-display text-sm text-ink leading-snug">{a.authority_name}</div>
                <div class="label-meta normal-case tracking-normal text-ink/60 mt-1">
                  <span class="font-mono">{a.total}</span> single bidder
                </div>
              </a>
            </li>
          ))}
        </ol>
      </aside>

      <!-- Results -->
      <section class="lg:col-span-8 px-4 md:px-6 py-8">
        <div class="flex items-baseline justify-between mb-4">
          <h2 class="label-meta">Contracte (sortate după valoare ↓)</h2>
          <span class="label-meta">
            <span class="font-mono">{offset + 1}–{Math.min(offset + limit, total)}</span> din <span class="font-mono">{fmt(total)}</span>
          </span>
        </div>

        <ol class="divide-y-2 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-5 hover:bg-stamp transition-none px-2 -mx-2">
                <div class="font-mono text-xs tabular-nums text-ink/60">{dateFmt(c.publication_date)}</div>
                <div class="min-w-0">
                  <div class="flex flex-wrap items-center gap-2 mb-1 label-meta normal-case tracking-normal text-ink/60">
                    {c.cpv_division_name && <span>{c.cpv_division_name}</span>}
                    <span class="chip-brutal bg-signal text-paper border-ink py-0.5 px-1.5 text-[10px]">
                      {c.num_offers === 1 ? '1 ofertă' : '1 câștigător'}
                    </span>
                  </div>
                  <h3 class="font-display font-semibold text-base md:text-lg text-ink leading-snug mb-1">
                    {c.title || c.ref_number}
                  </h3>
                  <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>{c.authority_name}{c.authority_county ? ` · ${c.authority_county}` : ''}</span>}
                    {c.supplier_name && <span>→ <span class="text-ink">{c.supplier_name}</span></span>}
                  </div>
                </div>
                <div class="text-right shrink-0 self-start">
                  <div class="font-mono font-bold tabular-nums text-base md:text-lg text-ink whitespace-nowrap">
                    {fmt(c.awarded_value)}
                    <span class="font-body text-xs text-ink/60 font-normal ml-1">RON</span>
                  </div>
                </div>
              </a>
            </li>
          ))}
        </ol>

        <nav class="flex items-center justify-between mt-10 pt-6 border-t-2 border-ink">
          {prevHref ? <a href={prevHref} class="btn-brutal">← Anterior</a> : <span></span>}
          <span class="label-meta">
            <span class="font-mono">{offset + 1}–{Math.min(offset + limit, total)}</span> din <span class="font-mono">{fmt(total)}</span>
          </span>
          {nextHref ? <a href={nextHref} class="btn-brutal">Următor →</a> : <span></span>}
        </nav>
      </section>
    </div>
  </main>
</AchizitiiLayout>
