---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import {
  INVESTIGATIONS_BY_SLUG,
  INVESTIGATIONS,
} from '../../lib/investigations.js';
import {
  getFirmDetails,
  getSupplierProfile,
  getEuFundsBeneficiarStatus,
  getRegasStatus,
  getAepStatus,
  getAnafDebtStatus,
} from '../../lib/profile-queries.js';
import {
  getAnreStatus,
  getAncomStatus,
  getCnscStatus,
  getBugetarStatus,
} from '../../lib/profile-queries-utilities.js';
import {
  getAsfStatus,
  getAaasStatus,
  getCurteaContStatus,
} from '../../lib/profile-queries-financial.js';
import { RECIPES_BY_SLUG } from '../../lib/recipes.js';
import '../../components/profile/profile.css';

export const prerender = false;

// CDN cache: narrative + cross-source data, refreshes on each scraper run.
// 5 min CDN cache is acceptable for editorial content.
Astro.response.headers.set('Cache-Control', 'public, max-age=60, s-maxage=300, stale-while-revalidate=600');

const slug = Astro.params.slug as string;
const lead = INVESTIGATIONS_BY_SLUG[slug];
if (!lead) return Astro.redirect('/404');

const cui = lead.cui;

const [
  firm, supplier,
  euFunds, regas, aep, anaf,
  anre, ancom, cnsc,
  asf, aaas, cdc, bugetar,
] = await Promise.all([
  getFirmDetails(cui),
  getSupplierProfile(cui),
  getEuFundsBeneficiarStatus(cui),
  getRegasStatus(cui),
  getAepStatus(cui),
  getAnafDebtStatus(cui),
  getAnreStatus(cui),
  getAncomStatus(cui),
  getCnscStatus(cui),
  getAsfStatus(cui),
  getAaasStatus(cui),
  getCurteaContStatus(cui),
  getBugetarStatus(cui),
]);

const fmt = (n: number | null | undefined) =>
  n == null ? '–' : new Intl.NumberFormat('ro-RO', { maximumFractionDigits: 0 }).format(n);
