{% extends 'base.html' %}
{% set active = 'categories' %}
{% block page_title %}Categorie{% endblock %}
{% block header_title %}Categorie{% endblock %}

{% block topbar_extra %}
<button class="btn btn-ghost" onclick="openCatModal()">+ Nuova categoria</button>
{% endblock %}

{% block content %}
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">

  <div>
    <div class="section-hdr" style="margin-bottom:10px">
      <h5 style="color:var(--expense)">↓ Uscite <span id="cntOut" style="font-size:.8rem;color:var(--muted);font-weight:400"></span></h5>
    </div>
    <div id="catGridOut" style="display:flex;flex-direction:column;gap:8px"></div>
  </div>

  <div>
    <div class="section-hdr" style="margin-bottom:10px">
      <h5 style="color:var(--income)">↑ Entrate <span id="cntIn" style="font-size:.8rem;color:var(--muted);font-weight:400"></span></h5>
    </div>
    <div id="catGridIn" style="display:flex;flex-direction:column;gap:8px"></div>
  </div>

</div>

<!-- Category modal -->
<div class="modal-overlay" id="catModal" onclick="if(event.target===this)closeCatModal()">
  <div class="modal-box" style="max-width:440px">
    <button class="modal-close" onclick="closeCatModal()">×</button>
    <h5 id="catModalTitle">Nuova Categoria</h5>

    <div class="form-group">
      <label class="form-label">Nome *</label>
      <input type="text" class="form-control" id="catName" placeholder="Es. Palestra, Animali…">
    </div>
    <div class="form-group">
      <label class="form-label">Tipo *</label>
      <select class="form-select" id="catType">
        <option value="uscita">↓ Uscita</option>
        <option value="entrata">↑ Entrata</option>
      </select>
    </div>
    <div class="form-row form-row-2">
      <div class="form-group">
        <label class="form-label">Colore</label>
        <input type="color" class="form-control" id="catColor" value="#6366f1" style="height:40px;padding:4px 6px;cursor:pointer">
      </div>
      <div class="form-group">
        <label class="form-label">Emoji</label>
        <input type="text" class="form-control" id="catIcon" placeholder="💰" maxlength="4">
      </div>
    </div>
    <div class="form-group">
      <label class="form-label">Budget mensile (€) <span style="font-weight:400;color:var(--muted)">— solo per uscite</span></label>
      <input type="number" class="form-control" id="catBudget" min="0" step="10" placeholder="0 = nessun budget">
    </div>

    <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:6px">
      <button class="btn btn-ghost" onclick="closeCatModal()">Annulla</button>
      <button class="btn btn-primary" onclick="saveCat()">Salva</button>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let catEditId = null;

async function loadCats() {
  await loadCategories();
  // Get current month spending
  const now = new Date();
  const d   = await fetch(`/api/budget?year=${now.getFullYear()}&month=${now.getMonth()+1}`).then(r=>r.json());
  const spentMap = {};
  d.forEach(r => spentMap[r.id] = r.spent);
  renderCats(spentMap);
}

