<!DOCTYPE html>
<html lang="it">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>{% block page_title %}{% endblock %} — ContabilitàFamily</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="/static/css/style.css">
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
</head>
<body>

<!-- ── Sidebar ──────────────────────────────────── -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">💰 ContabilitàFamily<small>Gestione economica famigliare</small></div>
  <ul class="sidebar-nav">
    <li><span class="sidebar-section">Panoramica</span></li>
    <li><a href="/"           {% if active=='dashboard'    %}class="active"{% endif %}><span class="nav-icon">📊</span> Dashboard</a></li>
    <li><a href="/calendar"   {% if active=='calendar'     %}class="active"{% endif %}><span class="nav-icon">📅</span> Calendario</a></li>
    <li><span class="sidebar-section">Gestione</span></li>
    <li><a href="/transactions"{% if active=='transactions' %}class="active"{% endif %}><span class="nav-icon">💳</span> Transazioni</a></li>
    <li><a href="/recurring"  {% if active=='recurring'    %}class="active"{% endif %}><span class="nav-icon">🔁</span> Ricorrenti</a></li>
    <li><a href="/categories" {% if active=='categories'   %}class="active"{% endif %}><span class="nav-icon">🏷️</span> Categorie</a></li>
    <li><span class="sidebar-section">Pianificazione</span></li>
    <li><a href="/budget"     {% if active=='budget'       %}class="active"{% endif %}><span class="nav-icon">🎯</span> Budget</a></li>
    <li><a href="/goals"      {% if active=='goals'        %}class="active"{% endif %}><span class="nav-icon">⭐</span> Obiettivi</a></li>
    <li><a href="/reports"    {% if active=='reports'      %}class="active"{% endif %}><span class="nav-icon">📈</span> Report</a></li>
    <li><span class="sidebar-section">Sistema</span></li>
    <li><a href="/impostazioni" {% if active=='impostazioni' %}class="active"{% endif %}><span class="nav-icon">⚙️</span> Impostazioni</a></li>
  </ul>
  <div class="sidebar-footer"><small id="sidebar-date"></small></div>
</nav>

<!-- ── Main ─────────────────────────────────────── -->
<div class="main">
  <header class="topbar">
    <h1>{% block header_title %}{% endblock %}</h1>
    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
      {% block topbar_extra %}{% endblock %}
      <button class="btn btn-primary" onclick="openTransactionModal()">+ Aggiungi</button>
    </div>
  </header>
  <div class="content">{% block content %}{% endblock %}</div>
</div>

<!-- ── Toast ─────────────────────────────────────── -->
<div id="toast"></div>

