---
import AchizitiiLayout from '../layouts/AchizitiiLayout.astro';
import { RECIPES_BY_SLUG } from '../lib/recipes.js';
import { INVESTIGATIONS } from '../lib/investigations.js';
import { query } from '../lib/db.js';

export const prerender = false;

// CDN cache: data refreshes nightly via refresh-mvs.sh. 5 min CDN cache
// + 10 min stale is plenty fresh, dramatically speeds up first-hit cold
// (which is otherwise dominated by 14 snapshot reads).
Astro.response.headers.set('Cache-Control', 'public, max-age=60, s-maxage=300, stale-while-revalidate=600');

const RED_FLAG_SLUGS = [
  // Tier-1: multi-pipe public-money convergence
  'firme-quadra-pipe-public',
  'firme-triplu-pipe-public',
  'firme-datornice-cu-contracte-seap',
  'donatori-care-au-castigat-seap',
  // Tier-2: cross-source moral hazard / regulatory convergence (added 2026-05-11)
  'donatori-politici-care-datoreaza-statului',
  'donatori-politici-care-contesta-la-cnsc',
  'energie-licentiati-anre-datornici-anaf',
  'autoritati-dubla-alerta-cdc-cnsc',
  'autoritati-contestate-cnsc',
  // Tier-3: unlicensed-contractor anomalies
  'energie-fara-licenta',
  'telco-fara-licenta',
  'stat-actionar-seap',
  // Tier-4: cross-source for context
  'firme-cu-ajutor-de-stat-si-seap',
  'firme-cu-fonduri-eu-si-seap',
];

// KPI strip — read from refresh table (instant) instead of computing
// INTERSECTs live (was 12s). Refreshed nightly via cron, see
// sql/043_red_flags_kpi_snapshot.sql.
const kpisPromise = query<{ k_name: string; k_value: string }>(
  `SELECT k_name, k_value::text FROM public_kpi.red_flags_counts`
);

// Top 5 rows per recipe — read from refresh table (instant) instead of
// running 14 cross-source queries live (~17s → ~5ms). Refreshed nightly via
// cron, see sql/044_red_flags_previews_snapshot.sql. Single SELECT covers
// all slugs; previously each recipe.fetch() took 1-12s and even Promise.all
// couldn't beat the 10-12s TRIPLE/QUADRA INTERSECT pipes.
const previewsPromise = query<{
  slug: string;
  position: number;
  primary_text: string | null;
  primary_href: string | null;
  secondary: string | null;
  metric: string | null;
  metric_raw: string | null;
  detail: string | null;
  badge_label: string | null;
  badge_tone: string | null;
}>(
  `SELECT slug, position, primary_text, primary_href, secondary, metric,
          metric_raw::text AS metric_raw, detail, badge_label, badge_tone
     FROM public_kpi.red_flags_previews
    ORDER BY slug, position`
);

// Wait for both KPI strip + recipe previews in parallel.
const [kpisResult, previewsResult] = await Promise.all([kpisPromise, previewsPromise]);
const k: Record<string, number> = {};
for (const row of kpisResult.rows) k[row.k_name] = Number(row.k_value);

const previews: Record<string, any[]> = {};
for (const slug of RED_FLAG_SLUGS) previews[slug] = [];
for (const row of previewsResult.rows) {
  if (!previews[row.slug]) previews[row.slug] = [];
  previews[row.slug].push({
    primary: row.primary_text || '',
    primaryHref: row.primary_href || undefined,
    secondary: row.secondary || undefined,
    metric: row.metric || '',
    metricRaw: row.metric_raw ? Number(row.metric_raw) : 0,
    detail: row.detail || undefined,
    badge: row.badge_label ? { label: row.badge_label, tone: row.badge_tone || undefined } : undefined,
  });
}

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

<AchizitiiLayout
  title="🚩 Red flags — pattern-uri legal/etic problematice · vreaudigital.ro"
  description="Firme cu semnale cross-source de risc: datornici ANAF câștigând contracte, donatori politici devenind furnizori publici, beneficiari multipli de fonduri."
  active="red-flags"