function renderCats(spentMap={}) {
  const gridOut = document.getElementById('catGridOut');
  const gridIn  = document.getElementById('catGridIn');
  gridOut.innerHTML = ''; gridIn.innerHTML = '';

  const out = categories.filter(c=>c.type==='uscita');
  const inp = categories.filter(c=>c.type==='entrata');
  document.getElementById('cntOut').textContent = `(${out.length})`;
  document.getElementById('cntIn').textContent  = `(${inp.length})`;

  [...out, ...inp].forEach(cat => {
    const spent  = spentMap[cat.id] || 0;
    const budget = cat.budget || 0;
    const pct    = budget > 0 ? Math.min((spent/budget)*100, 100) : 0;
    const over   = budget > 0 && spent > budget;
    const warn   = pct >= 70 && pct < 90;
    const danger = pct >= 90;
    const barColor = over ? 'var(--expense)' : (warn||danger) ? '#f59e0b' : cat.color;

    const card = document.createElement('div');
    card.className = 'cat-card';
    card.innerHTML = `
      <div class="cat-card-header">
        <div class="cat-card-icon" style="background:${cat.color}22;font-size:1.15rem">${cat.icon}</div>
        <div style="flex:1;min-width:0">
          <div style="font-weight:700;font-size:.9rem">${cat.name}</div>
          <div style="font-size:.72rem;color:${cat.type==='entrata'?'var(--income)':'var(--expense)'}">
            ${cat.type==='entrata'?'↑ Entrata':'↓ Uscita'}
          </div>
        </div>
        <div style="text-align:right;flex-shrink:0">
          ${cat.type==='uscita' && budget>0 ? `
            <div style="font-size:.8rem;font-weight:700;color:${over?'var(--expense)':'var(--text)'}">
              ${fmt(spent)} <span style="color:var(--muted);font-weight:400">/ ${fmt(budget)}</span>
            </div>` : (cat.type==='uscita' ? `<span style="font-size:.72rem;color:var(--muted)">Nessun budget</span>` : '')}
          <div style="display:flex;gap:4px;justify-content:flex-end;margin-top:4px">
            <button class="btn-icon" onclick="editCat(${cat.id})" title="Modifica">✏️</button>
            <button class="btn-icon" onclick="deleteCat(${cat.id})" title="Elimina">🗑️</button>
          </div>
        </div>
      </div>
      ${cat.type==='uscita' && budget>0 ? `
        <div>
          <div class="progress-outer"><div class="progress-inner" style="width:${pct}%;background:${barColor}"></div></div>
          <div style="font-size:.7rem;color:var(--muted);margin-top:2px">
            ${over?`🔴 Sforato di ${fmt(spent-budget)}`:(warn||danger)?`🟡 ${Math.round(pct)}% usato`:`🟢 ${Math.round(pct)}% usato`}
          </div>
        </div>` : ''}`;

    if (cat.type==='uscita') gridOut.appendChild(card);
    else                     gridIn.appendChild(card);
  });
}

// ── Modal ─────────────────────────────────────────────────────────────────────
function openCatModal(cat=null) {
  catEditId = cat ? cat.id : null;
  document.getElementById('catModalTitle').textContent = cat ? 'Modifica Categoria' : 'Nuova Categoria';
  document.getElementById('catName').value   = cat ? cat.name        : '';
  document.getElementById('catType').value   = cat ? cat.type        : 'uscita';
  document.getElementById('catColor').value  = cat ? cat.color       : '#6366f1';
  document.getElementById('catIcon').value   = cat ? (cat.icon||'')  : '';
  document.getElementById('catBudget').value = cat ? (cat.budget||0) : '';
  document.getElementById('catModal').classList.add('open');
  document.getElementById('catName').focus();
}
function closeCatModal() { document.getElementById('catModal').classList.remove('open'); }

async function saveCat() {
  const name = document.getElementById('catName').value.trim();
  if (!name) { showToast('Inserisci un nome','error'); return; }
  const payload = {
    name, type:  document.getElementById('catType').value,
    color: document.getElementById('catColor').value,
    icon:  document.getElementById('catIcon').value.trim() || '💰',
    budget: parseFloat(document.getElementById('catBudget').value) || 0
  };
  const url    = catEditId ? `/api/categories/${catEditId}` : '/api/categories';
  const method = catEditId ? 'PUT' : 'POST';
  const r = await fetch(url,{method,headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
  const j = await r.json();
  if (j.success || j.id) {
    showToast(catEditId?'Categoria aggiornata':'Categoria creata','success');
    closeCatModal(); loadCats();
  } else {
    showToast(j.error||'Errore','error');
  }
}

function editCat(id) { const c=categories.find(x=>x.id===id); if(c) openCatModal(c); }
function deleteCat(id) {
  openConfirm(async()=>{
    const r=await fetch(`/api/categories/${id}`,{method:'DELETE'});
    const j=await r.json();
    if(j.success){ showToast('Categoria eliminata'); loadCats(); }
    else showToast(j.error||'Errore','error');
  });
}

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