<!-- ── Transaction Modal ─────────────────────────── -->
<div class="modal-overlay" id="txModal" onclick="if(event.target===this)closeTxModal()">
  <div class="modal-box">
    <button class="modal-close" onclick="closeTxModal()">×</button>
    <h5 id="txModalTitle">Nuova Transazione</h5>

    <div class="type-toggle">
      <button class="type-btn active-in" id="btnEntrata" onclick="setTxType('entrata')">↑ Entrata</button>
      <button class="type-btn"           id="btnUscita"  onclick="setTxType('uscita')">↓ Uscita</button>
    </div>

    <div class="form-row form-row-2">
      <div class="form-group">
        <label class="form-label">Data *</label>
        <input type="date" class="form-control" id="txDate">
      </div>
      <div class="form-group">
        <label class="form-label">Importo (€) *</label>
        <input type="number" class="form-control" id="txAmount" min="0.01" step="0.01" placeholder="0,00">
      </div>
    </div>

    <div class="form-group">
      <label class="form-label">Descrizione *</label>
      <div style="display:flex;gap:6px">
        <input type="text" class="form-control" id="txDescription" placeholder="Es. Spesa al supermercato…" style="flex:1">
        <button class="btn btn-outline btn-sm" id="voiceBtn" onclick="startVoice()" title="Dettatura vocale" style="padding:0 10px;font-size:1.1rem">🎤</button>
      </div>
    </div>

    <div class="form-row form-row-2">
      <div class="form-group">
        <label class="form-label">Categoria</label>
        <select class="form-select" id="txCategory"><option value="">— Nessuna —</option></select>
      </div>
      <div class="form-group">
        <label class="form-label">Note</label>
        <input type="text" class="form-control" id="txNotes" placeholder="Opzionale…">
      </div>
    </div>

    <!-- Tags -->
    <div class="form-group">
      <label class="form-label">Tag <span style="font-weight:400;color:var(--muted)">(premi Invio o virgola per aggiungere)</span></label>
      <div class="tag-wrap">
        <input type="text" class="form-control" id="txTagInput"
               placeholder="Es. vacanza, auto…"
               oninput="showTagSuggestions(this.value)"
               onkeydown="tagKeydown(event)">
        <div class="tag-suggestions" id="tagSuggestions"></div>
      </div>
      <div id="selectedTagsWrap" style="display:flex;flex-wrap:wrap;gap:5px;margin-top:7px"></div>
    </div>

    <!-- Receipt -->
    <div class="form-group">
      <label class="form-label">Scontrino / Allegato</label>
      <input type="file" class="form-control" id="txReceipt" accept=".jpg,.jpeg,.png,.gif,.pdf,.webp" style="padding:5px">
      <div id="existingReceiptWrap" style="display:none;margin-top:8px"></div>
    </div>

    <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:6px">
      <button class="btn btn-ghost" onclick="closeTxModal()">Annulla</button>
      <button class="btn btn-primary" id="txSaveBtn" onclick="saveTx()">Salva</button>
    </div>
  </div>
</div>

<!-- ── Confirm Modal ──────────────────────────────── -->
<div class="modal-overlay" id="confirmModal" onclick="if(event.target===this)closeConfirm()">
  <div class="modal-box" style="max-width:340px;text-align:center">
    <div style="font-size:2.4rem;margin-bottom:10px">🗑️</div>
    <h5 style="margin-bottom:6px">Eliminare questa voce?</h5>
    <p style="color:var(--muted);font-size:.875rem;margin-bottom:18px">L'operazione non può essere annullata.</p>
    <div style="display:flex;gap:10px;justify-content:center">
      <button class="btn btn-ghost" onclick="closeConfirm()">Annulla</button>
      <button class="btn btn-danger" id="confirmOkBtn">Elimina</button>
    </div>
  </div>
</div>

<script>
// ── Globals ──────────────────────────────────────────────────────────────────
let categories = [], allTags = [];
let txEditId = null, txType = 'entrata';
let selectedTags = [];
let _confirmCb = null;

// ── Init ─────────────────────────────────────────────────────────────────────
document.getElementById('sidebar-date').textContent =
  new Date().toLocaleDateString('it-IT', {weekday:'long', day:'numeric', month:'long', year:'numeric'});

async function loadCategories() {
  const r = await fetch('/api/categories');
  categories = await r.json();
  return categories;
}
async function loadTags() {
  const r = await fetch('/api/tags');
  allTags = await r.json();
  return allTags;
}
Promise.all([loadCategories(), loadTags()]);

// ── Formatters ────────────────────────────────────────────────────────────────
function fmt(n) {
  return new Intl.NumberFormat('it-IT',{style:'currency',currency:'EUR'}).format(n||0);
}
function fmtDate(d) {
  if (!d) return '';
  const [y,m,dd] = d.split('-'); return `${dd}/${m}/${y}`;
}

// ── Toast ─────────────────────────────────────────────────────────────────────
let _toastTimer;
function showToast(msg, type='success') {
  const t = document.getElementById('toast');
  t.textContent = msg; t.className = `show ${type}`;
  clearTimeout(_toastTimer);
  _toastTimer = setTimeout(() => t.className = '', 3000);
}

