---
import AchizitiiLayout from '../layouts/AchizitiiLayout.astro';
import {
  getTodayActivity,
  getTodayFeed,
  getDailyComparison,
} from '../lib/dashboard-queries.js';

export const prerender = false;

// CDN cache: "azi" data updates as scrapers run (~daily 02:00).
// 60s browser, 5 min CDN, 10 min stale fallback.
Astro.response.headers.set('Cache-Control', 'public, max-age=60, s-maxage=300, stale-while-revalidate=600');

const [{ activity, using_24h }, feed, comparison] = await Promise.all([
  getTodayActivity(),
  getTodayFeed(50),
  getDailyComparison(),
]);

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 timeFmt = (d: string | null) =>
  d ? new Date(d).toLocaleTimeString('ro-RO', { hour: '2-digit', minute: '2-digit' }) : '';

const today = new Date().toLocaleDateString('ro-RO', { day: '2-digit', month: '2-digit', year: 'numeric' });

const TYPE_LABELS: Record<string, string> = {
  ca_notice: 'Atribuire (CA)', c_notice: 'Participare (CN)', pi_notice: 'Intenție (PI)',
  rfq_notice: 'Atribuire RFQ', rfq_invitation: 'Cerere ofertă',
  ted_notice: 'TED UE', contract: 'Contract', atribuire_fara: 'Atribuire fără',
  da: 'Cumpărare directă', notificare: 'Notificare', initiere: 'Inițiere',
};

const headerLabel = using_24h ? 'Ultimele 24 de ore' : `Azi în România · ${today}`;
const subtitle = using_24h
  ? 'Nu s-au publicat anunțuri azi (probabil weekend). Afișăm ultimele 24h.'
  : 'Anunțuri publicate astăzi în SEAP / TED. Date oficiale, actualizate continuu.';

const pctTone = (n: number) => n > 0 ? 'text-state' : n < 0 ? 'text-signal' : 'text-ink/60';
const pctSign = (n: number) => n > 0 ? '+' : '';
---

<AchizitiiLayout
  title={`Azi în România — ${today} · vreaudigital.ro`}
  description="Ce se publică azi în achiziții publice din România. Live feed cu autorități, furnizori, valori."
