{% extends 'base.html' %}
{% set active = 'budget' %}
{% block page_title %}Budget{% endblock %}
{% block header_title %}Gestione Budget{% endblock %}

{% block topbar_extra %}
<div class="month-nav">
  <button onclick="prevMonth()">‹</button>
  <span id="monthLabel"></span>
  <button onclick="nextMonth()">›</button>
</div>
<a href="/categories" class="btn btn-ghost btn-sm">⚙️ Modifica budget</a>
{% endblock %}

{% block content %}
<!-- Summary cards -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px">
  <div class="stat-card">
    <div class="stat-icon" style="background:#d1fae5;font-size:1.3rem">🟢</div>
    <div><div class="stat-label">Categorie OK</div><div class="stat-value" id="bOk" style="color:var(--income)">—</div></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:#fef3c7;font-size:1.3rem">🟡</div>
    <div><div class="stat-label">In avviso</div><div class="stat-value" id="bWarn" style="color:#d97706">—</div></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:#fee2e2;font-size:1.3rem">🔴</div>
    <div><div class="stat-label">Sforato</div><div class="stat-value" id="bOver" style="color:var(--expense)">—</div></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:#e0e7ff">💶</div>
    <div><div class="stat-label">Budget totale</div><div class="stat-value" id="bTotal">—</div></div>
  </div>
</div>

<!-- Legend -->
<div style="display:flex;gap:16px;margin-bottom:14px;font-size:.78rem;color:var(--muted)">
  <span>🟢 &lt;70%</span>
  <span>🟡 70–90%</span>
  <span>🔴 &gt;90% o sforato</span>
  <span style="margin-left:auto">Le categorie senza budget non sono incluse nelle statistiche</span>
</div>

<!-- Budget grid -->
<div id="budgetGrid" style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px"></div>
<div class="empty-state" id="budgetEmpty" style="display:none">
  <div class="empty-icon">🎯</div>
  <p>Nessun budget configurato</p>
  <a href="/categories" class="btn btn-primary btn-sm" style="margin-top:12px">Configura i budget →</a>
</div>
{% endblock %}

{% block scripts %}
<script>
let curYear=new Date().getFullYear(), curMonth=new Date().getMonth()+1;
const MONTHS=['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];

function updateLabel() {
  document.getElementById('monthLabel').textContent=`${MONTHS[curMonth-1]} ${curYear}`;
}
function prevMonth(){ curMonth--; if(curMonth<1){curMonth=12;curYear--;} loadBudget(); }
function nextMonth(){ curMonth++; if(curMonth>12){curMonth=1;curYear++;} loadBudget(); }

async function loadBudget() {
  updateLabel();
  const rows = await fetch(`/api/budget?year=${curYear}&month=${curMonth}`).then(r=>r.json());

  const withBudget = rows.filter(r=>r.budget>0);
  const grid=document.getElementById('budgetGrid'), empty=document.getElementById('budgetEmpty');
  grid.innerHTML='';

  if (!withBudget.length) { empty.style.display='block'; grid.style.display='none'; return; }
  empty.style.display='none'; grid.style.display='';

  let cOk=0, cWarn=0, cOver=0, budgetTotal=0;
  withBudget.forEach(r=>budgetTotal+=r.budget);

  withBudget.forEach(row => {
    const pct    = row.budget>0 ? (row.spent/row.budget)*100 : 0;
    const over   = row.spent > row.budget;
    const warn   = pct>=70 && pct<90;
    const danger = pct>=90;
    if (over||danger) cOver++; else if (warn) cWarn++; else cOk++;

    let tlIcon='🟢', tlCls='tl-ok-bg';
    if (over)   { tlIcon='🔴'; tlCls='tl-over-bg'; }
    else if (danger||warn) { tlIcon=warn?'🟡':'🔴'; tlCls=warn?'tl-warn-bg':'tl-over-bg'; }

    const barColor = over ? 'var(--expense)' : warn||danger ? '#f59e0b' : row.color;
    const remaining = row.budget - row.spent;

    const card=document.createElement('div');
    card.className='cat-card';
    card.innerHTML=`
      <div class="cat-card-header">
        <div class="cat-card-icon" style="background:${row.color}22">${row.icon}</div>
        <div style="flex:1">
          <div style="font-weight:700;font-size:.95rem">${row.name}</div>
          <div style="font-size:.75rem;color:var(--muted);margin-top:1px">
            Speso <strong>${fmt(row.spent)}</strong> di ${fmt(row.budget)}
          </div>
        </div>
        <span class="badge-pill ${tlCls}" style="font-size:.75rem">${tlIcon} ${Math.round(pct)}%</span>
      </div>
      <div class="progress-outer" style="margin:8px 0 6px">
        <div class="progress-inner" style="width:${Math.min(pct,100)}%;background:${barColor}"></div>
      </div>
      <div style="display:flex;justify-content:space-between;font-size:.75rem">
        <span style="color:var(--muted)">Usato: ${fmt(row.spent)}</span>
        <span style="color:${over?'var(--expense)':'var(--income)';font-weight:600}">${over?'Sforato: +'+fmt(-remaining):'Rimane: '+fmt(remaining)}</span>
      </div>
      ${row.spent===0?'<div style="font-size:.72rem;color:var(--muted);margin-top:6px">✨ Nessuna spesa questo mese</div>':''}`;
    grid.appendChild(card);
  });

  document.getElementById('bOk').textContent    = cOk;
  document.getElementById('bWarn').textContent  = cWarn;
  document.getElementById('bOver').textContent  = cOver;
  document.getElementById('bTotal').textContent = fmt(budgetTotal);

  // Also show categories without budget as a muted list
  const noBudget = rows.filter(r=>!r.budget);
  if (noBudget.length) {
    const info=document.createElement('div');
    info.style.cssText='margin-top:16px;color:var(--muted);font-size:.78rem';
    info.innerHTML=`<strong>Categorie senza budget:</strong> ${noBudget.map(r=>r.icon+' '+r.name).join(', ')} — <a href="/categories" style="color:var(--primary)">imposta budget →</a>`;
    grid.parentElement.appendChild(info);
  }
}

loadBudget();
</script>
{% endblock %}
