{% extends 'base.html' %}
{% set active = 'dashboard' %}
{% block page_title %}Dashboard{% endblock %}
{% block header_title %}Dashboard{% endblock %}

{% block topbar_extra %}
<div class="month-nav">
  <button onclick="prevMonth()">‹</button>
  <span id="monthLabel"></span>
  <button onclick="nextMonth()">›</button>
</div>
{% endblock %}

{% block content %}
<!-- Pending recurring notification -->
<div class="notif-banner" id="pendingBanner" style="display:none">
  <span>🔁</span>
  <span id="pendingText"></span>
  <button class="btn btn-sm" style="background:#fbbf24;color:#fff;margin-left:auto" onclick="generateRecurring()">Genera ora</button>
  <button class="btn-icon" onclick="this.parentElement.style.display='none'">×</button>
</div>

<!-- Stat cards -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:18px">
  <div class="stat-card">
    <div class="stat-icon" style="background:#d1fae5">💚</div>
    <div style="flex:1">
      <div class="stat-label">Entrate</div>
      <div class="stat-value amt-in" id="s-entrate">—</div>
      <div class="stat-sub"><span id="chg-entrate"></span></div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:#fee2e2">❤️</div>
    <div style="flex:1">
      <div class="stat-label">Uscite</div>
      <div class="stat-value amt-out" id="s-uscite">—</div>
      <div class="stat-sub"><span id="chg-uscite"></span></div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:#e0e7ff">💼</div>
    <div style="flex:1">
      <div class="stat-label">Saldo mese</div>
      <div class="stat-value" id="s-saldo">—</div>
      <div class="stat-sub" id="s-saldo-sub"></div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:#fef3c7">⭐</div>
    <div style="flex:1">
      <div class="stat-label">Risparmio %</div>
      <div class="stat-value" id="s-saving">—</div>
      <div class="stat-sub" id="s-proj-sub" style="font-size:.72rem"></div>
    </div>
  </div>
</div>

<!-- Charts row -->
<div style="display:grid;grid-template-columns:1.6fr 1fr;gap:14px;margin-bottom:18px">
  <div class="chart-card">
    <h6>Ultimi 6 mesi — Entrate vs Uscite</h6>
    <canvas id="trendChart" height="195"></canvas>
  </div>
  <div class="chart-card">
    <h6>Uscite per categoria</h6>
    <canvas id="catChart" height="195"></canvas>
    <div id="catChartEmpty" style="display:none;text-align:center;color:var(--muted);padding:40px 0;font-size:.875rem">Nessuna uscita questo mese</div>
  </div>
</div>

<!-- Top spese + Recent row -->
<div style="display:grid;grid-template-columns:1fr 1.6fr;gap:14px">
  <!-- Top 5 spese -->
  <div class="chart-card" style="padding:0;overflow:hidden">
    <div style="padding:16px 18px 8px">
      <h6 style="margin-bottom:0">Top 5 spese del mese</h6>
    </div>
    <div id="topSpeseBody"></div>
    <div class="empty-state" id="topSpeseEmpty" style="display:none;padding:28px 16px">
      <div class="empty-icon" style="font-size:1.8rem">📭</div>
      <p style="font-size:.82rem">Nessuna uscita</p>
    </div>
  </div>

  <!-- Recent transactions -->
  <div class="chart-card" style="padding:0;overflow:hidden">
    <div style="padding:16px 18px 8px;display:flex;align-items:center;justify-content:space-between">
      <h6 style="margin-bottom:0">Ultime transazioni</h6>
      <a href="/transactions" style="font-size:.78rem;color:var(--primary);text-decoration:none">Vedi tutte →</a>
    </div>
    <table class="data-table" id="recentTable">
      <thead><tr>
        <th>Data</th><th>Descrizione</th><th>Cat.</th><th style="text-align:right">Importo</th>
      </tr></thead>
      <tbody id="recentBody"></tbody>
    </table>
    <div class="empty-state" id="recentEmpty" style="display:none;padding:28px 16px">
      <div class="empty-icon" style="font-size:1.8rem">📭</div>
      <p style="font-size:.82rem">Nessuna transazione registrata</p>
      <button class="btn btn-primary btn-sm" style="margin-top:10px" onclick="openTransactionModal()">Aggiungi</button>
    </div>
  </div>
</div>
{% endblock %}

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

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

function renderChg(val, invertColor=false) {
  if (val === null || val === undefined) return '';
  const up = val >= 0;
  const cls = invertColor ? (up ? 'down' : 'up') : (up ? 'up' : 'down');
  return `<span class="stat-chg ${cls}">${up?'↑':'↓'} ${Math.abs(val)}%</span> vs mese prec.`;
}