>
  <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">Live feed</span>
      </div>
    </div>

    <!-- Header -->
    <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 w-16 h-16 md:w-20 md:h-20 text-3xl md:text-4xl">●</div>
          <div class="flex-1 min-w-0">
            <div class="label-meta mb-2">Dashboard live</div>
            <h1 class="font-display font-bold text-3xl md:text-5xl leading-[1.05] tracking-tight text-ink">
              {headerLabel}
            </h1>
            <p class="font-serif italic text-base md:text-lg text-ink/70 mt-3 max-w-3xl">{subtitle}</p>
          </div>
        </div>
      </div>
    </header>

    <!-- Stats register -->
    <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(activity.notices_count)}</div>
          <div class="stat-label">Anunțuri publicate</div>
          {comparison.avg_count_30d > 0 && (
            <div class={`label-meta normal-case tracking-normal mt-1 ${pctTone(comparison.count_pct)}`}>
              <span class="font-mono">{pctSign(comparison.count_pct)}{comparison.count_pct}%</span> vs media 30 zile
            </div>
          )}
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(activity.total_awarded)}</div>
          <div class="stat-label">RON atribuiți</div>
          {comparison.avg_awarded_30d > 0 && (
            <div class={`label-meta normal-case tracking-normal mt-1 ${pctTone(comparison.awarded_pct)}`}>
              <span class="font-mono">{pctSign(comparison.awarded_pct)}{comparison.awarded_pct}%</span> vs media 30 zile
            </div>
          )}
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(activity.distinct_authorities)}</div>
          <div class="stat-label">Autorități active</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(activity.awarded_count)}</div>
          <div class="stat-label">Contracte atribuite</div>
        </div>
      </div>
    </section>

    <!-- Top authority + top CPV strip -->
    {(activity.top_authority || activity.top_cpv) && (
      <section class="border-b-2 border-ink bg-paper">
        <div class="max-w-content mx-auto px-4 py-6 grid md:grid-cols-2 gap-0 divide-y md:divide-y-0 md:divide-x-2 divide-ink/20">
          {activity.top_authority && activity.top_authority.cui && (
            <div class="px-0 md:px-6 py-3 md:py-1">
              <div class="label-meta mb-1">Cea mai activă autoritate</div>
              <a href={`/autoritate/${activity.top_authority.cui}`} class="block group">
                <div class="font-display font-semibold text-lg md:text-xl text-ink group-hover:underline truncate">
                  {activity.top_authority.name}
                </div>
                {activity.top_authority.total > 0 && (
                  <div class="font-mono font-bold tabular-nums text-base text-ink/80 mt-0.5">
                    {fmt(activity.top_authority.total)} <span class="font-body text-xs text-ink/60 font-normal">RON</span>
                  </div>
                )}
              </a>
            </div>
          )}
          {activity.top_cpv && activity.top_cpv.division && (
            <div class="px-0 md:px-6 py-3 md:py-1">
              <div class="label-meta mb-1">Cea mai cumpărată categorie</div>
              <a href={`/categoria/${activity.top_cpv.division}`} class="block group">
                <div class="font-display font-semibold text-lg md:text-xl text-ink group-hover:underline truncate">
                  {activity.top_cpv.emoji && <span class="mr-2">{activity.top_cpv.emoji}</span>}
                  {activity.top_cpv.name || activity.top_cpv.division}
                </div>
                <div class="label-meta normal-case tracking-normal text-ink/60 mt-0.5">
                  <span class="font-mono">{activity.top_cpv.count}</span> anunțuri
                </div>
              </a>
            </div>
          )}
        </div>
      </section>
    )}

    <!-- Live feed -->
    <section class="border-b-2 border-ink">
      <div class="max-w-content mx-auto px-4 md:px-8 py-10">
        <div class="flex items-baseline justify-between mb-6">
          <div class="label-meta">Flux cronologic</div>
          <a href="/cauta" class="label-meta normal-case tracking-normal hover:bg-stamp">caută în 642K+ anunțuri →</a>
        </div>

        {feed.length === 0 && (
          <div class="border-2 border-ink p-12 text-center">
            <div class="label-meta mb-2">Niciun anunț publicat</div>
            <p class="font-display text-xl">Verifică din nou mai târziu.</p>
          </div>
        )}

        <ol class="divide-y-2 divide-ink/20">
          {feed.map((r) => (
            <li>
              <article class="grid md:grid-cols-[110px_1fr_auto] gap-x-5 gap-y-1 py-4 px-2 -mx-2 hover:bg-stamp transition-none items-baseline">
                <div class="font-mono text-xs tabular-nums text-ink/60 shrink-0">
                  <div>{dateFmt(r.publication_date)}</div>
                  {timeFmt(r.publication_date) && <div class="text-ink/40">{timeFmt(r.publication_date)}</div>}
                </div>
                <div class="min-w-0">
                  <div class="flex flex-wrap items-center gap-2 mb-1 label-meta normal-case tracking-normal text-ink/60">
                    {r.cpv_division_name && (
                      <a href={`/categoria/${r.cpv_division}`} class="hover:underline">
                        {r.cpv_emoji && <span class="mr-1">{r.cpv_emoji}</span>}{r.cpv_division_name}
                      </a>
                    )}
                    <span class="text-ink/40">·</span>
                    <span>{TYPE_LABELS[r.type] || r.type}</span>
                    {r.eu_funded && r.eu_funded.toLowerCase().startsWith('da') && (
                      <span class="bg-state text-paper px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-meta">UE</span>
                    )}
                    {r.source === 'ted_notice' && <span class="bg-state text-paper px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-meta">TED</span>}
                  </div>
                  <h2 class="font-display font-semibold text-base md:text-lg text-ink leading-snug mb-1">
                    <a href={`/anunt/${r.id}`} class="hover:underline">{r.title || r.ref_number || `#${r.id}`}</a>
                  </h2>
                  <div class="flex flex-wrap gap-x-3 gap-y-0.5 label-meta normal-case tracking-normal text-ink/70">
                    {r.authority_name && (
                      <span>
                        <a href={`/autoritate/${r.authority_cui}`} class="text-ink hover:underline font-medium">{r.authority_name}</a>
                        {r.authority_county && <span class="text-ink/50"> · {r.authority_county}</span>}
                      </span>
                    )}
                    {r.supplier_name && (
                      <span>→ <a href={`/firma/${(r.supplier_cui || '').replace(/^RO\s*/i, '').trim()}`} class="text-ink hover:underline font-medium">{r.supplier_name}</a></span>
                    )}
                  </div>
                </div>
                <div class="text-right shrink-0 self-start">
                  {r.awarded_value && (
                    <div class="font-mono font-bold tabular-nums text-base md:text-lg text-ink whitespace-nowrap">
                      {fmt(r.awarded_value)}
                      <span class="font-body text-xs text-ink/60 font-normal ml-1">RON</span>
                    </div>
                  )}
                  {!r.awarded_value && r.estimated_value && (
                    <div class="font-mono tabular-nums text-base text-ink/70 whitespace-nowrap">
                      {fmt(r.estimated_value)}
                      <span class="font-body text-[10px] text-ink/50 font-normal ml-1 uppercase">est.</span>
                    </div>
                  )}
                </div>
              </article>
            </li>
          ))}
        </ol>
      </div>
    </section>

    <!-- Footer strip -->
    <footer class="bg-ink text-paper">
      <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-paper/60">Dashboard-uri one-click</div>
        <div class="flex flex-wrap gap-2">
          <a href="/top-contracte" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Top contracte</a>
          <a href="/top-firme" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Top firme</a>
          <a href="/fonduri-ue" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Fonduri UE</a>
          <a href="/cauta" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Caută</a>
        </div>
      </div>
    </footer>
  </main>
</AchizitiiLayout>
