---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import { getAnnouncementDetail } from '../../lib/announcement-queries.js';

export const prerender = false;

const idParam = (Astro.params.id as string) || '';
const idNum = /^\d+$/.test(idParam) ? Number(idParam) : null;
if (idNum === null) return Astro.redirect('/404');

const a = await getAnnouncementDetail(idNum);
if (!a) return Astro.redirect('/404');

const fmt = (n: number | null | undefined) =>
  n == null ? '–' : new Intl.NumberFormat('ro-RO', { maximumFractionDigits: 0 }).format(Number(n));
const dateFmt = (d: string | null) =>
  d ? new Date(d).toLocaleDateString('ro-RO', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\./g, '.') : '–';
const stripCui = (cui: string | null | undefined) => (cui || '').replace(/^RO\s*/i, '').trim();

// Savings %
const est = Number(a.estimated_value) || 0;
const award = Number(a.awarded_value) || 0;
const savings = (est > 0 && award > 0 && award <= est) ? Math.round(100 * (est - award) / est) : null;

// JSONB normalization helpers
function asArray(v: any): any[] {
  if (!v) return [];
  if (Array.isArray(v)) return v;
  if (typeof v === 'object') return Object.values(v);
  return [];
}
function asObject(v: any): Record<string, any> {
  if (!v || typeof v !== 'object' || Array.isArray(v)) return {};
  return v;
}

const documents = asArray(a.documents);
const awardCriteria = asArray(a.award_criteria);
const lots = asArray(a.lots);
const details = asObject(a.details);
const hasLots = a.has_lots || a.contract_has_lots;

// Try to extract a short_description / description from details
const shortDescription =
  details.short_description || details.shortDescription ||
  details.description || details.descriere ||
  null;

// Other detail fields as chips (skip the description we already used)
const detailChips: { key: string; value: string }[] = [];
for (const [k, v] of Object.entries(details)) {
  if (['short_description', 'shortDescription', 'description', 'descriere'].includes(k)) continue;
  if (v == null || v === '') continue;
  if (typeof v === 'object') continue;
  const sv = String(v);
  if (sv.length > 120) continue;
  detailChips.push({ key: k, value: sv });
}

const sourceLabel = a.source?.startsWith('ted') ? 'TED' : a.source?.startsWith('wsp') ? 'SEAP / WSP' : (a.source || 'SEAP');
---

<AchizitiiLayout
  title={`${a.title || a.ref_number} — Anunț ${a.id}`}
  description={`Anunț ${a.ref_number}: ${a.authority_name || '—'} → ${a.supplier_name || '—'} · ${fmt(a.awarded_value)} RON.`}
