---
import AchizitiiLayout from '../layouts/AchizitiiLayout.astro';
import { Sankey } from '../components/viz/Sankey.tsx';
import { Treemap } from '../components/viz/Treemap.tsx';
import { BarRace } from '../components/viz/BarRace.tsx';
import { getSankeyFlows, getTreemapData, getBarRaceData } from '../lib/viz-queries.js';

export const prerender = false;

const tabRaw = (Astro.url.searchParams.get('tab') || 'flow').toLowerCase();
const tab: 'flow' | 'cpv' | 'race' =
  tabRaw === 'cpv' ? 'cpv' : tabRaw === 'race' ? 'race' : 'flow';

let sankey: Awaited<ReturnType<typeof getSankeyFlows>> | null = null;
let treemap: Awaited<ReturnType<typeof getTreemapData>> | null = null;
let barRace: Awaited<ReturnType<typeof getBarRaceData>> | null = null;

if (tab === 'flow') sankey = await getSankeyFlows(12);
else if (tab === 'cpv') treemap = await getTreemapData(12);
else if (tab === 'race') barRace = await getBarRaceData(12);

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

<AchizitiiLayout
  title="Explorer · vizualizări — vreaudigital.ro"
  description="Explorează vizual fluxul banilor publici: Sankey pe județe și firme, treemap CPV, evoluție lunară top firme."