const fmtRon = (v: number | null | undefined) => {
  if (v == null) return '–';
  if (v >= 1_000_000_000) return `${(v / 1_000_000_000).toFixed(2)} mld`;
  if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)} mil`;
  if (v >= 1_000) return `${(v / 1_000).toFixed(0)}K`;
  return Math.round(v).toString();
};

// Cross-source signal rows (only present ones)
type SignalRow = { src: string; icon: string; label: string; detail: string; href?: string };
const signals: SignalRow[] = [];
if (supplier && supplier.contracts_won > 0) {
  signals.push({
    src: 'SEAP', icon: '📋',
    label: `${fmt(supplier.contracts_won)} contracte câștigate · ${fmtRon(supplier.total_awarded)} RON`,
    detail: `${fmt(supplier.distinct_buyers)} cumpărători distincți · ${supplier.first_contract_date || '?'} → ${supplier.last_contract_date || '?'}`,
    href: `/firma/${cui}`,
  });
}
if (anaf) {
  signals.push({
    src: 'ANAF', icon: '🚨',
    label: `${fmtRon(anaf.debt_total)} RON datorie publică · ${anaf.period_label}`,
    detail: `categorie: ${anaf.debtor_category || '?'} · snapshot data.gov.ro`,
  });
}
if (anre && anre.nr_active > 0) {
  signals.push({
    src: 'ANRE', icon: '🔌',
    label: `${anre.nr_active} licențe ANRE active${anre.surse.length ? ` · ${anre.surse.join(', ')}` : ''}`,
    detail: anre.subtipuri.length ? anre.subtipuri.slice(0, 6).join(' / ') : 'titular registru licențe ANRE',
  });
}
if (ancom) {
  signals.push({
    src: 'ANCOM', icon: '📡',
    label: `${ancom.nr_autorizatii} autorizație${ancom.nr_autorizatii === 1 ? '' : 'i'} ANCOM`,
    detail: ancom.servicii.length ? ancom.servicii.slice(0, 6).join(' / ') : 'furnizor servicii telco',
  });
}
if (asf) {
  signals.push({
    src: 'ASF', icon: '💰',
    label: `${asf.nr_active}/${asf.nr_total} active registru ASF`,
    detail: `${asf.register_types.join(' / ')}${asf.has_radiat ? ` · ${asf.nr_radiate} radiat${asf.nr_radiate === 1 ? 'ă' : 'e'}` : ''}`,
  });
}
if (aaas) {
  signals.push({
    src: 'AAAS', icon: '🏛️',
    label: `stat acționar${aaas.max_state_share_pct != null ? ` · ${Number(aaas.max_state_share_pct).toFixed(1)}%` : ''}`,
    detail: aaas.statusuri.join(', '),
  });
}
if (regas) {
  signals.push({
    src: 'RegAS', icon: '🏛️',
    label: `${regas.nr_ajutoare} ajutoare de stat · ${fmtRon(regas.total_ron)} RON`,
    detail: `de la ${regas.nr_finantatori} finanțator${regas.nr_finantatori === 1 ? '' : 'i'} · ${regas.prima_acordare || '?'} → ${regas.ultima_acordare || '?'}`,
  });
}
if (aep) {
  signals.push({
    src: 'AEP', icon: '🗳️',
    label: `${aep.nr_donatii} donaț${aep.nr_donatii === 1 ? 'ie' : 'ii'} către partide · ${fmtRon(aep.total_lei)} RON`,
    detail: `partide: ${aep.partide.slice(0, 5).join(', ')}`,
  });
}
if (euFunds) {
  signals.push({
    src: 'Fonduri UE', icon: '🇪🇺',
    label: `${euFunds.anunturi} anunț${euFunds.anunturi === 1 ? '' : 'uri'} beneficiar privat · ${fmtRon(euFunds.buget_total)} RON`,
    detail: euFunds.programs.length ? euFunds.programs.map(p => p.program_op_cod).join(', ') : 'beneficiar fonduri europene',
  });
}
if (cnsc) {
  if (cnsc.asAuthority) {
    signals.push({
      src: 'CNSC', icon: '⚖️',
      label: `${cnsc.asAuthority.contestation_count} contestații primite (ca autoritate)`,
      detail: `${cnsc.asAuthority.first_contestation_date || '?'} → ${cnsc.asAuthority.last_contestation_date || '?'}`,
    });
  }
  if (cnsc.asContestator) {
    signals.push({
      src: 'CNSC', icon: '⚖️',
      label: `${cnsc.asContestator.contestations_filed} contestații depuse (ca contestator)`,
      detail: `împotriva altor autorități contractante`,
    });
  }
}
if (cdc && cdc.nr_total > 0) {
  signals.push({
    src: 'Curtea Conturi', icon: '📋',
    label: `${cdc.nr_total} raport${cdc.nr_total === 1 ? '' : 'oare'} audit`,
    detail: `entitate auditată pe site-ul Curții de Conturi`,
  });
}
if (bugetar) {
  signals.push({
    src: 'Min. Finanțelor', icon: '📊',
    label: `raportor MFP · ${bugetar.sector_label}`,
    detail: bugetar.is_ordonator_principal ? 'ordonator principal credite' : 'ordonator subordonat',
  });
}

// Related recipes — only include ones that exist
const relatedRecipes = lead.relatedRecipes
  .map(s => ({ slug: s, recipe: RECIPES_BY_SLUG[s] }))
  .filter(r => r.recipe != null);

// Display name preference: firm details > supplier > config title fragment
const displayName = firm?.name || supplier?.name || lead.title.split(' — ')[0];
---
<AchizitiiLayout
  title={`${lead.title} · vreaudigital.ro`}
  description={lead.subtitle}
  ogImage={`/api/og/firma/${cui}.png`}
  active="investigation"
>
  <main class="max-w-content mx-auto px-4 py-6">

    <nav class="text-xs text-meta mb-3">
      <a href="/investigation" class="text-meta hover:text-stamp">← Toate investigațiile</a>
      <span class="mx-2">·</span>
      <a href={`/firma/${cui}`} class="text-meta hover:text-stamp">profil firmă</a>
    </nav>

    <!-- Hero -->
    <header class="profile-header" style="border-color: var(--stamp); border-width: 2px;">
      <div class="profile-header-flag-strip" />
      <div class="flex items-start gap-4">
        <div class="profile-icon" style="font-size: 48px;">{lead.icon}</div>
        <div class="flex-1 min-w-0">
          <span class="label-meta">Investigație · {lead.angle.replace(/-/g, ' ')}</span>
          <h1 class="profile-name" style="font-size: 28px; line-height: 1.15; margin-top: 6px;">
            {lead.title}
          </h1>
          <p class="text-base text-meta mt-3 leading-relaxed">{lead.subtitle}</p>
          <div class="profile-subline" style="margin-top: 14px;">
            <a href={`/firma/${cui}`} class="badge badge-stamp">{displayName}</a>
            <span class="badge font-mono">CUI {cui}</span>
            {firm?.adr_judet && <span class="badge">📍 {firm.adr_judet}</span>}
            {firm?.data_inmatriculare && (
              <span class="badge">
                fondată {new Date(firm.data_inmatriculare).toLocaleDateString('ro-RO', { year: 'numeric', month: 'short' })}
              </span>
            )}
          </div>

          <!-- Headline metric -->
          <div style="margin-top: 22px; padding: 18px 20px; background: var(--paper-2); border-left: 4px solid var(--stamp);">
            <div style="font-size: 12px; color: var(--meta); letter-spacing: 0.05em; text-transform: uppercase; font-weight: 600;">
              Cifra-cheie
            </div>
            <div class="font-display" style="font-size: 38px; line-height: 1; color: var(--ink); margin-top: 4px; font-weight: 700;">
              {lead.headlineMetric}
            </div>
            <div style="font-size: 14px; color: var(--meta); margin-top: 6px;">
              {lead.headlineHint}
            </div>
          </div>
        </div>
      </div>
    </header>

    <!-- Caveat banner -->
    {lead.caveat && (
      <div class="panel" style="border-color: var(--signal); border-width: 1px; margin-top: 18px;">
        <div class="flex gap-2 items-start text-sm">
          <span style="font-size: 18px;">⚠</span>
          <div>
            <strong class="text-ink">Notă despre freshness:</strong>
            <span class="text-meta"> {lead.caveat}</span>
          </div>
        </div>
      </div>
    )}

    <!-- Live cross-source signals -->
    <section class="profile-section">
      <h2 class="profile-section-title">
        🔗 Semnale cross-source live
        <span class="profile-section-title-meta">{signals.length} surse publice cu date pentru această firmă</span>
      </h2>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
        {signals.map((s) => (
          <a href={s.href || `/firma/${cui}`} class="panel hover:border-stamp transition-colors">
            <div class="flex items-start gap-2">
              <div style="font-size: 22px;">{s.icon}</div>
              <div class="flex-1 min-w-0">
                <div class="text-xs font-mono uppercase tracking-wide" style="color: var(--meta);">{s.src}</div>
                <div class="text-ink mt-0.5 font-medium leading-snug">{s.label}</div>
                <div class="text-xs text-meta mt-1 leading-snug">{s.detail}</div>
              </div>
            </div>
          </a>
        ))}
      </div>
      <p class="text-xs text-meta mt-3">
        Datele se actualizează automat zilnic prin cron-uri systemd. Pentru profilul detaliat,
        deschide <a href={`/firma/${cui}`} class="text-stamp">/firma/{cui}</a>.
      </p>
    </section>

    <!-- Narrative -->
    <section class="profile-section">
      {lead.narrative.map((block) => (
        <div style="margin-bottom: 24px;">
          {block.heading && <h3 class="font-display text-xl text-ink mb-2">{block.heading}</h3>}
          <div class="prose-investigation" set:html={block.html} />
        </div>
      ))}
    </section>

    <!-- Key signals summary -->
    <section class="profile-section">
      <h2 class="profile-section-title">
        🔎 De reținut
      </h2>
      <ul class="space-y-2">
        {lead.keySignals.map((s) => (
          <li class="flex gap-2 items-start text-sm">
            <span class="text-stamp" style="font-size: 16px; line-height: 1.2; margin-top: -2px;">▸</span>
            <span class="text-ink">{s}</span>
          </li>
        ))}
      </ul>
    </section>

    <!-- Related recipes -->
    {relatedRecipes.length > 0 && (
      <section class="profile-section">
        <h2 class="profile-section-title">
          📂 Rețete jurnalistice conexe
          <span class="profile-section-title-meta">{relatedRecipes.length} pattern-uri unde apare un profil similar</span>
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
          {relatedRecipes.map(({ slug: s, recipe }) => (
            <a href={`/retete/${s}`} class="panel hover:border-stamp transition-colors">
              <div class="flex items-start gap-2">
                <div style="font-size: 22px;">{recipe!.icon}</div>
                <div class="flex-1 min-w-0">
                  <div class="text-ink font-medium leading-snug">{recipe!.title}</div>
                  <div class="text-xs text-meta mt-1 leading-snug">{recipe!.teaser}</div>
                </div>
              </div>
            </a>
          ))}
        </div>
      </section>
    )}

    <!-- Footer nav: other investigations -->
    <section class="profile-section" style="border: none; padding-top: 8px;">
      <div class="rule-meta mb-4" />
      <div class="flex flex-wrap gap-2 items-center justify-between">
        <span class="label-meta">Alte investigații</span>
        <a href="/investigation" class="text-sm text-stamp hover:underline">→ Toate cele {INVESTIGATIONS.length}</a>
      </div>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mt-3">
        {INVESTIGATIONS.filter(i => i.slug !== lead.slug).slice(0, 4).map((i) => (
          <a href={`/investigation/${i.slug}`} class="panel hover:border-stamp transition-colors">
            <div class="flex items-start gap-2">
              <div style="font-size: 22px;">{i.icon}</div>
              <div class="flex-1 min-w-0">
                <div class="text-ink font-medium leading-snug">{i.title.split(' — ')[0]}</div>
                <div class="text-xs text-meta mt-1 leading-snug">{i.headlineMetric} · {i.headlineHint}</div>
              </div>
            </div>
          </a>
        ))}
      </div>
    </section>

  </main>

  <style>
    .prose-investigation {
      font-size: 15px;
      line-height: 1.65;
      color: var(--ink);
    }
    .prose-investigation p {
      margin: 0 0 12px 0;
    }
    .prose-investigation p:last-child {
      margin-bottom: 0;
    }
    .prose-investigation strong {
      color: var(--ink);
      font-weight: 600;
    }
    .prose-investigation ul {
      margin: 8px 0 12px 0;
      padding-left: 22px;
    }
    .prose-investigation li {
      margin: 4px 0;
    }
    .prose-investigation a {
      color: var(--stamp);
      text-decoration: underline;
      text-decoration-thickness: 1px;
      text-underline-offset: 2px;
    }
    .prose-investigation a:hover {
      text-decoration-thickness: 2px;
    }
    .prose-investigation em {
      color: var(--meta);
      font-style: italic;
    }
  </style>
</AchizitiiLayout>
