---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import {
  getBeneficiarAnunt,
  getBeneficiarLots,
  getBeneficiarAlsoPosted,
  getProiectAnunturi,
  getProiectContext,
} from '../../lib/beneficiar-privat-queries.js';
import { getFirmDetails } from '../../lib/profile-queries.js';
import '../../components/profile/profile.css';

export const prerender = false;

const idParam = Astro.params.id as string;
const id = parseInt(idParam);
if (!Number.isFinite(id) || id <= 0) return Astro.redirect('/404');

const anunt = await getBeneficiarAnunt(id);
if (!anunt) return Astro.redirect('/404');

const [lots, alsoPosted, projectAnunturi, firmDetails, proiectCtx] = await Promise.all([
  getBeneficiarLots(id),
  getBeneficiarAlsoPosted(anunt.cui, anunt.beneficiar_name, id),
  anunt.smis_proiect_id ? getProiectAnunturi(anunt.smis_proiect_id, id) : Promise.resolve([]),
  anunt.cui ? getFirmDetails(anunt.cui) : Promise.resolve(null),
  anunt.smis_proiect_id ? getProiectContext(anunt.smis_proiect_id) : Promise.resolve(null),
]);

const fmtRon = (v: number | null | undefined) => {
  if (v == null) return '–';
  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 `${(v / 1_000).toFixed(0)}K`;
  return Math.round(v).toString();
};
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: 'short', day: 'numeric' }) : '–';

const totalBuget = lots.reduce((s, l) => s + (Number(l.buget_lei) || 0), 0);
const isOpen = (anunt.procedura_status || '').toLowerCase().includes('curs');
---

<AchizitiiLayout
  title={`${anunt.beneficiar_name} — Anunț #${anunt.id} · vreaudigital.ro`}
  description={`${anunt.beneficiar_name} (proiect SMIS ${anunt.smis_proiect_code || '?'}): ${anunt.tip_contract || '?'}, ${fmtRon(totalBuget)} RON din ${lots.length} lot${lots.length === 1 ? '' : 'uri'}.`}
