---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import {
  getAuthorityConcentrations,
  getConcentrationCount,
} from '../../lib/risk-queries.js';

export const prerender = false;

const url = Astro.url;
const limit = 50;
const offset = parseInt(url.searchParams.get('offset') || '0', 10) || 0;
const threshold = parseFloat(url.searchParams.get('threshold') || '0.6') || 0.6;

// MV doesn't support easy paging without re-querying; pull all then slice
const all = await getAuthorityConcentrations(threshold, 500);
const total = await getConcentrationCount(threshold);
const rows = all.slice(offset, offset + limit);

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

const pageBase = `/risc/concentrare?threshold=${threshold}`;
const prevHref = offset > 0 ? `${pageBase}&offset=${Math.max(0, offset - limit)}` : null;
const nextHref = offset + limit < total ? `${pageBase}&offset=${offset + limit}` : null;

// Histogram of shares
const buckets: Record<string, number> = { '60–70%': 0, '70–80%': 0, '80–90%': 0, '90–100%': 0 };
for (const a of all) {
  const p = pct(a.top_supplier_share);
  if (p < 70) buckets['60–70%']++;
  else if (p < 80) buckets['70–80%']++;
  else if (p < 90) buckets['80–90%']++;
  else buckets['90–100%']++;
}
const maxBucket = Math.max(...Object.values(buckets), 1);
---

<AchizitiiLayout
  title="Concentrare furnizori — captură de autoritate — vreaudigital.ro"
  description={`${fmt(total)} autorități unde un singur furnizor a câștigat peste ${pct(threshold)}% din valoarea anuală.`}
>
  <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">Concentrare</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">4</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 4 / 5</span>
            </div>
            <h1 class="font-display font-bold text-3xl md:text-5xl leading-[1.05] tracking-tight text-ink">
              Concentrare furnizori
            </h1>
            <p class="font-serif italic text-base md:text-lg text-ink/80 mt-3 max-w-3xl">
              Autorități unde un singur furnizor a câștigat peste {pct(threshold)}% din valoarea contractelor
              dintr-un an calendaristic. Concentrarea ridicată poate indica relații preferențiale, captură de
              autoritate sau lipsă de furnizori alternativi.
            </p>
          </div>
        </div>
      </div>
    </header>

    <!-- Stat strip + threshold filter -->
    <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 text-signal">{fmt(total)}</div>
          <div class="stat-label">Autoritate × an</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{pct(threshold)}%</div>
          <div class="stat-label">Prag minim</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{all.length > 0 ? pct(Math.max(...all.map(a => a.top_supplier_share))) : 0}%</div>
          <div class="stat-label">Concentrare maximă</div>
        </div>
        <div class="stat-tile px-3 md:px-6 flex flex-col justify-center">
          <div class="label-meta mb-1">Schimbă pragul</div>
          <div class="flex flex-wrap gap-1">
            {[0.6, 0.7, 0.8, 0.9].map(t => (
              <a href={`/risc/concentrare?threshold=${t}`}
                 class={`chip-brutal py-1 ${threshold === t ? 'chip-active' : ''}`}>
                {pct(t)}%
              </a>
            ))}
          </div>
        </div>
      </div>
    </section>

    <!-- Histogram -->
    <section class="border-b-2 border-ink">
      <div class="max-w-content mx-auto px-4 md:px-8 py-8">
        <h2 class="label-meta mb-4">Distribuția gradului de concentrare</h2>
        <div class="space-y-2">
          {Object.entries(buckets).map(([k, v]) => (
            <div class="grid grid-cols-[100px_1fr_60px] items-center gap-3">
              <span class="font-mono text-xs uppercase tracking-meta">{k}</span>
              <div class="bar-track h-5"><div class="bar-fill" style={`width:${(v / maxBucket) * 100}%;background:#C8102E`}></div></div>
              <span class="font-mono text-xs tabular-nums text-right">{v}</span>
            </div>
          ))}
        </div>
      </div>
    </section>

    <!-- Table of authorities -->
    <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">Autorități cu concentrare ≥ {pct(threshold)}%</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">
        {rows.map((a, i) => (
          <li>
            <a href={`/autoritate/${a.authority_cui}`}
               class="grid md:grid-cols-[40px_1fr_auto_auto] gap-x-5 gap-y-1 py-5 px-2 -mx-2 hover:bg-stamp transition-none items-baseline">
              <span class="font-mono text-xs text-ink/40 tabular-nums">{String(offset + i + 1).padStart(3, '0')}</span>
              <div class="min-w-0">
                <div class="font-display font-semibold text-base md:text-lg text-ink leading-snug">
                  {a.authority_name}
                </div>
                <div class="label-meta normal-case tracking-normal text-ink/70 mt-1">
                  <span class="font-mono">{a.year}</span> · top: <span class="text-ink font-medium">{a.top_supplier_name}</span> ({a.top_supplier_contracts} contracte)
                </div>
              </div>
              <div class="text-right whitespace-nowrap">
                <div class="font-mono font-bold tabular-nums text-base text-ink">{fmt(a.top_supplier_value)}</div>
                <div class="label-meta normal-case tracking-normal text-ink/60">din {fmt(a.year_total)} RON</div>
              </div>
              <div class="text-right whitespace-nowrap pl-4">
                <div class="font-mono font-bold tabular-nums text-2xl md:text-3xl text-signal">{pct(a.top_supplier_share)}%</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>
  </main>
</AchizitiiLayout>
