---
import AchizitiiLayout from '../../layouts/AchizitiiLayout.astro';
import {
  getProiectFull,
  getProiectAllAnunturi,
} 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 proiect = await getProiectFull(id);
if (!proiect) return Astro.redirect('/404');

const [anunturi, firmDetails] = await Promise.all([
  getProiectAllAnunturi(id),
  proiect.beneficiar_cui ? getFirmDetails(proiect.beneficiar_cui) : 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 openCount = anunturi.filter((a: any) => (a.procedura_status || '').toLowerCase().includes('curs')).length;
const closedCount = anunturi.length - openCount;
---

<AchizitiiLayout
  title={`${proiect.titlu || proiect.beneficiar_name || `Proiect SMIS ${proiect.smis_code}`} — Proiect EU · vreaudigital.ro`}
  description={`${proiect.beneficiar_name} (proiect SMIS ${proiect.smis_code || '?'}): ${proiect.program_op_text || proiect.program_op_cod || '?'}, ${anunturi.length} anunțuri, ${fmtRon(proiect.buget_total)} RON.`}
>
  <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> ·
      Proiect #{proiect.id}
    </div>

    <!-- Header -->
    <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">
          <div class="text-sm text-meta mb-1">
            {proiect.smis_code && <span class="font-mono">SMIS {proiect.smis_code}</span>}
            {proiect.data_contract && <span class="ml-3">Contract: {dateFmt(proiect.data_contract)}</span>}
          </div>
          <h1 class="profile-name">{proiect.titlu || proiect.beneficiar_name || `Proiect #${proiect.id}`}</h1>
          <div class="profile-subline">
            {proiect.beneficiar_name && (
              <span class="badge">
                🏢 {proiect.beneficiar_cui
                  ? <a href={`/firma/${proiect.beneficiar_cui}`} class="hover:underline">{proiect.beneficiar_name}</a>
                  : proiect.beneficiar_name
                }
              </span>
            )}
            {proiect.program_op_cod && <span class="badge badge-stamp font-mono">{proiect.program_op_cod}</span>}
            {proiect.beneficiar_judet && <span class="badge">📍 {proiect.beneficiar_judet}</span>}
            <span class="badge">{anunturi.length} anunț{anunturi.length === 1 ? '' : 'uri'}</span>
            {openCount > 0 && <span class="badge" data-tone="ok">🟢 {openCount} în ofertare</span>}
          </div>
          <div class="profile-dossier">
            Proiect cu finanțare europeană derulat de un beneficiar <strong>privat</strong>
            {proiect.beneficiar_name && proiect.beneficiar_cui && <> (<a href={`/firma/${proiect.beneficiar_cui}`} class="text-stamp font-semibold hover:underline">{proiect.beneficiar_name}</a>)</>}.
            {proiect.program_op_text && <> Program: <strong>{proiect.program_op_text}</strong>.</>}
            Pentru implementare beneficiarul a publicat <strong>{anunturi.length}</strong> anunț{anunturi.length === 1 ? '' : 'uri'} de achiziție
            cu un buget cumulat de <strong>{fmtRon(proiect.buget_total)} RON</strong>.
            Aceste proceduri NU intră în SEAP, dar trebuie publicate transparent conform Manualului Beneficiarului.
          </div>
        </div>
      </div>
    </div>

    <!-- KPI strip -->
    <div class="profile-kpi-strip">
      <div class="profile-kpi">
        <div class="profile-kpi-label">Buget total achiziții</div>
        <div class="profile-kpi-value">{fmtRon(proiect.buget_total)} <span style="font-size:12px;color:var(--meta);font-weight:500;">RON</span></div>
        <div class="profile-kpi-hint">{anunturi.length} anunț{anunturi.length === 1 ? '' : 'uri'}</div>
      </div>
      <div class="profile-kpi">
        <div class="profile-kpi-label">Data contract</div>
        <div class="profile-kpi-value" style="font-size:18px;">{dateFmt(proiect.data_contract)}</div>
      </div>
      <div class="profile-kpi">
        <div class="profile-kpi-label">Prima procedură</div>
        <div class="profile-kpi-value" style="font-size:18px;">{dateFmt(proiect.data_publicare_min)}</div>
      </div>
      <div class="profile-kpi">
        <div class="profile-kpi-label">Ultima procedură</div>
        <div class="profile-kpi-value" style="font-size:18px;">{dateFmt(proiect.data_publicare_max)}</div>
      </div>
      <div class="profile-kpi" data-tone={openCount > 0 ? 'ok' : 'state'}>
        <div class="profile-kpi-label">Status</div>
        <div class="profile-kpi-value" style="font-size:18px;">
          {openCount > 0 ? `${openCount} active` : 'închis'}
        </div>
        <div class="profile-kpi-hint">{closedCount} închise</div>
      </div>
    </div>

    <!-- Project metadata -->
    <div class="profile-section">
      <h2 class="profile-section-title">📋 Cadru program EU</h2>
      <div class="profile-firm-meta">
        {proiect.smis_code && (
          <div class="profile-firm-meta-item">
            <div class="profile-firm-meta-label">Cod SMIS</div>
            <div class="profile-firm-meta-value font-mono">{proiect.smis_code}</div>
          </div>
        )}
        {proiect.program_op_cod && (
          <div class="profile-firm-meta-item" style="grid-column: span 3;">
            <div class="profile-firm-meta-label">Program operațional</div>
            <div class="profile-firm-meta-value">
              <span class="badge badge-stamp font-mono">{proiect.program_op_cod}</span>
              {proiect.program_op_text && <span style="margin-left:6px;">{proiect.program_op_text}</span>}
            </div>
          </div>
        )}
        {proiect.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">{proiect.axa_cod}</span>
              {proiect.axa_text && <span style="margin-left:6px;color:var(--meta);">{proiect.axa_text}</span>}
            </div>
          </div>
        )}
        {proiect.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">{proiect.domeniul_cod}</span>
              {proiect.domeniul_text && <span style="margin-left:6px;color:var(--meta);">{proiect.domeniul_text}</span>}
            </div>
          </div>
        )}
        {proiect.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">{proiect.operatiune_cod}</span>
              {proiect.operatiune_text && <span style="margin-left:6px;color:var(--meta);">{proiect.operatiune_text}</span>}
            </div>
          </div>
        )}
      </div>
    </div>

    <!-- Beneficiar firma details (if matched) -->
    {firmDetails && proiect.beneficiar_cui && (
      <div class="profile-section">
        <h2 class="profile-section-title">🏢 Beneficiar — firmă matched în registru</h2>
        <div class="profile-firm-meta">
          <div class="profile-firm-meta-item">
            <div class="profile-firm-meta-label">CUI</div>
            <div class="profile-firm-meta-value font-mono">{proiect.beneficiar_cui}</div>
          </div>
          {firmDetails.forma_juridica && (
            <div class="profile-firm-meta-item">
              <div class="profile-firm-meta-label">Formă juridică</div>
              <div class="profile-firm-meta-value">{firmDetails.forma_juridica}</div>
            </div>
          )}
          {firmDetails.cod_inmatriculare && (
            <div class="profile-firm-meta-item">
              <div class="profile-firm-meta-label">Cod ONRC</div>
              <div class="profile-firm-meta-value font-mono">{firmDetails.cod_inmatriculare}</div>
            </div>
          )}
          {firmDetails.adr_full && (
            <div class="profile-firm-meta-item" style="grid-column: span 4;">
              <div class="profile-firm-meta-label">Adresă</div>
              <div class="profile-firm-meta-value">{firmDetails.adr_full}</div>
            </div>
          )}
        </div>
        <div style="margin-top: 14px;">
          <a href={`/firma/${proiect.beneficiar_cui}`} class="btn-brutal">
            Profil complet firmă →
          </a>
        </div>
      </div>
    )}

    <!-- All anunturi list -->
    <div class="profile-section">
      <h2 class="profile-section-title">
        📦 Toate anunțurile proiectului
        <span class="profile-section-title-meta">{anunturi.length}</span>
      </h2>
      <div>
        {anunturi.map((a: any) => {
          const isOpen = (a.procedura_status || '').toLowerCase().includes('curs');
          return (
            <a href={`/beneficiar-privat/${a.id}`} class="profile-contract">
              <div class="profile-contract-meta">
                <span>📄</span>
                <span>{a.tip_contract || '?'}</span>
                <span>·</span>
                <span>{dateFmt(a.data_publicare)}</span>
                <span class={`badge ${isOpen ? '' : 'badge-stamp'}`} style={isOpen ? 'background:#22c55e22;border-color:#22c55e;color:#15803d;' : ''}>
                  {isOpen ? '🟢 ofertare' : '⚪ închisă'}
                </span>
              </div>
              <div class="profile-contract-title">#{a.id} · {a.titlu || a.beneficiar_name || '?'}</div>
              <div class="profile-contract-bottom">
                <span class="profile-contract-cp">🏢 {a.beneficiar_name}</span>
                <span class="profile-contract-value">{fmtRon(Number(a.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/proiecte/details/${proiect.proiect_type}/${proiect.id}/`} target="_blank" rel="noopener" class="profile-external-link">Proiect SMIS — pagina originală ↗</a>
        {proiect.smis_code && (
          <a href={`https://www.fonduri-ue.ro/cautare?cmd=Cautare&search=${proiect.smis_code}`} target="_blank" rel="noopener" class="profile-external-link">Caută SMIS pe fonduri-ue.ro ↗</a>
        )}
        {proiect.beneficiar_cui && (
          <a href={`/firma/${proiect.beneficiar_cui}`} class="profile-external-link">Profil firmă în registru →</a>
        )}
      </div>
    </div>

  </main>
</AchizitiiLayout>