>
  <main class="bg-paper text-ink min-h-screen">

    <!-- Top 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">Red flags · cross-source signals</span>
      </div>
    </div>

    <!-- Header -->
    <header class="border-b-2 border-ink bg-stamp/40">
      <div class="max-w-content mx-auto px-4 py-12 md:py-16">
        <div class="flex items-start gap-5 md:gap-7">
          <div class="monogram w-16 h-16 md:w-20 md:h-20 text-3xl md:text-4xl bg-signal text-paper">🚩</div>
          <div class="flex-1 min-w-0">
            <div class="label-meta mb-2">vreaudigital · investigative signals</div>
            <h1 class="font-display font-bold text-3xl md:text-5xl leading-[1.05] tracking-tight text-ink">
              Red flags
            </h1>
            <p class="font-serif italic text-base md:text-lg text-ink/70 mt-3 max-w-3xl">
              Firme cu pattern-uri legal/etic problematice, detectate prin încrucișarea automată a
              <strong>5 surse publice</strong> (SEAP achiziții + ONRC firme + RegAS ajutoare de stat +
              ANAF datornici + AEP donații electorale + fonduri EU privat + AFIR plăți agricole).
            </p>
            <p class="font-body text-sm md:text-base text-ink/70 mt-4 max-w-3xl">
              Acestea NU sunt acuzații. Sunt <em>semnale</em> — coincidențe care merită investigație
              jurnalistă. Banii sunt publici, datele sunt publice, dar nimeni altcineva nu le agreghează
              într-un singur loc.
            </p>
          </div>
        </div>
      </div>
    </header>

    <!-- Tier-0: investigation lead pages -->
    <section class="border-b-2 border-ink bg-stamp/10">
      <div class="max-w-content mx-auto px-4 py-10">
        <div class="flex items-baseline justify-between mb-4 flex-wrap gap-2">
          <h2 class="font-display font-bold text-2xl md:text-3xl text-ink">
            🔬 Investigații narative
          </h2>
          <a href="/investigation" class="chip-brutal bg-ink text-paper border-ink hover:bg-paper hover:text-ink whitespace-nowrap">
            Toate cele {INVESTIGATIONS.length} →
          </a>
        </div>
        <p class="font-serif italic text-sm md:text-base text-ink/70 mb-6 max-w-3xl">
          Cinci firme și autorități unde datele agregate produc întrebări jurnalistice concrete.
          Fiecare lead are narativ + cross-source live.
        </p>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-3">
          {INVESTIGATIONS.map((i) => (
            <a href={`/investigation/${i.slug}`} class="block border-2 border-ink bg-paper p-4 hover:bg-stamp/30 transition-colors">
              <div class="text-3xl mb-2">{i.icon}</div>
              <div class="font-display font-bold text-sm text-ink leading-snug">
                {i.title.split(' — ')[0]}
              </div>
              <div class="font-mono font-bold text-stamp text-lg mt-2">{i.headlineMetric}</div>
              <div class="label-meta normal-case tracking-normal text-ink/60 mt-1 text-xs leading-snug">
                {i.headlineHint}
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>

    <!-- KPI 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-4 gap-0 divide-x-2 divide-ink/20">
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(k.regas_seap_firms)}</div>
          <div class="stat-label">RegAS ∩ SEAP firme</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(k.ben_seap_firms)}</div>
          <div class="stat-label">EU privat ∩ SEAP firme</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(k.datornic_seap_firms)}</div>
          <div class="stat-label">Datornici → SEAP</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(k.aep_seap_firms)}</div>
          <div class="stat-label">Donatori → SEAP</div>
        </div>
        <div class="stat-tile px-3 md:px-6 col-span-2 md:col-span-1 md:border-l-2 md:border-ink">
          <div class="stat-num text-signal">{fmt(k.triple_firms)}</div>
          <div class="stat-label">🔱 TRIPLE pipe</div>
        </div>
        <div class="stat-tile px-3 md:px-6 md:col-span-3" style="display:flex; align-items:center; justify-content:center; padding: 24px;">
          <div style="text-align:center;">
            <div class="font-mono font-bold tabular-nums text-5xl md:text-6xl text-signal">{fmt(k.quadra_firms)}</div>
            <div class="label-meta normal-case tracking-normal text-ink/70 mt-1">
              firme cu QUADRA pipe — toate 4 sursele de bani publici simultan
            </div>
          </div>
        </div>
      </div>
      {/* Tier-2 KPI row — new signals (added 2026-05-11) */}
      <div class="max-w-content mx-auto px-4 pb-8 grid grid-cols-3 gap-0 divide-x-2 divide-ink/20 border-t-2 border-ink/10">
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num text-signal">{fmt(k.donator_datornic_firms)}</div>
          <div class="stat-label">🗳️ Donatori + datornici ANAF</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num text-signal">{fmt(k.anre_datornic_firms)}</div>
          <div class="stat-label">🔌 Energie ANRE + datornici</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num text-signal">{fmt(k.dubla_alerta_firms)}</div>
          <div class="stat-label">🚨 Autorități dublă alertă (CdC+CNSC)</div>
        </div>
      </div>
    </section>

    <!-- 6 recipes as cards -->
    <section class="border-b-2 border-ink">
      <div class="max-w-content mx-auto px-4 md:px-8 py-12">
        {RED_FLAG_SLUGS.map((slug) => {
          const recipe = RECIPES_BY_SLUG[slug];
          if (!recipe) return null;
          const rows = previews[slug] || [];
          return (
            <div class="border-b border-ink/20 py-8 last:border-b-0">
              <div class="grid lg:grid-cols-[260px_1fr] gap-6 lg:gap-8">
                <div>
                  <div class="text-4xl mb-3">{recipe.icon}</div>
                  <h2 class="font-display font-bold text-xl md:text-2xl text-ink mb-2 leading-tight">
                    <a href={`/retete/${slug}`} class="hover:underline">{recipe.title}</a>
                  </h2>
                  <p class="label-meta normal-case tracking-normal text-ink/60 mb-3">{recipe.metricLabel}</p>
                  <p class="font-serif italic text-sm text-ink/70 mb-4">{recipe.teaser}</p>
                  <a href={`/retete/${slug}`} class="chip-brutal bg-ink text-paper border-ink hover:bg-paper hover:text-ink whitespace-nowrap">
                    vezi rețeta completă →
                  </a>
                </div>
                <div>
                  <div class="label-meta mb-3">Top 5 (live preview)</div>
                  {rows.length === 0 && (
                    <div class="font-serif italic text-ink/60 text-sm">Niciun rezultat încă.</div>
                  )}
                  <div class="divide-y divide-ink/20">
                    {rows.map((r: any, i: number) => (
                      <a href={r.primaryHref || '#'} class="flex items-baseline gap-3 py-2 -mx-2 px-2 hover:bg-stamp transition-none">
                        <span class="font-mono text-xs text-ink/40 w-5 tabular-nums shrink-0">{String(i + 1).padStart(2, '0')}</span>
                        <div class="flex-1 min-w-0">
                          <div class="font-display text-sm text-ink truncate">{r.primary}</div>
                          {r.secondary && <div class="label-meta normal-case tracking-normal text-ink/60 truncate mt-0.5">{r.secondary}</div>}
                        </div>
                        <div class="font-mono font-bold tabular-nums text-xs text-ink shrink-0">{r.metric}</div>
                      </a>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </section>

    <!-- How it works -->
    <section class="bg-ink text-paper">
      <div class="max-w-content mx-auto px-4 md:px-8 py-12">
        <div class="grid md:grid-cols-2 gap-8 md:gap-12">
          <div>
            <div class="label-meta text-paper/60 mb-3">Cum funcționează</div>
            <h2 class="font-display font-bold text-2xl md:text-3xl text-paper mb-4">
              Datele sunt publice. Combinarea lor dezvăluie pattern-urile.
            </h2>
            <p class="font-body text-base text-paper/80 mb-3">
              Fiecare sursă (ANAF, AEP, RegAS, SEAP, beneficiar.fonduri-ue.ro, AFIR) e accesibilă oricui
              individual. Dar nimeni nu le încrucișează prin <strong>CUI</strong> ca cheie de join.
            </p>
            <p class="font-body text-base text-paper/80">
              Aici facem <strong>5+ join-uri cross-source</strong> automatizate, cu refresh pe schedule.
              Pattern-urile rezultate (firmă datornică câștigând contract, donator devenind furnizor)
              sunt indicatori de risc bine documentați în literatura academică (OCP, EU SMSC, World Bank).
            </p>
          </div>
          <div>
            <div class="label-meta text-paper/60 mb-3">Sursele integrate</div>
            <ul class="space-y-2 font-body text-sm text-paper/90">
              <li>📋 <strong>SEAP</strong> · 642K anunțuri achiziții publice (data.gov.ro + WSP live)</li>
              <li>🏢 <strong>ONRC + ANAF v9</strong> · 3.97M firme + 4.25M ani financiari</li>
              <li>🏛️ <strong>RegAS</strong> · 78K ajutoare de stat (Consiliul Concurenței, 122.8 mld RON)</li>
              <li>🚨 <strong>ANAF datornici</strong> · 140K firme datornice (data.gov.ro Q1 2016)</li>
              <li>🗳️ <strong>AEP / banipartide.ro</strong> · 380K donații electorale (Expert Forum)</li>
              <li>🇪🇺 <strong>fonduri-ue.ro</strong> · 41K anunțuri EU privați + 11.5K proiecte</li>
              <li>🌾 <strong>AFIR</strong> · 1.04M plăți FEADR 2023+2024 (2.79 mld EUR)</li>
            </ul>
          </div>
        </div>
      </div>
    </section>

    <!-- Footer -->
    <footer class="bg-paper border-t-2 border-ink">
      <div class="max-w-content mx-auto px-4 py-8 flex flex-wrap items-baseline justify-between gap-3">
        <div class="label-meta text-ink/60">Toate semnalele într-un singur loc</div>
        <div class="flex flex-wrap gap-2">
          <a href="/" class="chip-brutal">Achiziții</a>
          <a href="/retete" class="chip-brutal">Toate rețetele</a>
          <a href="/cauta" class="chip-brutal">Caută</a>
          <a href="/fonduri-ue" class="chip-brutal">Fonduri UE</a>
        </div>
      </div>
    </footer>
  </main>
</AchizitiiLayout>