>
  <main class="bg-paper text-ink min-h-screen">

    <!-- Top register strip with breadcrumb -->
    <div class="bg-ink text-paper">
      <div class="max-w-content mx-auto px-4 py-3 flex items-center justify-between gap-3 flex-wrap">
        <div class="font-mono text-xs uppercase tracking-meta flex flex-wrap items-center gap-x-2 gap-y-1">
          <a href="/" class="hover:text-stamp">← vreaudigital</a>
          <span class="text-paper/40">/</span>
          {a.cpv_division && (
            <>
              <a href={`/categoria/${a.cpv_division}`} class="hover:text-stamp truncate max-w-[200px]">
                {a.cpv_division_name || a.cpv_division}
              </a>
              <span class="text-paper/40">/</span>
            </>
          )}
          {a.county_code && (
            <>
              <a href={`/judet/${a.county_code}`} class="hover:text-stamp">{a.county_code}</a>
              <span class="text-paper/40">/</span>
            </>
          )}
          <span class="text-paper/60">Anunț {a.id}</span>
        </div>
        <span class="font-mono text-xs uppercase tracking-meta text-paper/60">{sourceLabel}</span>
      </div>
    </div>

    <!-- Header: title + meta -->
    <header class="border-b-2 border-ink">
      <div class="max-w-content mx-auto px-4 py-10 md:py-14">
        <div class="label-meta mb-3">
          {a.type} · Ref. <span class="font-mono normal-case tracking-normal text-ink">{a.ref_number}</span>
        </div>
        <h1 class="font-display font-bold text-2xl md:text-4xl leading-[1.1] tracking-tight text-ink max-w-4xl">
          {a.title || a.ref_number}
        </h1>
        <div class="flex flex-wrap gap-x-6 gap-y-1 mt-4 label-meta text-ink/70">
          <span>Publicat <span class="font-mono normal-case tracking-normal text-ink">{dateFmt(a.publication_date)}</span></span>
          {a.notice_state && <span>{a.notice_state}</span>}
          {a.procedure_state && <span>{a.procedure_state}</span>}
          {a.legislation && <span>{a.legislation}</span>}
          {a.joue && <span class="bg-stamp text-ink px-1.5">JOUE</span>}
          {a.framework_agreement && <span class="bg-stamp text-ink px-1.5">Acord-cadru</span>}
        </div>
        {shortDescription && (
          <p class="font-serif italic text-base md:text-lg text-ink/80 mt-5 max-w-3xl leading-relaxed">
            {shortDescription}
          </p>
        )}
      </div>
    </header>

    <!-- Stats: 4-up -->
    <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(a.estimated_value)}</div>
          <div class="stat-label">Estimat ({a.currency || 'RON'})</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{fmt(a.awarded_value)}</div>
          <div class="stat-label">Atribuit ({a.currency || 'RON'})</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num">{savings == null ? '–' : `${savings}%`}</div>
          <div class="stat-label">Economie</div>
        </div>
        <div class="stat-tile px-3 md:px-6">
          <div class="stat-num text-base md:text-lg leading-tight">
            {a.notice_state || a.procedure_state || a.type}
          </div>
          <div class="stat-label">Status</div>
        </div>
      </div>
    </section>

    <!-- Two-col: details (left) + sidebar (right) -->
    <section class="grid lg:grid-cols-12 gap-0 border-b-2 border-ink">
      <div class="lg:col-span-8 px-4 md:px-8 py-10 lg:border-r-2 lg:border-ink">

        <!-- Authority block -->
        {a.authority_cui && (
          <div class="mb-8">
            <div class="label-meta mb-2">Autoritate contractantă</div>
            <a href={`/autoritate/${a.authority_cui}`} class="block -mx-2 px-2 py-2 hover:bg-stamp transition-none">
              <div class="font-display font-semibold text-lg md:text-xl text-ink">{a.authority_name || '—'}</div>
              <div class="label-meta normal-case tracking-normal text-ink/60 mt-1">
                CUI <span class="font-mono">{a.authority_cui}</span>
                {a.authority_county && <> · {a.authority_county}</>}
                {a.authority_type && <> · {a.authority_type}</>}
              </div>
              {a.authority_address && <div class="font-serif italic text-sm text-ink/70 mt-1">{a.authority_address}</div>}
            </a>
          </div>
        )}

        <!-- Supplier block -->
        {a.supplier_cui && (
          <div class="mb-8">
            <div class="label-meta mb-2">Furnizor / Câștigător</div>
            <a href={`/firma/${stripCui(a.supplier_cui)}`} class="block -mx-2 px-2 py-2 hover:bg-stamp transition-none">
              <div class="font-display font-semibold text-lg md:text-xl text-ink">
                {a.supplier_name || '—'}
                {a.supplier_is_sme === true && <span class="ml-2 bg-stamp text-ink px-1.5 label-meta">IMM</span>}
              </div>
              <div class="label-meta normal-case tracking-normal text-ink/60 mt-1">
                CUI <span class="font-mono">{a.supplier_cui}</span>
                {a.supplier_county && <> · {a.supplier_county}</>}
              </div>
              {a.supplier_address && <div class="font-serif italic text-sm text-ink/70 mt-1">{a.supplier_address}</div>}
            </a>
          </div>
        )}

        <!-- CPV + procedure block -->
        <div class="mb-8 grid sm:grid-cols-2 gap-y-5 gap-x-8 border-t-2 border-ink/20 pt-6">
          {a.cpv_division && (
            <div>
              <div class="label-meta mb-1">Categorie CPV</div>
              <a href={`/categoria/${a.cpv_division}`} class="font-display font-semibold text-base text-ink hover:bg-stamp -mx-1 px-1">
                {a.cpv_division_name || a.cpv_division}
              </a>
              <div class="label-meta normal-case tracking-normal text-ink/60 mt-1">
                <span class="font-mono">{a.cpv_code || a.cpv_division}</span>
                {a.cpv_name_ro && a.cpv_name_ro !== a.cpv_division_name && <> · {a.cpv_name_ro}</>}
              </div>
            </div>
          )}
          {a.procedure_type && (
            <div>
              <div class="label-meta mb-1">Procedură</div>
              <div class="font-display font-semibold text-base text-ink">{a.procedure_type}</div>
              {a.legislation && <div class="label-meta normal-case tracking-normal text-ink/60 mt-1">{a.legislation}</div>}
            </div>
          )}
          {hasLots && (
            <div>
              <div class="label-meta mb-1">Loturi</div>
              <div class="font-mono tabular-nums text-base text-ink">{a.lots_count || lots.length || '—'}</div>
            </div>
          )}
          {a.framework_agreement && (
            <div>
              <div class="label-meta mb-1">Acord-cadru</div>
              <div class="font-display font-semibold text-base text-ink">Da</div>
            </div>
          )}
          {a.county_code && (
            <div>
              <div class="label-meta mb-1">Județ</div>
              <a href={`/judet/${a.county_code}`} class="font-display font-semibold text-base text-ink hover:bg-stamp -mx-1 px-1">
                {a.county_code}
              </a>
            </div>
          )}
        </div>

        <!-- Lots section -->
        {hasLots && lots.length > 0 && (
          <div class="mb-8 border-t-2 border-ink/20 pt-6">
            <div class="label-meta mb-4">Loturi ({lots.length})</div>
            <ol class="divide-y divide-ink/20">
              {lots.map((lot: any, i: number) => {
                const lotTitle = lot.title || lot.name || lot.titlu || `Lot ${i + 1}`;
                const lotValue = lot.awarded_value ?? lot.value ?? lot.valoare ?? null;
                const lotDesc = lot.description || lot.short_description || lot.descriere || null;
                return (
                  <li class="py-4 px-2 -mx-2 grid md:grid-cols-[60px_1fr_auto] gap-x-5 gap-y-1 items-baseline">
                    <span class="font-mono text-xs text-ink/40 tabular-nums">{String(i + 1).padStart(2, '0')}</span>
                    <div class="min-w-0">
                      <div class="font-display font-semibold text-base text-ink leading-snug">{lotTitle}</div>
                      {lotDesc && <div class="font-serif italic text-sm text-ink/70 mt-1">{String(lotDesc)}</div>}
                    </div>
                    {lotValue != null && (
                      <div class="font-mono font-bold tabular-nums text-base text-ink text-right whitespace-nowrap">
                        {fmt(Number(lotValue))}
                        <span class="font-body text-xs text-ink/60 font-normal ml-1">RON</span>
                      </div>
                    )}
                  </li>
                );
              })}
            </ol>
          </div>
        )}

        <!-- Detail chips -->
        {detailChips.length > 0 && (
          <div class="border-t-2 border-ink/20 pt-6">
            <div class="label-meta mb-3">Detalii suplimentare</div>
            <div class="flex flex-wrap gap-2">
              {detailChips.map((d) => (
                <span class="chip-brutal">
                  <span class="text-ink/60 mr-1">{d.key}:</span>
                  <span class="normal-case tracking-normal">{d.value}</span>
                </span>
              ))}
            </div>
          </div>
        )}
      </div>

      <!-- Sidebar -->
      <aside class="lg:col-span-4 px-4 md:px-8 py-10 border-t-2 border-ink lg:border-t-0">

        <div class="mb-8">
          <div class="label-meta mb-3">Calendar</div>
          <dl class="divide-y divide-ink/20">
            <div class="flex justify-between gap-4 py-2">
              <dt class="label-meta normal-case tracking-normal text-ink/60">Publicare</dt>
              <dd class="font-mono text-sm tabular-nums text-ink">{dateFmt(a.publication_date)}</dd>
            </div>
            {a.deadline_submission && (
              <div class="flex justify-between gap-4 py-2">
                <dt class="label-meta normal-case tracking-normal text-ink/60">Termen depunere</dt>
                <dd class="font-mono text-sm tabular-nums text-ink">{dateFmt(a.deadline_submission)}</dd>
              </div>
            )}
            {a.opening_date && (
              <div class="flex justify-between gap-4 py-2">
                <dt class="label-meta normal-case tracking-normal text-ink/60">Deschidere</dt>
                <dd class="font-mono text-sm tabular-nums text-ink">{dateFmt(a.opening_date)}</dd>
              </div>
            )}
            {a.contract_date && (
              <div class="flex justify-between gap-4 py-2">
                <dt class="label-meta normal-case tracking-normal text-ink/60">Contract</dt>
                <dd class="font-mono text-sm tabular-nums text-ink">{dateFmt(a.contract_date)}</dd>
              </div>
            )}
          </dl>
        </div>

        {awardCriteria.length > 0 && (
          <div class="mb-8">
            <div class="label-meta mb-3">Criterii atribuire</div>
            <ul class="divide-y divide-ink/20">
              {awardCriteria.map((cr: any) => {
                const name = cr.name || cr.title || cr.criteriu || cr.label || (typeof cr === 'string' ? cr : 'Criteriu');
                const weight = cr.weight ?? cr.pondere ?? cr.percentage ?? null;
                return (
                  <li class="py-2 flex items-baseline justify-between gap-3">
                    <span class="font-display text-sm text-ink leading-snug">{String(name)}</span>
                    {weight != null && (
                      <span class="font-mono text-xs tabular-nums text-ink/70 shrink-0">{String(weight)}{typeof weight === 'number' ? '%' : ''}</span>
                    )}
                  </li>
                );
              })}
            </ul>
          </div>
        )}

        {documents.length > 0 && (
          <div class="mb-8">
            <div class="label-meta mb-3">Documente ({documents.length})</div>
            <ul class="divide-y divide-ink/20">
              {documents.slice(0, 12).map((doc: any) => {
                const url = doc.url || doc.link || doc.href || null;
                const name = doc.name || doc.title || doc.filename || doc.numeFisier || (url ? url.split('/').pop() : 'Document');
                const ext = (typeof name === 'string' && name.includes('.'))
                  ? name.split('.').pop()?.toLowerCase()
                  : null;
                return (
                  <li class="py-2">
                    {url ? (
                      <a href={url} target="_blank" rel="noopener" class="flex items-baseline justify-between gap-3 -mx-2 px-2 hover:bg-stamp transition-none">
                        <span class="font-body text-sm text-ink underline truncate">{String(name)}</span>
                        {ext && <span class="font-mono text-xs uppercase text-ink/60 shrink-0">{ext}</span>}
                      </a>
                    ) : (
                      <span class="font-body text-sm text-ink/70 truncate block">{String(name)}</span>
                    )}
                  </li>
                );
              })}
            </ul>
          </div>
        )}

        <div class="border-t-2 border-ink pt-5">
          <div class="label-meta mb-3">Sursă</div>
          {a.seap_url ? (
            <a href={a.seap_url} target="_blank" rel="noopener" class="btn-brutal w-full justify-between">
              <span>Vezi în {sourceLabel}</span>
              <span>↗</span>
            </a>
          ) : (
            <div class="label-meta normal-case tracking-normal text-ink/60">Sursă: {sourceLabel}</div>
          )}
        </div>
      </aside>
    </section>

    <footer class="bg-ink text-paper">
      <div class="max-w-content mx-auto px-4 py-8 flex flex-wrap items-center justify-between gap-4">
        <div class="label-meta text-paper/60">Anunț #{a.id} · {a.ref_number}</div>
        <div class="flex flex-wrap gap-2">
          {a.cpv_division && (
            <a href={`/categoria/${a.cpv_division}`} class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">
              Categorie {a.cpv_division}
            </a>
          )}
          {a.county_code && (
            <a href={`/judet/${a.county_code}`} class="chip-brutal bg-ink text-paper border-paper hover:bg-paper hover:text-ink">
              Județ {a.county_code}
            </a>
          )}
        </div>
      </div>
    </footer>
  </main>
</AchizitiiLayout>