// ── Transaction modal ─────────────────────────────────────────────────────────
function openTransactionModal(tx=null) {
  txEditId      = tx ? tx.id : null;
  selectedTags  = tx ? (tx.tags||[]).map(t=>t.name) : [];
  txType        = tx ? tx.type : 'entrata';

  document.getElementById('txModalTitle').textContent = tx ? 'Modifica Transazione' : 'Nuova Transazione';
  document.getElementById('txDate').value        = tx ? tx.date : new Date().toISOString().split('T')[0];
  document.getElementById('txAmount').value      = tx ? tx.amount : '';
  document.getElementById('txDescription').value = tx ? tx.description : '';
  document.getElementById('txNotes').value       = tx ? (tx.notes||'') : '';
  document.getElementById('txReceipt').value     = '';
  document.getElementById('txTagInput').value    = '';

  // Show/hide existing receipt
  const receiptWrap = document.getElementById('existingReceiptWrap');
  if (tx && tx.receipt_path) {
    receiptWrap.style.display = 'block';
    const ext = tx.receipt_path.split('.').pop().toLowerCase();
    const isImg = ['jpg','jpeg','png','gif','webp'].includes(ext);
    receiptWrap.innerHTML = `
      <div class="receipt-preview">
        ${isImg ? `<img src="${tx.receipt_path}" alt="scontrino">` : '📄'}
        <a href="${tx.receipt_path}" target="_blank" style="color:var(--primary);font-weight:600">Vedi allegato</a>
        <button class="btn-icon" onclick="deleteReceipt(${tx.id})" title="Rimuovi">🗑️</button>
      </div>`;
  } else {
    receiptWrap.style.display = 'none';
    receiptWrap.innerHTML = '';
  }

  setTxType(txType);
  populateCatSelect(txType, tx ? tx.category_id : null);
  renderSelectedTags();
  document.getElementById('txModal').classList.add('open');
  setTimeout(() => document.getElementById('txAmount').focus(), 50);
}
function closeTxModal() {
  document.getElementById('txModal').classList.remove('open');
  document.getElementById('tagSuggestions').style.display = 'none';
}

function setTxType(type) {
  txType = type;
  document.getElementById('btnEntrata').className = 'type-btn' + (type==='entrata' ? ' active-in' : '');
  document.getElementById('btnUscita').className  = 'type-btn' + (type==='uscita'  ? ' active-out' : '');
  populateCatSelect(type, null);
}

function populateCatSelect(type, selectedId) {
  const sel = document.getElementById('txCategory');
  sel.innerHTML = '<option value="">— Nessuna —</option>';
  categories.filter(c => c.type === type || c.type === 'entrambi').forEach(c => {
    const o = document.createElement('option');
    o.value = c.id; o.textContent = c.icon + ' ' + c.name;
    if (selectedId && c.id == selectedId) o.selected = true;
    sel.appendChild(o);
  });
}