>
  <main class="max-w-content mx-auto px-4 py-6">

    <!-- Breadcrumb -->
    <div class="text-xs text-meta mb-3">
      <a href="/" class="hover:underline">Achiziții</a> ·
      <a href="/fonduri-ue" class="hover:underline">Fonduri EU</a> ·
      Beneficiar privat #{anunt.id}
    </div>

    <!-- Header card -->
    <div class="profile-header">
      <div class="profile-header-flag-strip" />
      <div class="flex items-start gap-4">
        <div class="profile-icon">🇪🇺</div>
        <div class="flex-1 min-w-0">
          <h1 class="profile-name">{anunt.beneficiar_name}</h1>
          <div class="profile-subline">
            {anunt.cui && <span class="badge font-mono">CUI {anunt.cui}</span>}
            {!anunt.cui && <span class="badge badge-signal">CUI nematchat</span>}
            {anunt.beneficiar_program_tag && <span class="badge badge-stamp">{anunt.beneficiar_program_tag}</span>}
            {anunt.beneficiar_judet && <span class="badge">📍 {anunt.beneficiar_judet}</span>}
            <span class="badge">{anunt.tip_contract || '?'}</span>
            <span class="badge" data-tone={isOpen ? 'ok' : 'state'}>{isOpen ? '🟢 În ofertare' : '⚪ Procedură închisă'}</span>
          </div>
          <div class="profile-dossier">
            Anunț de achiziție publicat de un beneficiar <strong>privat</strong> al fondurilor europene
            ({anunt.beneficiar_program_tag || 'SMIS'}). Aceste proceduri NU intră în SEAP, dar trebuie
            făcute transparent conform Manualului Beneficiarului. Total buget: <strong>{fmtRon(totalBuget)} RON</strong>
            din <strong>{lots.length}</strong> lot{lots.length === 1 ? '' : 'uri'}.
            {anunt.cui && firmDetails && <> Beneficiarul are profil în registrul nostru de firme: <a href={`/firma/${anunt.cui}`} class="text-stamp font-semibold hover:underline">vezi profil firmă completă</a>.</>}
          </div>

          <div class="profile-firm-meta" style="margin-top: 14px;">
            {anunt.beneficiar_adresa && (
              <div class="profile-firm-meta-item">
                <div class="profile-firm-meta-label">Adresă</div>
                <div class="profile-firm-meta-value">{anunt.beneficiar_adresa}{anunt.beneficiar_localitate ? `, ${anunt.beneficiar_localitate}` : ''}{anunt.beneficiar_judet ? `, jud. ${anunt.beneficiar_judet}` : ''}</div>
              </div>
            )}
            {anunt.beneficiar_contact && (
              <div class="profile-firm-meta-item">
                <div class="profile-firm-meta-label">Contact</div>
                <div class="profile-firm-meta-value">{anunt.beneficiar_contact}</div>
              </div>
            )}
            {anunt.beneficiar_telefon && (
              <div class="profile-firm-meta-item">
                <div class="profile-firm-meta-label">Telefon</div>
                <div class="profile-firm-meta-value">{anunt.beneficiar_telefon}</div>
              </div>
            )}
            {anunt.beneficiar_regiune && (
              <div class="profile-firm-meta-item">
                <div class="profile-firm-meta-label">Regiune</div>
                <div class="profile-firm-meta-value">{anunt.beneficiar_regiune}</div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>

    <!-- KPI strip -->
    <div class="profile-kpi-strip">
      <div class="profile-kpi">
        <div class="profile-kpi-label">Buget total anunț</div>
        <div class="profile-kpi-value">{fmtRon(totalBuget)} <span style="font-size:12px;color:var(--meta);font-weight:500;">RON</span></div>
        <div class="profile-kpi-hint">{lots.length} lot{lots.length === 1 ? '' : 'uri'}</div>
      </div>
      <div class="profile-kpi">
        <div class="profile-kpi-label">Tip contract</div>
        <div class="profile-kpi-value" style="font-size:18px;">{anunt.tip_contract || '?'}</div>
      </div>
      <div class="profile-kpi" data-tone={isOpen ? 'ok' : 'state'}>
        <div class="profile-kpi-label">Status</div>
        <div class="profile-kpi-value" style="font-size:18px;">{isOpen ? 'Deschisă' : 'Închisă'}</div>
        <div class="profile-kpi-hint">{anunt.procedura_status || ''}</div>
      </div>
      <div class="profile-kpi">
        <div class="profile-kpi-label">Data publicare</div>
        <div class="profile-kpi-value" style="font-size:18px;">{dateFmt(anunt.data_publicare)}</div>
      </div>
      <div class="profile-kpi" data-tone={isOpen ? 'warn' : 'ok'}>
        <div class="profile-kpi-label">Termen ofertă</div>
        <div class="profile-kpi-value" style="font-size:18px;">{dateFmt(anunt.data_limita_oferta)}</div>
        <div class="profile-kpi-hint">{anunt.ora_limita_oferta || ''}</div>
      </div>
    </div>

    <!-- Project box -->
    {anunt.smis_proiect_code && (
      <div class="profile-section">
        <h2 class="profile-section-title">📋 Proiect EU</h2>
        <div class="profile-firm-meta">
          <div class="profile-firm-meta-item">
            <div class="profile-firm-meta-label">Cod SMIS</div>
            <div class="profile-firm-meta-value font-mono">{anunt.smis_proiect_code}</div>
          </div>
          <div class="profile-firm-meta-item" style="grid-column: span 3;">
            <div class="profile-firm-meta-label">Denumire</div>
            <div class="profile-firm-meta-value">{proiectCtx?.titlu || anunt.smis_proiect_name || '—'}</div>
          </div>
          {proiectCtx?.program_op_cod && (
            <div class="profile-firm-meta-item">
              <div class="profile-firm-meta-label">Program operațional</div>
              <div class="profile-firm-meta-value">
                <span class="badge badge-stamp font-mono">{proiectCtx.program_op_cod}</span>
                {proiectCtx.program_op_text && <span style="margin-left:6px;">{proiectCtx.program_op_text}</span>}
              </div>
            </div>
          )}
          {proiectCtx?.axa_cod && (
            <div class="profile-firm-meta-item" style="grid-column: span 2;">
              <div class="profile-firm-meta-label">Axă prioritară</div>
              <div class="profile-firm-meta-value">
                <span class="font-mono">{proiectCtx.axa_cod}</span>
                {proiectCtx.axa_text && <span style="margin-left:6px;color:var(--meta);">{proiectCtx.axa_text}</span>}
              </div>
            </div>
          )}
          {proiectCtx?.domeniul_cod && (
            <div class="profile-firm-meta-item" style="grid-column: span 2;">
              <div class="profile-firm-meta-label">Domeniul de intervenție</div>
              <div class="profile-firm-meta-value">
                <span class="font-mono">{proiectCtx.domeniul_cod}</span>
                {proiectCtx.domeniul_text && <span style="margin-left:6px;color:var(--meta);">{proiectCtx.domeniul_text}</span>}
              </div>
            </div>
          )}
          {proiectCtx?.operatiune_cod && (
            <div class="profile-firm-meta-item" style="grid-column: span 2;">
              <div class="profile-firm-meta-label">Operațiune</div>
              <div class="profile-firm-meta-value">
                <span class="font-mono">{proiectCtx.operatiune_cod}</span>
                {proiectCtx.operatiune_text && <span style="margin-left:6px;color:var(--meta);">{proiectCtx.operatiune_text}</span>}
              </div>
            </div>
          )}
          {proiectCtx?.data_contract && (
            <div class="profile-firm-meta-item">
              <div class="profile-firm-meta-label">Data contractului</div>
              <div class="profile-firm-meta-value">{dateFmt(proiectCtx.data_contract)}</div>
            </div>
          )}
        </div>
        {projectAnunturi.length > 0 && (
          <div style="margin-top: 14px;">
            <div class="text-sm text-meta mb-2">Alte {projectAnunturi.length} anunțuri din același proiect:</div>
            <div>
              {projectAnunturi.map((p) => (
                <a href={`/beneficiar-privat/${p.id}`} class="profile-contract">
                  <div class="profile-contract-meta">
                    <span>📄</span>
                    <span>{p.tip_contract || '?'}</span>
                    <span>·</span>
                    <span>{dateFmt(p.data_publicare)}</span>
                  </div>
                  <div class="profile-contract-title">#{p.id} · {p.titlu || p.beneficiar_name || '?'}</div>
                  <div class="profile-contract-bottom">
                    <span class="profile-contract-cp">🏢 {p.beneficiar_name}</span>
                    <span class="profile-contract-value">{fmtRon(Number(p.total_buget))} RON</span>
                  </div>
                </a>
              ))}
            </div>
          </div>
        )}
      </div>
    )}

    <!-- Loturi -->
    <div class="profile-section">
      <h2 class="profile-section-title">
        📦 Loturi
        <span class="profile-section-title-meta">{lots.length}</span>
      </h2>
      <div>
        {lots.map((l) => (
          <div class="profile-contract">
            <div class="profile-contract-meta">
              <span class="font-mono">Lot {l.lot_no}</span>
              {l.lot_label && l.lot_label !== String(l.lot_no) && <><span>·</span><span>{l.lot_label}</span></>}
              {l.cpv_cod && <><span>·</span><span class="font-mono">CPV {l.cpv_cod}</span></>}
              {l.durata_contract && <><span>·</span><span>{l.durata_contract}</span></>}
            </div>
            <div class="profile-contract-bottom" style="margin-top: 6px;">
              <div style="display:flex;gap:12px;">
                {l.descriere_url && <a href={l.descriere_url} target="_blank" rel="noopener" class="text-stamp text-sm hover:underline">Descriere lot ↗</a>}
                {l.spec_url && <a href={l.spec_url} target="_blank" rel="noopener" class="text-stamp text-sm hover:underline">Specificații PDF ↗</a>}
              </div>
              <span class="profile-contract-value">{fmtRon(Number(l.buget_lei))} RON</span>
            </div>
          </div>
        ))}
      </div>
    </div>

    <!-- Other anunturi by same beneficiar -->
    {alsoPosted.length > 0 && (
      <div class="profile-section">
        <h2 class="profile-section-title">
          🔁 Alte anunțuri ale aceluiași beneficiar
          <span class="profile-section-title-meta">{alsoPosted.length}</span>
        </h2>
        <div>
          {alsoPosted.map((p) => (
            <a href={`/beneficiar-privat/${p.id}`} class="profile-contract">
              <div class="profile-contract-meta">
                <span>📄</span>
                <span>{p.tip_contract || '?'}</span>
                <span>·</span>
                <span>{dateFmt(p.data_publicare)}</span>
              </div>
              <div class="profile-contract-title">#{p.id} · {p.titlu || '—'}</div>
              <div class="profile-contract-bottom">
                <span></span>
                <span class="profile-contract-value">{fmtRon(Number(p.total_buget))} RON</span>
              </div>
            </a>
          ))}
        </div>
      </div>
    )}

    <!-- External links -->
    <div class="profile-external">
      <div class="profile-external-label">🔍 Surse</div>
      <div class="profile-external-links">
        <a href={`https://beneficiar.fonduri-ue.ro:8080/anunturi/details/2/${anunt.id}/`} target="_blank" rel="noopener" class="profile-external-link">Anunțul original (fonduri-ue.ro) ↗</a>
        {anunt.smis_proiect_id && anunt.smis_proiect_code && (
          <a href={`https://beneficiar.fonduri-ue.ro:8080/proiecte/details/1/${anunt.smis_proiect_id}/`} target="_blank" rel="noopener" class="profile-external-link">Proiect SMIS {anunt.smis_proiect_code} ↗</a>
        )}
        {anunt.cui && (
          <a href={`/firma/${anunt.cui}`} class="profile-external-link">Profil firmă în registrul nostru →</a>
        )}
        <a href={`https://www.google.com/search?q=${encodeURIComponent(anunt.beneficiar_name + ' fonduri europene')}`} target="_blank" rel="noopener" class="profile-external-link">Google</a>
      </div>
    </div>

  </main>
</AchizitiiLayout>
