---
import AchizitiiLayout from '../layouts/AchizitiiLayout.astro';
import { search, getResultCoords, parseSearchParams, buildSearchUrl, buildSearchUrlWithPagination, type SearchFilters } from '../lib/search-queries.js';
import { query } from '../lib/db.js';
import SearchMap from '../components/cauta/SearchMap.tsx';
import CpvAutocomplete from '../components/cauta/CpvAutocomplete.tsx';

export const prerender = false;

// CDN cache by full URL (query-string included): all results are public,
// so anyone with the same filters sees the same data. 60s max-age +
// 5 min CDN cache + 10 min stale-while-revalidate keeps the page snappy
// while bounded staleness vs nightly scrape cadence is acceptable.
Astro.response.headers.set('Cache-Control', 'public, max-age=60, s-maxage=300, stale-while-revalidate=600');

const filters = parseSearchParams(Astro.url);
const data = await search(filters);

// Resolve the label for the currently selected CPV (any level), so the
// autocomplete can render its current selection without a roundtrip.
let currentCpvLabel: string | null = null;
if (filters.cpv_division) {
  const row = await query<{ name_ro: string }>(
    `SELECT name_ro FROM seap.cpv_codes WHERE code = $1 LIMIT 1`,
    [filters.cpv_division],
  );
  currentCpvLabel = row.rows[0]?.name_ro || null;
}

// Fetch lat/lng for visible results — fast indexed lookup on firms.entities
const resultIds = data.results.map(r => r.id);
const coordsRaw = await getResultCoords(resultIds);
// Map: id -> { supplier?, authority? }
const markers = coordsRaw;

// Cross-source signal flags for visible suppliers (existing pattern)
const supplierCuis = Array.from(new Set(
  data.results
    .map(r => (r.supplier_cui || '').replace(/^RO\s*/i, '').trim())
    .filter(c => c && c !== ''),
));
const euMap = new Map<string, number>();
const regasMap = new Map<string, number>();
const aepMap = new Map<string, number>();
const datornicMap = new Map<string, number>();
if (supplierCuis.length > 0) {
  const [eu, regas, aep, datornic] = await Promise.all([
    query<{ cui: string; anunturi: number }>(
      `SELECT cui, anunturi FROM firms.mv_eu_funds_per_cui WHERE cui = ANY($1)`,
      [supplierCuis],
    ),
    query<{ cui: string; n: number }>(
      `SELECT cui, COUNT(*)::int AS n FROM regas.ajutoare WHERE cui = ANY($1) GROUP BY cui`,
      [supplierCuis],
    ),
    query<{ cui: string; n: number }>(
      `SELECT donator_cui AS cui, COUNT(*)::int AS n FROM aep.donatii_pj WHERE donator_cui = ANY($1) GROUP BY donator_cui`,
      [supplierCuis],
    ),
    query<{ cui: string; debt: number }>(
      `SELECT cui, debt_total::numeric AS debt FROM anaf.datornici_latest WHERE cui = ANY($1)`,
      [supplierCuis],
    ),
  ]);
  for (const row of eu.rows) euMap.set(row.cui, Number(row.anunturi));
  for (const row of regas.rows) regasMap.set(row.cui, Number(row.n));
  for (const row of aep.rows) aepMap.set(row.cui, Number(row.n));
  for (const row of datornic.rows) datornicMap.set(row.cui, Number(row.debt));
}

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, '.') : '–';

function withFilter(key: keyof SearchFilters, val: any): string {
  const next = { ...filters };
  delete next.offset;
  // @ts-ignore
  if (next[key] === val) delete next[key];
  else (next as any)[key] = val;
  return buildSearchUrl('/cauta', next);
}
function withoutFilter(key: keyof SearchFilters): string {
  const next = { ...filters };
  delete next.offset;
  delete next[key];
  return buildSearchUrl('/cauta', next);
}