async function saveTx() {
  const date = document.getElementById('txDate').value;
  const amt  = parseFloat(document.getElementById('txAmount').value);
  const desc = document.getElementById('txDescription').value.trim();
  if (!date)       { showToast('Inserisci la data','error'); return; }
  if (!amt||amt<=0){ showToast('Importo non valido','error'); return; }
  if (!desc)       { showToast('Inserisci la descrizione','error'); return; }

  const catId = document.getElementById('txCategory').value;
  const payload = {
    date, amount: amt, type: txType,
    category_id: catId ? parseInt(catId) : null,
    description: desc,
    notes: document.getElementById('txNotes').value.trim(),
    tags: selectedTags
  };

  const btn = document.getElementById('txSaveBtn');
  btn.disabled = true; btn.textContent = 'Salvataggio…';

  let txId;
  if (txEditId) {
    await fetch(`/api/transactions/${txEditId}`,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
    txId = txEditId;
  } else {
    const r = await fetch('/api/transactions',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
    const j = await r.json(); txId = j.id;
  }

  // Upload receipt if selected
  const file = document.getElementById('txReceipt').files[0];
  if (file && txId) {
    const fd = new FormData(); fd.append('file', file);
    await fetch(`/api/transactions/${txId}/receipt`,{method:'POST',body:fd});
  }

  btn.disabled = false; btn.textContent = 'Salva';
  showToast(txEditId ? 'Transazione aggiornata' : 'Transazione aggiunta','success');
  closeTxModal();
  if (typeof onTxSaved === 'function') onTxSaved();
}

async function deleteReceipt(txId) {
  await fetch(`/api/transactions/${txId}/receipt`,{method:'DELETE'});
  document.getElementById('existingReceiptWrap').style.display = 'none';
  showToast('Allegato rimosso');
}

// ── Tags ──────────────────────────────────────────────────────────────────────
function showTagSuggestions(val) {
  const box = document.getElementById('tagSuggestions');
  if (!val.trim()) { box.style.display='none'; return; }
  const matches = allTags.filter(t => t.name.toLowerCase().includes(val.toLowerCase()) && !selectedTags.includes(t.name));
  if (!matches.length) { box.style.display='none'; return; }
  box.innerHTML = '';
  matches.slice(0,6).forEach(t => {
    const d = document.createElement('div');
    d.textContent = t.name;
    d.onclick = () => { addTag(t.name); document.getElementById('txTagInput').value=''; box.style.display='none'; };
    box.appendChild(d);
  });
  box.style.display = 'block';
}
function tagKeydown(e) {
  if (e.key==='Enter'||e.key===',') {
    e.preventDefault();
    const v = document.getElementById('txTagInput').value.trim();
    if (v) { addTag(v); document.getElementById('txTagInput').value=''; }
    document.getElementById('tagSuggestions').style.display='none';
  }
}
function addTag(name) {
  if (!selectedTags.includes(name)) { selectedTags.push(name); renderSelectedTags(); }
}
function removeTag(name) {
  selectedTags = selectedTags.filter(t=>t!==name); renderSelectedTags();
}
function renderSelectedTags() {
  const wrap = document.getElementById('selectedTagsWrap');
  wrap.innerHTML = '';
  selectedTags.forEach(name => {
    const tag   = allTags.find(t=>t.name===name);
    const color = tag ? tag.color : '#6366f1';
    const chip  = document.createElement('span');
    chip.className = 'tag-chip';
    chip.style.cssText = `background:${color}22;color:${color};border:1px solid ${color}44`;
    chip.innerHTML = `${name} <span onclick="removeTag('${name}')" style="cursor:pointer;margin-left:2px">×</span>`;
    wrap.appendChild(chip);
  });
}

// ── Voice note ────────────────────────────────────────────────────────────────
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SpeechRecognition) document.getElementById('voiceBtn').style.display='none';
let voiceRec = null;
function startVoice() {
  if (!SpeechRecognition) return;
  if (voiceRec) { voiceRec.stop(); return; }
  voiceRec = new SpeechRecognition();
  voiceRec.lang = 'it-IT'; voiceRec.interimResults = false;
  document.getElementById('voiceBtn').textContent = '⏹';
  voiceRec.onresult = e => {
    document.getElementById('txDescription').value = e.results[0][0].transcript;
  };
  voiceRec.onend = () => {
    voiceRec = null; document.getElementById('voiceBtn').textContent = '🎤';
  };
  voiceRec.start();
}

// ── Confirm dialog ────────────────────────────────────────────────────────────
function openConfirm(cb) { _confirmCb=cb; document.getElementById('confirmModal').classList.add('open'); }
function closeConfirm()  { _confirmCb=null; document.getElementById('confirmModal').classList.remove('open'); }
document.getElementById('confirmOkBtn').onclick = () => { if (_confirmCb) _confirmCb(); closeConfirm(); };
document.addEventListener('keydown', e => { if(e.key==='Escape'){closeTxModal();closeConfirm();} });
document.addEventListener('click', e => {
  const box = document.getElementById('tagSuggestions');
  if (box && !box.contains(e.target) && e.target.id!=='txTagInput') box.style.display='none';
});
</script>
{% block scripts %}{% endblock %}
</body>
</html>
