---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import {
  getOverpricedContracts,
  getOverpricedCount,
} 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] = await Promise.all([
  getOverpricedContracts(limit, offset),
  getOverpricedCount(),
]);

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

<AchizitiiLayout
  title="Peste piață — overprice — vreaudigital.ro"
  description={`${fmt(total)} contracte cu valoare peste dublul medianei pe categoria CPV.`}
>
  <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">Overprice</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-3xl md:text-4xl">5</div>
          <div class="flex-1 min-w-0">
            <div class="flex flex-wrap items-baseline gap-3 mb-2">
              <span class="chip-brutal bg-stamp text-ink">Avertisment</span>
              <span class="label-meta">Indicator 5 / 5</span>
            </div>
            <h1 class="font-display font-bold text-3xl md:text-5xl leading-[1.05] tracking-tight text-ink">
              Peste piață
            </h1>
            <p class="font-serif italic text-base md:text-lg text-ink/80 mt-3 max-w-3xl">
              Contracte câștigate la valori care depășesc dublul medianei calculate pe diviziunea CPV
              (primele 2 cifre din codul CPV). Outliers de preț pot indica supra-evaluare, lipsă de
              concurență sau servicii speciale care merită explicate public.
            </p>
          </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-3 gap-0 divide-x-2 divide-ink/20">
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(total)}</div>
          <div class="stat-label">Outliers > 2× median</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">2×</div>
          <div class="stat-label">Pragul de detectare</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">CPV-2</div>
          <div class="stat-label">Bază comparație</div>
        </div>
      </div>
    </section>

    <section class="max-w-content mx-auto px-4 md:px-8 py-10">
      <div class="flex items-baseline justify-between mb-4">
        <h2 class="label-meta">Sortat după ratio față de mediană</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-stamp text-ink py-0.5 px-1.5 text-[10px]">
                    ×{c.ratio_to_median != null ? Number(c.ratio_to_median).toFixed(1) : '?'}
                  </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 whitespace-nowrap">
                <div class="font-mono font-bold tabular-nums text-base md:text-lg text-ink">
                  {fmt(c.awarded_value)}
                  <span class="font-body text-xs text-ink/60 font-normal ml-1">RON</span>
                </div>
                <div class="label-meta normal-case tracking-normal text-ink/60">median CPV {fmt(c.median_value)}</div>
              </div>
            </a>
          </li>
        ))}
      </ol>

      {(prevHref || nextHref) && (
        <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>
  </main>
</AchizitiiLayout>