// Quick year ranges
const thisYear = new Date().getFullYear();
const yearOptions = [thisYear, thisYear - 1, thisYear - 2, thisYear - 3];
function yearRangeUrl(y: number): string {
  const next = { ...filters };
  delete next.offset;
  next.date_from = `${y}-01-01`;
  next.date_to = `${y}-12-31`;
  return buildSearchUrl('/cauta', next);
}
const activeYearRange = (() => {
  if (!filters.date_from || !filters.date_to) return null;
  const m1 = /^(\d{4})-01-01$/.exec(filters.date_from);
  const m2 = /^(\d{4})-12-31$/.exec(filters.date_to);
  if (m1 && m2 && m1[1] === m2[1]) return Number(m1[1]);
  return null;
})();

const TYPE_LABELS: Record<string, string> = {
  ca_notice: 'Atribuiri (CA)', c_notice: 'Participare (CN)', pi_notice: 'Intenție (PI)',
  rfq_notice: 'Atribuiri 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',
  modificare: 'Modificare',
};

const STATE_LABELS: Record<string, { label: string; tone: 'good' | 'warn' | 'bad' | 'neutral' }> = {
  'Publicat':       { label: 'Publicat',         tone: 'neutral' },
  'In desfasurare': { label: 'În desfășurare',   tone: 'warn' },
  'Atribuita':      { label: 'Atribuită',        tone: 'good' },
  'Anulata':        { label: 'Anulată',          tone: 'bad' },
  'Suspended':      { label: 'Suspendată',       tone: 'bad' },
};

const activeFilters: { label: string; href: string }[] = [];
if (filters.q) activeFilters.push({ label: `"${filters.q}"`, href: withoutFilter('q') });
if (filters.cpv_division) {
  const cpvName = currentCpvLabel
    || data.facets.cpv_divisions.find(c => c.code === filters.cpv_division)?.name
    || filters.cpv_division;
  activeFilters.push({ label: cpvName, href: withoutFilter('cpv_division') });
}
if (filters.county_code) activeFilters.push({ label: filters.county_code, href: withoutFilter('county_code') });
if (filters.type) activeFilters.push({ label: TYPE_LABELS[filters.type] || filters.type, href: withoutFilter('type') });
if (filters.procedure_type) activeFilters.push({ label: filters.procedure_type, href: withoutFilter('procedure_type') });
if (filters.procedure_state) activeFilters.push({ label: STATE_LABELS[filters.procedure_state]?.label || filters.procedure_state, href: withoutFilter('procedure_state') });
if (filters.value_min) activeFilters.push({ label: `≥ ${fmt(filters.value_min)} RON`, href: withoutFilter('value_min') });
if (filters.value_max) activeFilters.push({ label: `≤ ${fmt(filters.value_max)} RON`, href: withoutFilter('value_max') });
if (filters.date_from) activeFilters.push({ label: `de la ${filters.date_from}`, href: withoutFilter('date_from') });
if (filters.date_to) activeFilters.push({ label: `până la ${filters.date_to}`, href: withoutFilter('date_to') });
if (filters.has_lots) activeFilters.push({ label: 'Cu loturi', href: withoutFilter('has_lots') });
if (filters.framework_agreement) activeFilters.push({ label: 'Acord-cadru', href: withoutFilter('framework_agreement') });
if (filters.eu_funded) activeFilters.push({ label: 'Fonduri UE', href: withoutFilter('eu_funded') });

const limit = filters.limit ?? 30;
const offset = filters.offset ?? 0;
---

<AchizitiiLayout
  title={filters.q ? `Caută "${filters.q}" — vreaudigital.ro` : 'Caută în achiziții publice — vreaudigital.ro'}
  description="Caută în 781K+ anunțuri publice din SEAP după CPV, județ, valoare, perioadă, status. Cu hartă interactivă a firmelor și autorităților."
  active="cauta"