async function loadDashboard() {
  updateMonthLabel();
  const d = await fetch(`/api/dashboard?year=${curYear}&month=${curMonth}`).then(r=>r.json());

  document.getElementById('s-entrate').textContent = fmt(d.entrate);
  document.getElementById('s-uscite').textContent  = fmt(d.uscite);
  document.getElementById('chg-entrate').innerHTML = renderChg(d.chg_entrate);
  document.getElementById('chg-uscite').innerHTML  = renderChg(d.chg_uscite, true);

  const saldo = d.saldo;
  const sEl = document.getElementById('s-saldo');
  sEl.textContent = fmt(saldo);
  sEl.className   = 'stat-value ' + (saldo>=0?'amt-in':'amt-out');
  document.getElementById('s-saldo-sub').textContent = saldo>=0 ? '👍 sei in attivo' : '⚠️ speso più delle entrate';

  const pct = d.entrate>0 ? Math.round((saldo/d.entrate)*100) : 0;
  const savEl = document.getElementById('s-saving');
  savEl.textContent = pct + '%';
  savEl.className   = 'stat-value ' + (pct>=0?'amt-in':'amt-out');

  // Projection
  const projSub = document.getElementById('s-proj-sub');
  if (d.projection) {
    const p = d.projection;
    projSub.innerHTML = `📅 ${p.elapsed}/${p.total} gg • proiezione uscite: <strong>${fmt(p.projected)}</strong>`;
  } else {
    projSub.textContent = '% delle entrate risparmiate';
  }

  // Pending recurring
  const banner = document.getElementById('pendingBanner');
  if (d.pending_recurring && d.pending_recurring.length > 0) {
    const n = d.pending_recurring.length;
    document.getElementById('pendingText').textContent =
      `${n} transazion${n>1?'i':'e'} ricorrente${n>1?'':'o'} da generare: ${d.pending_recurring.map(r=>r.description).join(', ')}`;
    banner.style.display = 'flex';
  } else {
    banner.style.display = 'none';
  }

  // Trend chart
  if (trendChart) trendChart.destroy();
  trendChart = new Chart(document.getElementById('trendChart'), {
    type: 'bar',
    data: {
      labels: d.monthly_trend.map(x=>x.label),
      datasets: [
        {label:'Entrate', data:d.monthly_trend.map(x=>x.entrate), backgroundColor:'rgba(16,185,129,.75)', borderRadius:6},
        {label:'Uscite',  data:d.monthly_trend.map(x=>x.uscite),  backgroundColor:'rgba(239,68,68,.75)',  borderRadius:6}
      ]
    },
    options: {
      responsive:true,
      plugins:{legend:{position:'top'},tooltip:{callbacks:{label:ctx=>` ${fmt(ctx.raw)}`}}},
      scales:{y:{ticks:{callback:v=>'€'+v.toLocaleString('it-IT')},grid:{color:'#f1f5f9'}},x:{grid:{display:false}}}
    }
  });

  // Category pie
  const catCanvas = document.getElementById('catChart');
  const catEmpty  = document.getElementById('catChartEmpty');
  if (catChart) catChart.destroy();
  if (d.by_category.length > 0) {
    catCanvas.style.display = ''; catEmpty.style.display = 'none';
    catChart = new Chart(catCanvas, {
      type: 'doughnut',
      data: {
        labels: d.by_category.map(x=>x.icon+' '+x.name),
        datasets:[{data:d.by_category.map(x=>x.total), backgroundColor:d.by_category.map(x=>x.color), borderWidth:2, borderColor:'#fff'}]
      },
      options: {
        cutout:'60%',
        plugins:{legend:{position:'right',labels:{font:{size:11},boxWidth:10}},tooltip:{callbacks:{label:ctx=>` ${fmt(ctx.raw)}`}}}
      }
    });
  } else {
    catCanvas.style.display = 'none'; catEmpty.style.display = 'block';
  }

  // Top 5 spese
  const topBody  = document.getElementById('topSpeseBody');
  const topEmpty = document.getElementById('topSpeseEmpty');
  topBody.innerHTML = '';
  if (d.top_spese.length > 0) {
    topEmpty.style.display = 'none';
    d.top_spese.forEach((tx,i) => {
      const div = document.createElement('div');
      div.style.cssText = 'display:flex;align-items:center;gap:10px;padding:10px 18px;border-bottom:1px solid var(--border)';
      if (i === d.top_spese.length-1) div.style.borderBottom = 'none';
      div.innerHTML = `
        <div style="width:22px;height:22px;border-radius:50%;background:${tx.color||'#64748b'}22;display:flex;align-items:center;justify-content:center;font-size:.85rem;flex-shrink:0">${tx.icon||'📦'}</div>
        <div style="flex:1;min-width:0">
          <div style="font-weight:600;font-size:.85rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${tx.description}</div>
          <div style="font-size:.72rem;color:var(--muted)">${tx.cat_name||'—'} · ${fmtDate(tx.date)}</div>
        </div>
        <div class="amt-out" style="font-size:.9rem;font-weight:800;flex-shrink:0">${fmt(tx.amount)}</div>`;
      topBody.appendChild(div);
    });
  } else {
    topEmpty.style.display = 'flex';
  }

  // Recent transactions
  const tbody = document.getElementById('recentBody');
  const empty = document.getElementById('recentEmpty');
  tbody.innerHTML = '';
  if (d.recent.length === 0) {
    document.getElementById('recentTable').style.display = 'none';
    empty.style.display = 'flex'; empty.style.flexDirection = 'column'; empty.style.alignItems = 'center';
  } else {
    document.getElementById('recentTable').style.display = '';
    empty.style.display = 'none';
    d.recent.forEach(tx => {
      const tr = document.createElement('tr');
      const catHtml = tx.cat_name
        ? `<span class="cat-dot" style="background:${tx.color}"></span>${tx.cat_name}`
        : '<span style="color:var(--muted)">—</span>';
      tr.innerHTML = `
        <td style="color:var(--muted);white-space:nowrap">${fmtDate(tx.date)}</td>
        <td style="font-weight:500;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${tx.description}</td>
        <td style="font-size:.78rem">${catHtml}</td>
        <td style="text-align:right" class="${tx.type==='entrata'?'amt-in':'amt-out'}">${tx.type==='entrata'?'+':'−'}${fmt(tx.amount)}</td>`;
      tbody.appendChild(tr);
    });
  }
}

async function generateRecurring() {
  const r = await fetch('/api/recurring/generate',{method:'POST'});
  const j = await r.json();
  showToast(`${j.count} transazion${j.count!==1?'i':'e'} generate`,'success');
  loadDashboard();
}

function onTxSaved() { loadDashboard(); }
loadDashboard();
</script>
{% endblock %}