>
  <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">Explorer · vizualizări</span>
      </div>
    </div>

    <!-- Header -->
    <header class="border-b-2 border-ink">
      <div class="max-w-content mx-auto px-4 py-8 md:py-10">
        <div class="font-mono text-[10px] md:text-xs uppercase tracking-meta text-ink/60 mb-2">Explorer date · ultimele 12 luni</div>
        <h1 class="font-display font-bold text-3xl md:text-5xl leading-[1.05] tracking-tight text-ink">
          Cum curg banii publici
        </h1>
        <p class="font-serif italic text-base md:text-lg text-ink/80 mt-3 max-w-2xl">
          Trei lentile peste aceleași date: fluxul de la județ la firmă, harta categoriilor cumpărate, cursa lunară a celor mai mari câștigători.
        </p>
      </div>
    </header>

    <!-- Tabs -->
    <nav class="border-b-2 border-ink bg-paper">
      <div class="max-w-content mx-auto px-4 py-3 flex flex-wrap gap-2">
        <a href="?tab=flow"
           class={`chip-brutal ${tab === 'flow' ? '!bg-ink !text-paper' : ''}`}
           aria-current={tab === 'flow' ? 'page' : undefined}>
          Money flow · Sankey
        </a>
        <a href="?tab=cpv"
           class={`chip-brutal ${tab === 'cpv' ? '!bg-ink !text-paper' : ''}`}
           aria-current={tab === 'cpv' ? 'page' : undefined}>
          Categorii · Treemap
        </a>
        <a href="?tab=race"
           class={`chip-brutal ${tab === 'race' ? '!bg-ink !text-paper' : ''}`}
           aria-current={tab === 'race' ? 'page' : undefined}>
          Bar race · Top 10
        </a>
      </div>
    </nav>

    <!-- Description -->
    <section class="max-w-content mx-auto px-4 py-6 border-b-2 border-ink">
      {tab === 'flow' && (
        <p class="font-serif italic text-base md:text-lg text-ink/80 max-w-3xl">
          Fluxul banilor de la județ, prin tipul de autoritate, către firma câștigătoare. Grosimea legăturii e proporțională cu suma. Click pe un județ sau o firmă deschide profilul.
        </p>
      )}
      {tab === 'cpv' && (
        <p class="font-serif italic text-base md:text-lg text-ink/80 max-w-3xl">
          Treemap pe diviziile CPV — fiecare dreptunghi e o categorie de cheltuieli, mărimea e valoarea atribuită în ultimele 12 luni. Click deschide categoria.
        </p>
      )}
      {tab === 'race' && (
        <p class="font-serif italic text-base md:text-lg text-ink/80 max-w-3xl">
          Topul firmelor câștigătoare lună după lună, cumulativ. Apasă PLAY ca să rulezi cursa, sau folosește slider-ul. Roșu = locul 1, galben = poziție urcată față de luna precedentă.
        </p>
      )}
    </section>

    <!-- Visualization area -->
    <section class="max-w-content mx-auto px-4 py-8">
      {tab === 'flow' && sankey && (
        <>
          {sankey.nodes.length > 0 ? (
            <Sankey nodes={sankey.nodes} links={sankey.links} height={760} client:only="react" />
          ) : (
            <div class="bg-paper border-2 border-ink p-12 text-center">
              <div class="font-mono text-xs uppercase tracking-meta text-ink/60">Nu există date suficiente.</div>
            </div>
          )}
          <div class="grid md:grid-cols-3 gap-0 border-2 border-ink border-t-0">
            <div class="p-4 border-r-2 border-ink last:border-r-0">
              <div class="label-meta mb-1">VALOARE TOTALĂ</div>
              <div class="font-display font-bold text-2xl tabular-nums">{fmt(sankey.totalValue)} RON</div>
            </div>
            <div class="p-4 border-r-2 border-ink last:border-r-0">
              <div class="label-meta mb-1">JUDEȚE TOP</div>
              <div class="font-mono text-xs tabular-nums">
                {sankey.topCounties.map((c) => (
                  <div class="flex justify-between gap-2"><span>{c.code}</span><span class="text-ink/70">{fmt(c.value)} RON</span></div>
                ))}
              </div>
            </div>
            <div class="p-4">
              <div class="label-meta mb-1">PERIOADĂ</div>
              <div class="font-mono text-xs">Ultimele 12 luni</div>
              <div class="font-mono text-xs text-ink/60 mt-1">{sankey.nodes.length} noduri · {sankey.links.length} legături</div>
            </div>
          </div>
        </>
      )}

      {tab === 'cpv' && treemap && (
        <>
          {treemap.leaves.length > 0 ? (
            <Treemap leaves={treemap.leaves} height={760} client:only="react" />
          ) : (
            <div class="bg-paper border-2 border-ink p-12 text-center">
              <div class="font-mono text-xs uppercase tracking-meta text-ink/60">Nu există date CPV.</div>
            </div>
          )}
          <div class="grid md:grid-cols-3 gap-0 border-2 border-ink border-t-0">
            <div class="p-4 border-r-2 border-ink last:border-r-0">
              <div class="label-meta mb-1">VALOARE TOTALĂ</div>
              <div class="font-display font-bold text-2xl tabular-nums">{fmt(treemap.totalValue)} RON</div>
            </div>
            <div class="p-4 border-r-2 border-ink last:border-r-0">
              <div class="label-meta mb-1">CONTRACTE</div>
              <div class="font-display font-bold text-2xl tabular-nums">{fmt(treemap.totalContracts)}</div>
            </div>
            <div class="p-4">
              <div class="label-meta mb-1">DIVIZII CPV</div>
              <div class="font-display font-bold text-2xl tabular-nums">{treemap.leaves.length}</div>
            </div>
          </div>
        </>
      )}

      {tab === 'race' && barRace && (
        <>
          {barRace.months.length > 0 ? (
            <BarRace months={barRace.months} byMonth={barRace.byMonth} height={760} client:only="react" />
          ) : (
            <div class="bg-paper border-2 border-ink p-12 text-center">
              <div class="font-mono text-xs uppercase tracking-meta text-ink/60">Nu există date pentru cursă.</div>
            </div>
          )}
          <div class="grid md:grid-cols-2 gap-0 border-2 border-ink border-t-0">
            <div class="p-4 border-r-2 border-ink last:border-r-0">
              <div class="label-meta mb-1">PERIOADĂ</div>
              <div class="font-mono text-xs tabular-nums">{barRace.months[0] || '–'} → {barRace.months[barRace.months.length - 1] || '–'}</div>
              <div class="font-mono text-xs text-ink/60 mt-1">{barRace.months.length} luni</div>
            </div>
            <div class="p-4">
              <div class="label-meta mb-1">TOP 3 FINAL</div>
              <div class="font-mono text-xs tabular-nums">
                {barRace.topSuppliers.slice(0, 3).map((s, i) => (
                  <div class="flex justify-between gap-2 truncate">
                    <span class="truncate">{String(i + 1).padStart(2, '0')} {s.name.length > 32 ? s.name.slice(0, 31) + '…' : s.name}</span>
                    <span class="text-ink/70 shrink-0">{fmt(s.value)} RON</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </>
      )}
    </section>

    <!-- Footer meta -->
    <footer class="bg-ink text-paper border-t-2 border-ink">
      <div class="max-w-content mx-auto px-4 py-8">
        <div class="grid md:grid-cols-3 gap-6">
          <div>
            <div class="font-mono text-[10px] uppercase tracking-meta text-paper/60 mb-2">SURSE</div>
            <div class="font-mono text-xs text-paper/80">SEAP · ANAP · TED · ONRC</div>
          </div>
          <div>
            <div class="font-mono text-[10px] uppercase tracking-meta text-paper/60 mb-2">PERIOADĂ ACOPERITĂ</div>
            <div class="font-mono text-xs text-paper/80 tabular-nums">Ultimele 12 luni · agregat de pe seap.announcements</div>
          </div>
          <div>
            <div class="font-mono text-[10px] uppercase tracking-meta text-paper/60 mb-2">EXPLOREAZĂ</div>
            <div class="flex flex-wrap gap-2">
              <a href="/harta" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">harta</a>
              <a href="/cauta" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">căutare</a>
              <a href="/azi" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">azi</a>
            </div>
          </div>
        </div>
      </div>
    </footer>
  </main>
</AchizitiiLayout>