>
  <main class="bg-paper text-ink min-h-screen">

    <!-- Search bar -->
    <div class="border-b-2 border-ink">
      <div class="max-w-content mx-auto px-4 py-6">
        <form method="GET" action="/cauta" class="flex gap-0">
          <input type="text" name="q" value={filters.q || ''}
            placeholder="caută: nume firmă, autoritate, cuvinte cheie, CIF…"
            autofocus
            class="flex-1 input-brutal text-lg md:text-xl py-4" />
          <button class="btn-brutal-primary px-6 md:px-10 -ml-0.5">Caută</button>
          {filters.cpv_division && <input type="hidden" name="cpv" value={filters.cpv_division} />}
          {filters.county_code && <input type="hidden" name="county_code" value={filters.county_code} />}
          {filters.type && <input type="hidden" name="type" value={filters.type} />}
          {filters.procedure_type && <input type="hidden" name="procedure_type" value={filters.procedure_type} />}
          {filters.procedure_state && <input type="hidden" name="procedure_state" value={filters.procedure_state} />}
          {filters.value_min !== undefined && <input type="hidden" name="value_min" value={filters.value_min} />}
          {filters.value_max !== undefined && <input type="hidden" name="value_max" value={filters.value_max} />}
          {filters.date_from && <input type="hidden" name="date_from" value={filters.date_from} />}
          {filters.date_to && <input type="hidden" name="date_to" value={filters.date_to} />}
          {filters.eu_funded && <input type="hidden" name="eu_funded" value="1" />}
          {filters.sort && <input type="hidden" name="sort" value={filters.sort} />}
        </form>

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

        <!-- Year quick-pick -->
        <div class="flex flex-wrap items-center gap-2 mt-3">
          <span class="label-meta">An:</span>
          {yearOptions.map(y => (
            <a href={activeYearRange === y ? withoutFilter('date_from') : yearRangeUrl(y)}
               class:list={['chip-brutal', { 'chip-active': activeYearRange === y }]}>
              {y}
            </a>
          ))}
        </div>
      </div>
    </div>

    <!-- Result counter + sort -->
    <div class="border-b-2 border-ink bg-paper">
      <div class="max-w-content mx-auto px-4 py-4 flex items-baseline justify-between flex-wrap gap-3">
        <div>
          <span class="font-mono font-bold tabular-nums text-2xl md:text-4xl text-ink">{fmt(data.total)}</span>
          <span class="label-meta normal-case tracking-normal text-ink/60 ml-3">rezultate</span>
          {data.sum_awarded > 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.sum_awarded)}</span> RON
            </span>
          )}
          {markers.length > 0 && (
            <span class="label-meta normal-case tracking-normal text-ink/60 ml-3 hidden lg:inline">
              · <span class="font-mono tabular-nums text-ink">{markers.length}</span> puncte pe hartă
            </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' && k !== 'limit').map(([k, v]) =>
            v != null && v !== false ? <input type="hidden" name={k === 'cpv_division' ? 'cpv' : k === 'eu_funded' ? 'eu_funded' : k} value={String(v === true ? 1 : 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="value_desc" selected={filters.sort === 'value_desc'}>Valoare ↓</option>
            <option value="value_asc" selected={filters.sort === 'value_asc'}>Valoare ↑</option>
          </select>
        </form>
      </div>
    </div>

    <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-5 py-6 space-y-6 lg:sticky lg:top-0 lg:max-h-screen lg:overflow-y-auto">

        <!-- Date range manual -->
        <div>
          <h3 class="label-meta mb-2">Perioadă</h3>
          <form method="GET" action="/cauta" class="space-y-1">
            {Object.entries(filters).filter(([k]) => k !== 'date_from' && k !== 'date_to' && k !== 'offset').map(([k, v]) =>
              v != null && v !== false ? <input type="hidden" name={k === 'cpv_division' ? 'cpv' : k === 'eu_funded' ? 'eu_funded' : k} value={String(v === true ? 1 : v)} /> : null
            )}
            <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"/>
            <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"/>
            <button class="btn-brutal w-full text-xs py-1 mt-1">Aplică</button>
          </form>
        </div>

        <!-- Procedure state (in progress / awarded / cancelled) -->
        {data.facets.states.length > 0 && (
          <div>
            <h3 class="label-meta mb-2">Status procedură</h3>
            <div class="space-y-0.5">
              {data.facets.states.map(s => {
                const meta = STATE_LABELS[s.state] || { label: s.state, tone: 'neutral' as const };
                return (
                  <a href={withFilter('procedure_state', s.state)}
                    class:list={['flex items-baseline justify-between px-2 py-1.5 text-sm hover:bg-stamp transition-none', { 'bg-ink text-paper': filters.procedure_state === s.state }]}>
                    <span class="font-display flex items-center gap-1.5">
                      <span class={`inline-block w-2 h-2 rounded-full ${meta.tone === 'good' ? 'bg-green-600' : meta.tone === 'warn' ? 'bg-amber-500' : meta.tone === 'bad' ? 'bg-red-600' : 'bg-slate-400'}`}></span>
                      {meta.label}
                    </span>
                    <span class="font-mono text-xs tabular-nums opacity-70">{fmt(s.count)}</span>
                  </a>
                );
              })}
            </div>
          </div>
        )}

        <div>
          <h3 class="label-meta mb-2">Categorie CPV</h3>
          <CpvAutocomplete
            client:load
            value={filters.cpv_division || null}
            valueLabel={currentCpvLabel}
            name="cpv_autocomplete"
          />
          {data.facets.cpv_divisions.length > 0 && (
            <>
              <div class="label-meta mt-3 mb-1 normal-case tracking-normal text-ink/60">Top divizii:</div>
              <div class="space-y-0.5">
                {data.facets.cpv_divisions.slice(0, 8).map(c => (
                  <a href={withFilter('cpv_division', c.code)}
                     class:list={['flex items-baseline justify-between px-2 py-1 text-xs hover:bg-stamp transition-none', { 'bg-ink text-paper': filters.cpv_division === c.code }]}>
                    <span class="truncate flex-1 font-display">{c.name || c.code}</span>
                    <span class="font-mono text-[10px] tabular-nums opacity-70 shrink-0 ml-2">{fmt(c.count)}</span>
                  </a>
                ))}
              </div>
            </>
          )}
        </div>

        {data.facets.counties.length > 0 && (
          <div>
            <h3 class="label-meta mb-2">Județe (NUTS)</h3>
            <div class="grid grid-cols-2 gap-0.5">
              {data.facets.counties.slice(0, 14).map(c => (
                <a href={withFilter('county_code', c.code)}
                   class:list={['flex items-baseline justify-between px-2 py-1.5 text-sm hover:bg-stamp transition-none', { 'bg-ink text-paper': filters.county_code === c.code }]}>
                  <span class="font-mono">{c.code}</span>
                  <span class="font-mono text-xs tabular-nums opacity-70">{fmt(c.count)}</span>
                </a>
              ))}
            </div>
          </div>
        )}

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

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

        <div>
          <h3 class="label-meta mb-2">Valoare</h3>
          <div class="space-y-0.5">
            {data.facets.value_buckets.filter(b => b.count > 0).map(b => {
              const isActive = filters.value_min === b.range[0] && filters.value_max === b.range[1];
              const url = isActive ? withoutFilter('value_min')
                : (() => {
                    const next = { ...filters };
                    delete next.offset;
                    next.value_min = b.range[0];
                    if (b.range[1] != null) next.value_max = b.range[1];
                    else delete next.value_max;
                    return buildSearchUrl('/cauta', next);
                  })();
              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.bucket}</span>
                  <span class="font-mono text-xs tabular-nums opacity-70">{fmt(b.count)}</span>
                </a>
              );
            })}
          </div>
        </div>

        <!-- Cross-cutting toggles -->
        <div>
          <h3 class="label-meta mb-2">Marcatori</h3>
          <div class="space-y-0.5">
            <a href={filters.eu_funded ? withoutFilter('eu_funded') : withFilter('eu_funded', true)}
               class:list={['flex items-baseline justify-between px-2 py-1.5 text-sm hover:bg-stamp transition-none', { 'bg-ink text-paper': filters.eu_funded }]}>
              <span class="font-display">🇪🇺 Cofinanțat UE</span>
            </a>
            <a href={filters.has_lots ? withoutFilter('has_lots') : withFilter('has_lots', true)}
               class:list={['flex items-baseline justify-between px-2 py-1.5 text-sm hover:bg-stamp transition-none', { 'bg-ink text-paper': filters.has_lots }]}>
              <span class="font-display">Cu loturi</span>
            </a>
            <a href={filters.framework_agreement ? withoutFilter('framework_agreement') : withFilter('framework_agreement', true)}
               class:list={['flex items-baseline justify-between px-2 py-1.5 text-sm hover:bg-stamp transition-none', { 'bg-ink text-paper': filters.framework_agreement }]}>
              <span class="font-display">Acord-cadru</span>
            </a>
          </div>
        </div>
      </aside>

      <!-- Results + Map -->
      <section class="lg:col-span-9 grid lg:grid-cols-12 gap-0">

        <!-- Results list -->
        <div class="lg:col-span-7 px-4 md:px-5 py-6 lg:border-r-2 lg:border-ink">
          {data.results.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>
            </div>
          )}

          <ol class="divide-y-2 divide-ink/20" id="results-list">
            {data.results.map(r => {
              const sCui = (r.supplier_cui || '').replace(/^RO\s*/i, '').trim();
              const euCount = euMap.get(sCui);
              const regasCount = regasMap.get(sCui);
              const aepCount = aepMap.get(sCui);
              const datornic = datornicMap.get(sCui);
              const stateMeta = r.procedure_state ? STATE_LABELS[r.procedure_state] : null;
              return (
              <li>
                <article class="grid md:grid-cols-[90px_1fr_auto] gap-x-4 gap-y-1 py-4 hover:bg-stamp transition-none px-2 -mx-2 search-row"
                         data-result-id={r.id}>
                  <div class="font-mono text-xs tabular-nums text-ink/60 shrink-0">{dateFmt(r.publication_date)}</div>
                  <div class="min-w-0">
                    <div class="flex flex-wrap items-center gap-1.5 mb-1 label-meta normal-case tracking-normal text-ink/60">
                      {r.cpv_division_name && <span>{r.cpv_division_name}</span>}
                      <span class="text-ink/40">·</span>
                      <span>{TYPE_LABELS[r.type] || r.type}</span>
                      {stateMeta && (
                        <span class:list={[
                          'px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-meta border border-ink/30',
                          stateMeta.tone === 'good' ? 'bg-green-100 text-green-900' :
                          stateMeta.tone === 'warn' ? 'bg-amber-100 text-amber-900' :
                          stateMeta.tone === 'bad' ? 'bg-red-100 text-red-900' :
                          'bg-paper text-ink/70'
                        ]}>{stateMeta.label}</span>
                      )}
                      {r.source.startsWith('wsp_') && <span class="bg-stamp text-ink px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-meta">WSP live</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 UE</span>}
                      {r.risk_flags && r.risk_flags.length > 0 && r.risk_flags.map(f => (
                        <a href={`/risc/${f.code === 'single_bidder' ? 'single-bidder' : f.code === 'short_deadline' ? 'termen-scurt' : f.code === 'suspicious_savings' ? 'economii-suspect' : f.code === 'overprice' ? 'overprice' : ''}`}
                           title={f.label}
                           class={`px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-meta border border-ink ${f.severity === 'high' ? 'bg-signal text-paper' : 'bg-stamp text-ink'} hover:bg-ink hover:text-paper`}>
                          ⚑ {f.label}
                        </a>
                      ))}
                    </div>
                    <h2 class="font-display font-semibold text-base leading-snug mb-1">
                      <a href={`/anunt/${r.id}`} class="hover:underline">{r.title || r.ref_number}</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/${sCui}`} class="text-ink hover:underline font-medium">{r.supplier_name}</a>
                          {datornic !== undefined && (
                            <a href={`/firma/${sCui}`}
                               title={`Pe lista publică ANAF datornici (${datornic.toLocaleString('ro-RO')} RON)`}
                               class="ml-1.5 inline-block bg-signal text-paper px-1 py-0.5 font-mono text-[10px] uppercase tracking-meta hover:bg-ink">
                              🚨 datornic
                            </a>
                          )}
                          {euCount !== undefined && euCount > 0 && (
                            <a href={`/firma/${sCui}`}
                               title={`${euCount} anunțuri ca beneficiar privat de fonduri EU`}
                               class="ml-1.5 inline-block bg-state text-paper px-1 py-0.5 font-mono text-[10px] uppercase tracking-meta hover:bg-ink">
                              🇪🇺 {euCount}
                            </a>
                          )}
                          {regasCount !== undefined && regasCount > 0 && (
                            <a href={`/firma/${sCui}`}
                               title={`${regasCount} ajutoare de stat în registrul Consiliului Concurenței (RegAS)`}
                               class="ml-1.5 inline-block bg-state text-paper px-1 py-0.5 font-mono text-[10px] uppercase tracking-meta hover:bg-ink">
                              🏛️ {regasCount}
                            </a>
                          )}
                          {aepCount !== undefined && aepCount > 0 && (
                            <a href={`/firma/${sCui}`}
                               title={`${aepCount} donații la partide politice raportate la AEP`}
                               class="ml-1.5 inline-block bg-state text-paper px-1 py-0.5 font-mono text-[10px] uppercase tracking-meta hover:bg-ink">
                              🗳️ {aepCount}
                            </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 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.estimated_value && !r.awarded_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>

          {data.total > limit && (
            <nav class="flex items-center justify-between mt-8 pt-6 border-t-2 border-ink">
              {offset > 0 ? (
                <a href={buildSearchUrlWithPagination('/cauta', { ...filters, offset: Math.max(0, offset - limit) })}
                   class="btn-brutal">← Anterior</a>
              ) : <span></span>}
              <span class="label-meta">
                <span class="font-mono">{offset + 1}–{Math.min(offset + limit, data.total)}</span> din <span class="font-mono">{fmt(data.total)}</span>
              </span>
              {offset + limit < data.total ? (
                <a href={buildSearchUrlWithPagination('/cauta', { ...filters, offset: offset + limit })}
                   class="btn-brutal">Următor →</a>
              ) : <span></span>}
            </nav>
          )}
        </div>

        <!-- Map column (sticky) -->
        <div class="lg:col-span-5 px-4 md:px-0 py-6 md:pl-5 md:pr-5">
          <div class="lg:sticky lg:top-2">
            <div class="label-meta mb-2 flex items-center justify-between">
              <span>Harta rezultatelor</span>
              <span class="font-mono text-[10px] tabular-nums text-ink/60 normal-case tracking-normal">
                {markers.length} pcte · {data.results.length} anunțuri
              </span>
            </div>
            {markers.length > 0 ? (
              <div class="border-2 border-ink">
                <SearchMap markers={markers} height={560} client:only="react" />
              </div>
            ) : (
              <div class="border-2 border-ink p-8 text-center bg-stamp/20">
                <div class="label-meta mb-1">Nu există coordonate</div>
                <p class="font-serif italic text-sm text-ink/70">
                  Niciuna dintre firmele/autoritățile din rezultate nu este încă geocodată.
                </p>
              </div>
            )}
            <div class="mt-3 font-serif italic text-xs text-ink/60">
              Punctele roșii sunt furnizori, cele albastre sunt autorități contractante. Click pe un punct
              deschide profilul firmei sau al autorității într-un tab nou.
            </div>
          </div>
        </div>
      </section>
    </div>
  </main>

  <script>
    // CPV autocomplete -> URL param. Listens for the CustomEvent dispatched
    // by <CpvAutocomplete> and updates the `cpv` query string in place.
    document.addEventListener('cpv:selected', (e: Event) => {
      const detail = (e as CustomEvent).detail as { code: string | null };
      const url = new URL(window.location.href);
      if (detail.code) url.searchParams.set('cpv', detail.code);
      else url.searchParams.delete('cpv');
      url.searchParams.delete('offset');
      window.location.assign(url.toString());
    });

    // Result-row hover → highlight corresponding marker on SearchMap.
    // Uses event delegation on the results <ol> and dispatches a CustomEvent
    // that SearchMap.tsx subscribes to via window.addEventListener('cauta:hover').
    document.querySelectorAll<HTMLElement>('.search-row[data-result-id]').forEach((row) => {
      const id = Number(row.dataset.resultId);
      if (!Number.isFinite(id)) return;
      row.addEventListener('mouseenter', () => {
        window.dispatchEvent(new CustomEvent('cauta:hover', { detail: { id } }));
      });
      row.addEventListener('mouseleave', () => {
        window.dispatchEvent(new CustomEvent('cauta:hover', { detail: { id: null } }));
      });
    });
  </script>
</AchizitiiLayout>
