---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import {
  browseBeneficiarAnunturi,
  parseBrowseParams,
  buildBrowseUrl,
  getSeapCountsForCuis,
  type BrowseFilters,
} from '../../lib/beneficiar-privat-queries.js';

export const prerender = false;

const filters = parseBrowseParams(Astro.url);
if (!filters.limit) filters.limit = 30;

const data = await browseBeneficiarAnunturi(filters);

// SEAP cross-link counts for visible page (badge "vezi și pe SEAP")
const visibleCuis = Array.from(new Set(
  data.rows.map(r => (r.cui || '').trim()).filter(c => c && c !== ''),
));
const seapCounts = await getSeapCountsForCuis(visibleCuis);

// Geocoded subset for the map (only rows with cui + lat/lng)
const mapPoints = data.rows
  .filter(r => r.lat != null && r.lng != null)
  .map(r => ({
    id: r.id,
    cui: r.cui,
    name: r.beneficiar_name,
    titlu: r.titlu || r.smis_proiect_name || `#${r.id}`,
    lat: r.lat as number,
    lng: r.lng as number,
    buget: r.buget_total,
    program: r.program_op_cod,
    judet: r.beneficiar_judet,
  }));

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 fmtBudget = (v: number) => {
  if (v >= 1_000_000_000) return `${(v / 1_000_000_000).toFixed(1)} mld`;
  if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)} mil`;
  if (v >= 1_000) return `${Math.round(v / 1_000)}K`;
  return Math.round(v).toString();
};

function withFilter(key: keyof BrowseFilters, val: any): string {
  const next = { ...filters, offset: 0 };
  // @ts-ignore
  if ((next as any)[key] === val) delete (next as any)[key];
  else (next as any)[key] = val;
  return buildBrowseUrl('/fonduri-ue/anunturi', next);
}
function withoutFilter(key: keyof BrowseFilters): string {
  const next = { ...filters, offset: 0 }; delete (next as any)[key];
  return buildBrowseUrl('/fonduri-ue/anunturi', next);
}

const STATUS_LABELS: Record<string, string> = {
  open: 'În curs de ofertare',
  closed: 'Procedură închisă',
};

const activeChips: { label: string; href: string }[] = [];
if (filters.q) activeChips.push({ label: `"${filters.q}"`, href: withoutFilter('q') });
if (filters.program) {
  const txt = data.facets.programs.find(p => p.code === filters.program)?.text || filters.program;
  activeChips.push({ label: `Program: ${filters.program} · ${txt}`, href: withoutFilter('program') });
}
if (filters.judet) activeChips.push({ label: `Județ: ${filters.judet}`, href: withoutFilter('judet') });
if (filters.tip_contract) activeChips.push({ label: filters.tip_contract, href: withoutFilter('tip_contract') });
if (filters.axa) activeChips.push({ label: `Axă: ${filters.axa}`, href: withoutFilter('axa') });
if (filters.status) activeChips.push({ label: STATUS_LABELS[filters.status], href: withoutFilter('status') });
if (filters.buget_min) activeChips.push({ label: `≥ ${fmt(filters.buget_min)} RON`, href: withoutFilter('buget_min') });
if (filters.buget_max) activeChips.push({ label: `≤ ${fmt(filters.buget_max)} RON`, href: withoutFilter('buget_max') });
if (filters.date_from) activeChips.push({ label: `de la ${filters.date_from}`, href: withoutFilter('date_from') });
if (filters.date_to) activeChips.push({ label: `până la ${filters.date_to}`, href: withoutFilter('date_to') });

const BUGET_BUCKETS: { label: string; min: number; max: number | null }[] = [
  { label: '< 50K RON',  min: 0,        max: 50_000 },
  { label: '50K – 200K', min: 50_000,   max: 200_000 },
  { label: '200K – 1M',  min: 200_000,  max: 1_000_000 },
  { label: '1M – 5M',    min: 1_000_000, max: 5_000_000 },
  { label: '> 5M RON',   min: 5_000_000, max: null },
];

const totalPages = Math.ceil(data.total / (filters.limit || 30));
const currentPage = Math.floor((filters.offset || 0) / (filters.limit || 30)) + 1;
---

<AchizitiiLayout
  title={filters.q
    ? `Caută "${filters.q}" în anunțuri fonduri UE — vreaudigital.ro`
    : 'Anunțuri beneficiari privați fonduri UE — vreaudigital.ro'}
  description={`Browse ${fmt(41494)} anunțuri publicate de beneficiari privați ai fondurilor europene. Filtrează după program, axă, județ, buget, status.`}
>
  <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>
        <div class="font-mono text-xs uppercase tracking-meta text-paper/60">
          <a href="/fonduri-ue" class="hover:text-stamp">Fonduri UE</a> · Anunțuri beneficiari privați
        </div>
      </div>
    </div>

    <!-- Search bar -->
    <div class="border-b-2 border-ink">
      <div class="max-w-content mx-auto px-4 py-6">
        <form method="GET" action="/fonduri-ue/anunturi" class="flex gap-0">
          <input type="text" name="q" value={filters.q || ''}
            placeholder="caută: nume beneficiar, proiect, cod SMIS, CIF…"
            class="flex-1 input-brutal text-base md:text-lg py-3" />
          <button class="btn-brutal-primary px-6 md:px-10 -ml-0.5">Caută</button>
          {filters.program && <input type="hidden" name="program" value={filters.program} />}
          {filters.judet && <input type="hidden" name="judet" value={filters.judet} />}
          {filters.tip_contract && <input type="hidden" name="tip" value={filters.tip_contract} />}
          {filters.axa && <input type="hidden" name="axa" value={filters.axa} />}
          {filters.status && <input type="hidden" name="status" value={filters.status} />}
          {filters.sort && <input type="hidden" name="sort" value={filters.sort} />}
        </form>

        {activeChips.length > 0 && (
          <div class="flex flex-wrap items-center gap-2 mt-4">
            <span class="label-meta">Filtre:</span>
            {activeChips.map(c => (
              <a href={c.href} class="chip-brutal chip-active hover:bg-signal hover:text-paper">
                {c.label} <span class="ml-1">×</span>
              </a>
            ))}
            <a href="/fonduri-ue/anunturi" class="label-meta normal-case tracking-normal underline hover:bg-stamp px-1">resetează</a>
          </div>
        )}
      </div>
    </div>

    <!-- Counter strip -->
    <div class="border-b-2 border-ink bg-paper">
      <div class="max-w-content mx-auto px-4 py-5 flex items-baseline justify-between flex-wrap gap-3">
        <div>
          <span class="font-mono font-bold tabular-nums text-3xl md:text-5xl text-ink">{fmt(data.total)}</span>
          <span class="label-meta normal-case tracking-normal text-ink/60 ml-3">anunțuri</span>
          {data.buget_sum > 0 && (
            <span class="label-meta normal-case tracking-normal text-ink/60 ml-3 hidden md:inline">
              · cumulat <span class="font-mono font-bold tabular-nums text-ink">{fmt(data.buget_sum)}</span> RON
            </span>
          )}
        </div>
        <form method="GET" class="text-sm flex items-center gap-2">
          <span class="label-meta">Sortează</span>
          {Object.entries(filters).filter(([k]) => k !== 'sort' && k !== 'offset').map(([k, v]) =>
            v != null && v !== '' ? <input type="hidden" name={k === 'tip_contract' ? 'tip' : k} value={String(v)} /> : null
          )}
          <select name="sort" onchange="this.form.submit()" class="border-2 border-ink bg-paper px-2 py-1 font-mono text-xs uppercase tracking-meta">
            <option value="date_desc" selected={filters.sort === 'date_desc' || !filters.sort}>Data ↓</option>
            <option value="date_asc" selected={filters.sort === 'date_asc'}>Data ↑</option>
            <option value="buget_desc" selected={filters.sort === 'buget_desc'}>Buget ↓</option>
            <option value="buget_asc" selected={filters.sort === 'buget_asc'}>Buget ↑</option>
          </select>
        </form>
      </div>
    </div>

    <!-- Map strip (only if we have geocoded points) -->
    {mapPoints.length > 0 && (
      <section class="border-b-2 border-ink bg-paper">
        <div class="max-w-content mx-auto px-4 py-4">
          <div class="flex items-baseline justify-between mb-2">
            <div class="label-meta">📍 Locații beneficiari pe pagina curentă</div>
            <span class="label-meta normal-case tracking-normal text-ink/50">{mapPoints.length} / {data.rows.length} geocodate</span>
          </div>
          <div id="anunturi-map" style="height: 320px; border: 2px solid var(--ink, #1a1a1a);"></div>
          <script type="application/json" is:inline id="anunturi-map-data" set:html={JSON.stringify(mapPoints)}></script>
        </div>
      </section>
    )}

    <div class="max-w-content mx-auto grid lg:grid-cols-12 gap-0">
      <!-- Sidebar -->
      <aside class="lg:col-span-3 lg:border-r-2 lg:border-ink px-4 md:px-6 py-8 space-y-8">

        {data.facets.status.length > 1 && (
          <div>
            <h3 class="label-meta mb-3">Status</h3>
            <div class="space-y-0.5">
              {data.facets.status.map(s => (
                <a href={withFilter('status', s.status)}
                   class:list={['flex items-baseline justify-between px-2 py-1.5 text-sm hover:bg-stamp transition-none', { 'bg-ink text-paper': filters.status === s.status }]}>
                  <span class="font-display">
                    {s.status === 'open' ? '🟢 În ofertare' : '⚪ Închisă'}
                  </span>
                  <span class="font-mono text-xs tabular-nums opacity-70">{fmt(s.count)}</span>
                </a>
              ))}
            </div>
          </div>
        )}

        {data.facets.programs.length > 0 && (
          <div>
            <h3 class="label-meta mb-3">Program operațional</h3>
            <div class="space-y-0.5">
              {data.facets.programs.map(p => (
                <a href={withFilter('program', p.code)}
                   class:list={['flex items-baseline justify-between gap-2 px-2 py-1.5 text-sm hover:bg-stamp transition-none', { 'bg-ink text-paper': filters.program === p.code }]}>
                  <span class="flex items-baseline gap-1.5 min-w-0 flex-1">
                    <span class="font-mono text-[10px] bg-state text-paper px-1 shrink-0">{p.code}</span>
                    <span class="font-display truncate text-xs">{p.text || ''}</span>
                  </span>
                  <span class="font-mono text-xs tabular-nums opacity-70 shrink-0">{fmt(p.count)}</span>
                </a>
              ))}
            </div>
          </div>
        )}

        {data.facets.axe.length > 0 && filters.program && (
          <div>
            <h3 class="label-meta mb-3">Axă prioritară</h3>
            <div class="space-y-0.5">
              {data.facets.axe.map(a => (
                <a href={withFilter('axa', a.code)}
                   class:list={['flex items-baseline justify-between gap-2 px-2 py-1.5 text-sm hover:bg-stamp transition-none', { 'bg-ink text-paper': filters.axa === a.code }]}>
                  <span class="flex items-baseline gap-1.5 min-w-0 flex-1">
                    <span class="font-mono text-[10px] shrink-0">{a.code}</span>
                    {a.text && <span class="font-display truncate text-xs text-ink/70">{a.text}</span>}
                  </span>
                  <span class="font-mono text-xs tabular-nums opacity-70 shrink-0">{fmt(a.count)}</span>
                </a>
              ))}
            </div>
          </div>
        )}

        {data.facets.tip_contract.length > 0 && (
          <div>
            <h3 class="label-meta mb-3">Tip contract</h3>
            <div class="space-y-0.5">
              {data.facets.tip_contract.map(t => (
                <a href={withFilter('tip_contract', t.tip)}
                   class:list={['flex items-baseline justify-between px-2 py-1.5 text-sm hover:bg-stamp transition-none', { 'bg-ink text-paper': filters.tip_contract === t.tip }]}>
                  <span class="font-display">{t.tip}</span>
                  <span class="font-mono text-xs tabular-nums opacity-70">{fmt(t.count)}</span>
                </a>
              ))}
            </div>
          </div>
        )}

        {data.facets.judete.length > 0 && (
          <div>
            <h3 class="label-meta mb-3">Județ beneficiar</h3>
            <div class="grid grid-cols-2 gap-0.5">
              {data.facets.judete.slice(0, 24).map(j => (
                <a href={withFilter('judet', j.judet)}
                   class:list={['flex items-baseline justify-between px-2 py-1 text-xs hover:bg-stamp transition-none', { 'bg-ink text-paper': filters.judet === j.judet }]}>
                  <span class="font-display truncate">{j.judet}</span>
                  <span class="font-mono tabular-nums opacity-70">{fmt(j.count)}</span>
                </a>
              ))}
            </div>
          </div>
        )}

        <div>
          <h3 class="label-meta mb-3">Buget (RON)</h3>
          <div class="space-y-0.5">
            {BUGET_BUCKETS.map(b => {
              const isActive = filters.buget_min === b.min && (b.max == null ? filters.buget_max === undefined : filters.buget_max === b.max);
              const url = isActive
                ? withoutFilter('buget_min')
                : buildBrowseUrl('/fonduri-ue/anunturi', {
                    ...filters, offset: 0, buget_min: b.min, buget_max: b.max ?? undefined,
                  });
              return (
                <a href={url}
                   class:list={['flex items-baseline justify-between px-2 py-1.5 text-sm hover:bg-stamp transition-none', { 'bg-ink text-paper': isActive }]}>
                  <span class="font-display">{b.label}</span>
                </a>
              );
            })}
          </div>
        </div>

        <div>
          <h3 class="label-meta mb-3">Perioadă</h3>
          <form method="GET" class="space-y-2">
            {Object.entries(filters).filter(([k]) => k !== 'date_from' && k !== 'date_to' && k !== 'offset').map(([k, v]) =>
              v != null && v !== '' ? <input type="hidden" name={k === 'tip_contract' ? 'tip' : k} value={String(v)} /> : null
            )}
            <div>
              <label class="label-meta block mb-1">De la</label>
              <input type="date" name="date_from" value={filters.date_from || ''} class="w-full border-2 border-ink bg-paper px-2 py-1 font-mono text-xs" />
            </div>
            <div>
              <label class="label-meta block mb-1">Până la</label>
              <input type="date" name="date_to" value={filters.date_to || ''} class="w-full border-2 border-ink bg-paper px-2 py-1 font-mono text-xs" />
            </div>
            <button class="btn-brutal w-full text-xs">Aplică perioadă</button>
          </form>
        </div>

      </aside>

      <!-- Results -->
      <section class="lg:col-span-9 px-4 md:px-6 py-8">
        {data.rows.length === 0 && (
          <div class="border-2 border-ink p-12 text-center">
            <div class="label-meta mb-2">Niciun rezultat</div>
            <p class="font-display text-xl">Încearcă alte filtre sau cuvinte cheie.</p>
            <a href="/fonduri-ue/anunturi" class="chip-brutal mt-4 inline-block">Resetează filtrele</a>
          </div>
        )}

        <ol class="divide-y-2 divide-ink/20">
          {data.rows.map(r => {
            const titleText = r.titlu || r.smis_proiect_name || `Anunț #${r.id}`;
            const isOpen = (r.procedura_status || '').toLowerCase().includes('curs');
            const seap = r.cui ? seapCounts.get(r.cui) : undefined;
            return (
              <li>
                <article class="grid grid-cols-1 md:grid-cols-[110px_1fr_auto] gap-x-5 gap-y-1 py-5 hover:bg-stamp transition-none px-2 -mx-2 items-baseline">
                  <div class="font-mono text-xs tabular-nums text-ink/60 shrink-0 self-start">
                    {dateFmt(r.data_publicare)}
                  </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">
                      <span class="bg-state text-paper px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-meta">🇪🇺 EU</span>
                      {r.program_op_cod && (
                        <a href={withFilter('program', r.program_op_cod)}
                           title={r.program_op_text || r.program_op_cod}
                           class="bg-ink text-paper px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-meta hover:bg-stamp hover:text-ink">
                          {r.program_op_cod}
                        </a>
                      )}
                      <span class="text-ink/40">·</span>
                      <span>{r.tip_contract || '?'}</span>
                      {isOpen ? (
                        <span class="bg-stamp text-ink px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-meta">🟢 În ofertare</span>
                      ) : (
                        <span class="text-ink/50 font-mono text-[10px] uppercase tracking-meta">⚪ Închisă</span>
                      )}
                      {r.smis_proiect_code && (
                        <a href={`/proiect/${r.smis_proiect_id}`}
                           class="font-mono text-[10px] text-ink/60 hover:text-ink hover:underline">
                          SMIS {r.smis_proiect_code}
                        </a>
                      )}
                    </div>
                    <h2 class="font-display font-semibold text-base md:text-lg text-ink leading-snug mb-1">
                      <a href={`/beneficiar-privat/${r.id}`} class="hover:underline">
                        {titleText}
                      </a>
                    </h2>
                    <div class="flex flex-wrap gap-x-3 gap-y-0.5 label-meta normal-case tracking-normal text-ink/70">
                      <span>
                        {r.cui ? (
                          <a href={`/firma/${r.cui}`} class="text-ink hover:underline font-medium">
                            {r.beneficiar_name}
                          </a>
                        ) : (
                          <span class="text-ink font-medium">{r.beneficiar_name}</span>
                        )}
                        {r.beneficiar_judet && (
                          <span class="text-ink/50"> · {r.beneficiar_judet}</span>
                        )}
                      </span>
                      {r.loturi > 0 && (
                        <span class="text-ink/50">{r.loturi} lot{r.loturi === 1 ? '' : 'uri'}</span>
                      )}
                      {seap && seap.contracts > 0 && (
                        <a href={`/firma/${r.cui}`}
                           title={`${seap.contracts} contracte SEAP, ${fmt(seap.total)} RON cumulat`}
                           class="bg-state text-paper px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-meta hover:bg-ink">
                          🔗 SEAP {seap.contracts}
                        </a>
                      )}
                    </div>
                  </div>
                  <div class="text-right shrink-0 self-start">
                    {r.buget_total > 0 ? (
                      <>
                        <div class="font-mono font-bold tabular-nums text-base md:text-lg text-ink whitespace-nowrap">
                          {fmtBudget(r.buget_total)}
                          <span class="font-body text-xs text-ink/60 font-normal ml-1">RON</span>
                        </div>
                        <div class="label-meta normal-case tracking-normal text-ink/40 text-[10px]">
                          {fmt(r.buget_total)} exact
                        </div>
                      </>
                    ) : (
                      <div class="text-ink/40 text-xs italic font-serif">fără buget</div>
                    )}
                  </div>
                </article>
              </li>
            );
          })}
        </ol>

        {totalPages > 1 && (
          <nav class="flex items-center justify-between mt-10 pt-6 border-t-2 border-ink">
            {(filters.offset ?? 0) > 0 ? (
              <a href={buildBrowseUrl('/fonduri-ue/anunturi', { ...filters, offset: Math.max(0, (filters.offset ?? 0) - (filters.limit ?? 30)) })}
                 class="btn-brutal">← Anterior</a>
            ) : <span></span>}
            <span class="label-meta">
              <span class="font-mono">{(filters.offset ?? 0) + 1}–{Math.min((filters.offset ?? 0) + (filters.limit ?? 30), data.total)}</span> din <span class="font-mono">{fmt(data.total)}</span>
              <span class="text-ink/40 ml-2">(pagina {currentPage}/{totalPages})</span>
            </span>
            {(filters.offset ?? 0) + (filters.limit ?? 30) < data.total ? (
              <a href={buildBrowseUrl('/fonduri-ue/anunturi', { ...filters, offset: (filters.offset ?? 0) + (filters.limit ?? 30) })}
                 class="btn-brutal">Următor →</a>
            ) : <span></span>}
          </nav>
        )}
      </section>
    </div>

    <!-- 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">Hub-uri conexe</div>
        <div class="flex flex-wrap gap-2">
          <a href="/fonduri-ue" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">← Fonduri UE (overview)</a>
          <a href="/cauta" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Caută SEAP</a>
          <a href="/retete" class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">Rețete</a>
        </div>
      </div>
    </footer>
  </main>

  <!-- Leaflet for the map -->
  {mapPoints.length > 0 && (
    <>
      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" crossorigin="" />
      <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" crossorigin="" is:inline></script>
      <script is:inline>
        document.addEventListener('DOMContentLoaded', function () {
          // @ts-ignore
          const L = window.L;
          if (!L) return;
          const data = JSON.parse(document.getElementById('anunturi-map-data').textContent || '[]');
          if (!data.length) return;
          const map = L.map('anunturi-map', { scrollWheelZoom: false });
          L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap',
            maxZoom: 18,
          }).addTo(map);
          const fmt = (n) => new Intl.NumberFormat('ro-RO', { maximumFractionDigits: 0 }).format(n);
          const bounds = [];
          data.forEach(p => {
            const marker = L.circleMarker([p.lat, p.lng], {
              radius: Math.min(15, Math.max(5, Math.log10(Math.max(1, p.buget)) - 2)),
              fillColor: '#c2410c',
              color: '#1a1a1a',
              weight: 1.5,
              fillOpacity: 0.7,
            }).addTo(map);
            const titleEsc = String(p.titlu).replace(/</g, '&lt;');
            const nameEsc = String(p.name).replace(/</g, '&lt;');
            marker.bindPopup(
              '<div style="font-family:system-ui;font-size:12px;max-width:240px;">'
              + '<div style="font-weight:bold;margin-bottom:4px;">' + nameEsc + '</div>'
              + '<div style="color:#666;margin-bottom:4px;">' + titleEsc + '</div>'
              + (p.program ? '<div style="font-family:monospace;font-size:10px;background:#1a4d6e;color:#fff;padding:1px 4px;display:inline-block;">' + p.program + '</div> ' : '')
              + (p.judet ? '<span style="font-size:10px;color:#666;">' + p.judet + '</span>' : '')
              + '<div style="margin-top:6px;font-family:monospace;font-weight:bold;">' + fmt(p.buget) + ' RON</div>'
              + '<a href="/beneficiar-privat/' + p.id + '" style="color:#c2410c;font-size:11px;">vezi anunțul →</a>'
              + '</div>'
            );
            bounds.push([p.lat, p.lng]);
          });
          if (bounds.length === 1) {
            map.setView(bounds[0], 11);
          } else {
            map.fitBounds(bounds, { padding: [25, 25] });
          }
        });
      </script>
    </>
  )}
</AchizitiiLayout>
