---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import {
  getRiskOverview,
  getSingleBidderContracts,
  getSuspiciousSavings,
  getOverpricedContracts,
  getAuthorityConcentrations,
  getShortDeadlineContracts,
} from '../../lib/risk-queries.js';

export const prerender = false;

const [overview, singleTop, savingsTop, overpricedTop, concTop, shortTop] = await Promise.all([
  getRiskOverview(),
  getSingleBidderContracts(5, 0),
  getSuspiciousSavings(5, 0),
  getOverpricedContracts(5, 0),
  getAuthorityConcentrations(0.6, 5),
  getShortDeadlineContracts(5, 0),
]);

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 pct = (n: number) => Math.round(n * 100);

const flags = [
  {
    code: 'single_bidder',
    severity: 'high' as const,
    title: 'Un singur ofertant',
    short: 'Single bidder',
    desc: 'Contracte câștigate cu o singură ofertă primită — semn că procedura n-a fost competitivă.',
    href: '/risc/single-bidder',
    count: overview.single_bidder,
    samples: singleTop,
    sampleField: 'awarded_value' as const,
  },
  {
    code: 'concentrare',
    severity: 'high' as const,
    title: 'Concentrare furnizori',
    short: 'Top supplier > 60%',
    desc: 'Autorități unde un singur furnizor a câștigat peste 60% din valoarea anuală — risc de captură.',
    href: '/risc/concentrare',
    count: overview.authority_concentration,
    samples: concTop,
    sampleField: 'top_supplier_share' as const,
  },
  {
    code: 'overprice',
    severity: 'medium' as const,
    title: 'Peste piață',
    short: 'Overprice > 2× median CPV',
    desc: 'Contracte cu valori atribuite peste dublul medianei pe categoria CPV.',
    href: '/risc/overprice',
    count: overview.overprice,
    samples: overpricedTop,
    sampleField: 'awarded_value' as const,
  },
  {
    code: 'suspicious_savings',
    severity: 'medium' as const,
    title: 'Economii suspect mari',
    short: '> 50% sub estimat',
    desc: 'Contracte unde câștigătorul a oferit mai puțin de jumătate din valoarea estimată — fie estimare proastă, fie risc de calitate slabă.',
    href: '/risc/economii-suspect',
    count: overview.suspicious_savings,
    samples: savingsTop,
    sampleField: 'savings_pct' as const,
  },
  {
    code: 'short_deadline',
    severity: 'medium' as const,
    title: 'Termen scurt',
    short: '< 10 zile pentru ofertă',
    desc: 'Anunțuri cu mai puțin de 10 zile între publicare și termen — uneori indică pregătire prealabilă cu un furnizor.',
    href: '/risc/termen-scurt',
    count: overview.short_deadline,
    samples: shortTop,
    sampleField: 'days_gap' as const,
  },
];
---

<AchizitiiLayout
  title="Indicatori de risc — vreaudigital.ro"
  description="5 indicatori de risc pentru achiziții publice România, bazați pe ghidul Open Contracting Partnership. Single bidder, concentrare furnizori, peste piață."
>
  <main class="bg-paper text-ink min-h-screen">

    <!-- Top register 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">Indicatori de risc</span>
      </div>
    </div>

    <!-- Header: monogram-signal R -->
    <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">R</div>
          <div class="flex-1 min-w-0">
            <div class="label-meta mb-2">Red flags · OCP</div>
            <h1 class="font-display font-bold text-3xl md:text-5xl leading-[1.05] tracking-tight text-ink">
              Indicatori de risc în achizițiile publice
            </h1>
            <p class="font-serif italic text-base md:text-lg text-ink/80 mt-3 max-w-3xl">
              Cinci semnale automate, calculate pe datele oficiale SEAP. Inspirate din
              ghidul <a href="https://www.open-contracting.org/" target="_blank" class="underline hover:bg-stamp">Open Contracting Partnership</a>.
              Un flag nu înseamnă fraudă — înseamnă "merită investigat".
            </p>
          </div>
        </div>
      </div>
    </header>

    <!-- 5 stat tiles -->
    <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-5 gap-0 divide-x-2 divide-ink/20">
        {flags.map(f => (
          <a href={f.href} class="stat-tile px-3 md:px-4 py-2 hover:bg-stamp transition-none">
            <div class={`stat-num ${f.severity === 'high' ? 'text-signal' : ''}`}>{fmt(f.count)}</div>
            <div class="stat-label">{f.short}</div>
          </a>
        ))}
      </div>
    </section>

    <!-- Per-flag detail blocks -->
    <section class="max-w-content mx-auto px-4 py-10 space-y-12">
      {flags.map(f => (
        <article class="border-2 border-ink">
          <header class="flex flex-wrap items-baseline justify-between gap-3 px-5 md:px-7 py-5 border-b-2 border-ink bg-paper">
            <div class="flex items-baseline gap-3 min-w-0">
              <span class={`chip-brutal ${f.severity === 'high' ? 'bg-signal text-paper border-ink' : 'bg-stamp text-ink'}`}>
                {f.severity === 'high' ? 'Critic' : 'Avertisment'}
              </span>
              <h2 class="font-display font-bold text-2xl md:text-3xl text-ink leading-tight">{f.title}</h2>
            </div>
            <div class="flex items-baseline gap-3">
              <span class="font-mono font-bold text-2xl tabular-nums">{fmt(f.count)}</span>
              <a href={f.href} class="btn-brutal">Vezi toate →</a>
            </div>
          </header>

          <p class="font-serif italic text-base md:text-lg text-ink/80 px-5 md:px-7 py-4 border-b-2 border-ink/30 max-w-4xl">
            {f.desc}
          </p>

          <div class="px-5 md:px-7 py-3">
            <div class="label-meta mb-3">Top 5 exemple</div>

            {f.code === 'concentrare' ? (
              <ol class="divide-y divide-ink/20">
                {(f.samples as any[]).map((s, i) => (
                  <li>
                    <a href={`/autoritate/${s.authority_cui}`}
                       class="grid md:grid-cols-[40px_1fr_auto] gap-x-4 gap-y-1 py-3 px-2 -mx-2 hover:bg-stamp transition-none items-baseline">
                      <span class="font-mono text-xs text-ink/40 tabular-nums">{String(i + 1).padStart(2, '0')}</span>
                      <div class="min-w-0">
                        <div class="font-display font-semibold text-base text-ink truncate">{s.authority_name}</div>
                        <div class="label-meta normal-case tracking-normal text-ink/60 mt-0.5">
                          {s.year} · top: <span class="text-ink">{s.top_supplier_name}</span>
                        </div>
                      </div>
                      <div class="text-right whitespace-nowrap">
                        <div class="font-mono font-bold tabular-nums text-base text-signal">{pct(s.top_supplier_share)}%</div>
                        <div class="label-meta normal-case tracking-normal text-ink/60">{fmt(s.top_supplier_value)} RON</div>
                      </div>
                    </a>
                  </li>
                ))}
              </ol>
            ) : (
              <ol class="divide-y divide-ink/20">
                {(f.samples as any[]).map((s, i) => (
                  <li>
                    <a href={`/anunt/${s.id}`}
                       class="grid md:grid-cols-[40px_110px_1fr_auto] gap-x-4 gap-y-1 py-3 px-2 -mx-2 hover:bg-stamp transition-none items-baseline">
                      <span class="font-mono text-xs text-ink/40 tabular-nums">{String(i + 1).padStart(2, '0')}</span>
                      <span class="font-mono text-xs tabular-nums text-ink/60">{dateFmt(s.publication_date)}</span>
                      <div class="min-w-0">
                        <div class="font-display font-semibold text-base text-ink leading-snug">{s.title || s.ref_number}</div>
                        <div class="label-meta normal-case tracking-normal text-ink/60 mt-0.5">
                          {s.authority_name && <span>{s.authority_name}</span>}
                          {s.supplier_name && <span> → {s.supplier_name}</span>}
                        </div>
                      </div>
                      <div class="text-right whitespace-nowrap">
                        {f.code === 'suspicious_savings' && s.savings_pct != null ? (
                          <>
                            <div class="font-mono font-bold tabular-nums text-base text-stamp" style="color:#000;background:#F4D03F;padding:2px 6px;display:inline-block">−{s.savings_pct}%</div>
                            <div class="label-meta normal-case tracking-normal text-ink/60 mt-1">{fmt(s.awarded_value)} / {fmt(s.estimated_value)} est.</div>
                          </>
                        ) : f.code === 'overprice' && s.ratio_to_median != null ? (
                          <>
                            <div class="font-mono font-bold tabular-nums text-base text-signal">×{Number(s.ratio_to_median).toFixed(1)}</div>
                            <div class="label-meta normal-case tracking-normal text-ink/60 mt-1">{fmt(s.awarded_value)} RON · median {fmt(s.median_value)}</div>
                          </>
                        ) : f.code === 'short_deadline' && s.days_gap != null ? (
                          <>
                            <div class="font-mono font-bold tabular-nums text-base text-ink">{Number(s.days_gap).toFixed(1)}z</div>
                            <div class="label-meta normal-case tracking-normal text-ink/60 mt-1">{fmt(s.estimated_value)} RON est.</div>
                          </>
                        ) : (
                          <div class="font-mono font-bold tabular-nums text-base text-ink">
                            {fmt(s.awarded_value)}
                            <span class="font-body text-xs text-ink/60 font-normal ml-1">RON</span>
                          </div>
                        )}
                      </div>
                    </a>
                  </li>
                ))}
                {(f.samples as any[]).length === 0 && (
                  <li class="py-6 text-center label-meta normal-case tracking-normal text-ink/60">
                    Niciun exemplu în datele curente.
                  </li>
                )}
              </ol>
            )}
          </div>
        </article>
      ))}
    </section>

    <!-- Methodology footer -->
    <footer class="bg-ink text-paper">
      <div class="max-w-content mx-auto px-4 py-10">
        <div class="label-meta text-paper/60 mb-3">Metodologie</div>
        <div class="font-serif italic text-base md:text-lg text-paper/90 max-w-3xl space-y-3">
          <p>Indicatorii sunt calculați pe baza câmpurilor publice SEAP: <span class="font-mono text-sm not-italic text-paper">awarded_value, estimated_value, deadline_submission, num_offers, all_winners</span>.</p>
          <p>Pentru "concentrare furnizori" agregăm pe an calendaristic, ultimele 36 de luni. Pentru "peste piață" calculăm mediana pe diviziune CPV (primele 2 cifre). Pragurile (50%, 60%, 2×, 10 zile) sunt configurabile.</p>
          <p class="text-paper/70">Codul SQL este în <a href="https://github.com/" target="_blank" class="underline hover:bg-stamp hover:text-ink">depozitul public</a>. Pull-requests welcome.</p>
        </div>
      </div>
    </footer>
  </main>
</AchizitiiLayout>
