{% extends 'base.html' %}
{% set active = 'goals' %}
{% block page_title %}Obiettivi{% endblock %}
{% block header_title %}Obiettivi di Risparmio{% endblock %}

{% block topbar_extra %}
<button class="btn btn-ghost" onclick="openGoalModal()">+ Nuovo obiettivo</button>
{% endblock %}

{% block content %}
<div id="goalsGrid" style="display:grid;grid-template-columns:repeat(2,1fr);gap:16px"></div>
<div class="empty-state" id="goalsEmpty" style="display:none">
  <div class="empty-icon">⭐</div>
  <p>Nessun obiettivo di risparmio</p>
  <button class="btn btn-primary btn-sm" style="margin-top:12px" onclick="openGoalModal()">Crea il primo obiettivo</button>
</div>

<!-- Goal Modal -->
<div class="modal-overlay" id="goalModal" onclick="if(event.target===this)closeGoalModal()">
  <div class="modal-box">
    <button class="modal-close" onclick="closeGoalModal()">×</button>
    <h5 id="goalModalTitle">Nuovo Obiettivo</h5>
    <div class="form-row form-row-2">
      <div class="form-group">
        <label class="form-label">Nome *</label>
        <input type="text" class="form-control" id="goalName" placeholder="Es. Vacanza estate…">
      </div>
      <div class="form-group">
        <label class="form-label">Emoji icona</label>
        <input type="text" class="form-control" id="goalIcon" placeholder="🎯" maxlength="4">
      </div>
    </div>
    <div class="form-row form-row-2">
      <div class="form-group">
        <label class="form-label">Obiettivo (€) *</label>
        <input type="number" class="form-control" id="goalTarget" min="1" step="1" placeholder="5000">
      </div>
      <div class="form-group">
        <label class="form-label">Già risparmiato (€)</label>
        <input type="number" class="form-control" id="goalCurrent" min="0" step="1" placeholder="0">
      </div>
    </div>
    <div class="form-row form-row-2">
      <div class="form-group">
        <label class="form-label">Scadenza (opzionale)</label>
        <input type="date" class="form-control" id="goalDeadline">
      </div>
      <div class="form-group">
        <label class="form-label">Colore</label>
        <input type="color" class="form-control" id="goalColor" value="#4f46e5" style="height:40px;padding:4px 6px;cursor:pointer">
      </div>
    </div>
    <div class="form-group">
      <label class="form-label">Note</label>
      <textarea class="form-control" id="goalNotes" rows="2" placeholder="Opzionale…"></textarea>
    </div>
    <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:6px">
      <button class="btn btn-ghost" onclick="closeGoalModal()">Annulla</button>
      <button class="btn btn-primary" onclick="saveGoal()">Salva</button>
    </div>
  </div>
</div>

<!-- Contribute Modal -->
<div class="modal-overlay" id="contribModal" onclick="if(event.target===this)this.classList.remove('open')">
  <div class="modal-box" style="max-width:340px">
    <button class="modal-close" onclick="document.getElementById('contribModal').classList.remove('open')">×</button>
    <h5 id="contribTitle">Aggiungi contributo</h5>
    <div class="form-group">
      <label class="form-label">Importo (€)</label>
      <input type="number" class="form-control" id="contribAmount" min="0.01" step="0.01" placeholder="100">
    </div>
    <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:6px">
      <button class="btn btn-ghost" onclick="document.getElementById('contribModal').classList.remove('open')">Annulla</button>
      <button class="btn btn-primary" onclick="saveContrib()">Aggiungi</button>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let goals = [], goalEditId = null, contribGoalId = null;

async function loadGoals() {
  goals = await fetch('/api/goals').then(r=>r.json());
  renderGoals();
}

function renderGoals() {
  const grid=document.getElementById('goalsGrid'), empty=document.getElementById('goalsEmpty');
  grid.innerHTML='';
  if (!goals.length) { empty.style.display='block'; grid.style.display='none'; return; }
  empty.style.display='none'; grid.style.display='';

  goals.forEach(g => {
    const pct      = g.target_amount>0 ? Math.min((g.current_amount/g.target_amount)*100,100) : 0;
    const remaining= g.target_amount - g.current_amount;
    const done     = g.current_amount >= g.target_amount;

    // Deadline info
    let deadlineHtml = '';
    if (g.deadline) {
      const dDays = Math.round((new Date(g.deadline)-new Date())/86400000);
      const dStr  = fmtDate(g.deadline);
      if (done)          deadlineHtml = `<span class="badge-pill tl-ok-bg">✅ Completato!</span>`;
      else if (dDays<0)  deadlineHtml = `<span class="badge-pill tl-over-bg">⏰ Scaduto ${dStr}</span>`;
      else if (dDays<=30)deadlineHtml = `<span class="badge-pill tl-warn-bg">⏳ ${dDays}gg al ${dStr}</span>`;
      else               deadlineHtml = `<span style="font-size:.75rem;color:var(--muted)">📅 Entro ${dStr}</span>`;
    }

    // SVG ring
    const r=30, circ=2*Math.PI*r, offset=circ*(1-pct/100);
    const ringColor = done ? '#10b981' : g.color;

    const card=document.createElement('div');
    card.className='goal-card';
    card.innerHTML=`
      <div style="display:flex;gap:16px;align-items:flex-start">
        <svg class="goal-progress-ring" viewBox="0 0 72 72">
          <circle cx="36" cy="36" r="${r}" fill="none" stroke="#e2e8f0" stroke-width="6"/>
          <circle cx="36" cy="36" r="${r}" fill="none" stroke="${ringColor}" stroke-width="6"
            stroke-dasharray="${circ}" stroke-dashoffset="${offset}"
            stroke-linecap="round" transform="rotate(-90 36 36)" style="transition:stroke-dashoffset .5s"/>
          <text x="36" y="36" text-anchor="middle" dominant-baseline="middle"
            style="font-size:10px;font-weight:800;fill:${ringColor}">${Math.round(pct)}%</text>
        </svg>
        <div style="flex:1;min-width:0">
          <div style="display:flex;align-items:center;gap:8px;margin-bottom:4px">
            <span style="font-size:1.3rem">${g.icon||'🎯'}</span>
            <span style="font-weight:700;font-size:1rem">${g.name}</span>
          </div>
          <div style="font-size:.85rem;margin-bottom:6px">
            <span style="font-weight:800;color:${g.color};font-size:1.05rem">${fmt(g.current_amount)}</span>
            <span style="color:var(--muted)"> / ${fmt(g.target_amount)}</span>
          </div>
          ${deadlineHtml ? `<div style="margin-bottom:6px">${deadlineHtml}</div>` : ''}
          ${!done ? `<div style="font-size:.75rem;color:var(--muted)">Mancano ${fmt(remaining)}</div>` : ''}
          ${g.notes ? `<div style="font-size:.75rem;color:var(--muted);margin-top:4px;font-style:italic">${g.notes}</div>` : ''}
        </div>
        <div style="display:flex;flex-direction:column;gap:4px;flex-shrink:0">
          <button class="btn btn-sm btn-primary" onclick="openContrib(${g.id},'${g.name.replace(/'/g,'')}')">+ Contribuisci</button>
          <div style="display:flex;gap:4px;justify-content:flex-end">
            <button class="btn-icon" onclick="editGoal(${g.id})" title="Modifica">✏️</button>
            <button class="btn-icon" onclick="deleteGoal(${g.id})" title="Elimina">🗑️</button>
          </div>
        </div>
      </div>`;
    grid.appendChild(card);
  });
}

// ── Goal Modal ────────────────────────────────────────────────────────────────
function openGoalModal(g=null) {
  goalEditId=g?g.id:null;
  document.getElementById('goalModalTitle').textContent=g?'Modifica Obiettivo':'Nuovo Obiettivo';
  document.getElementById('goalName').value    =g?g.name:'';
  document.getElementById('goalIcon').value    =g?(g.icon||''):'';
  document.getElementById('goalTarget').value  =g?g.target_amount:'';
  document.getElementById('goalCurrent').value =g?g.current_amount:'';
  document.getElementById('goalDeadline').value=g?(g.deadline||''):'';
  document.getElementById('goalColor').value   =g?g.color:'#4f46e5';
  document.getElementById('goalNotes').value   =g?(g.notes||''):'';
  document.getElementById('goalModal').classList.add('open');
}
function closeGoalModal() { document.getElementById('goalModal').classList.remove('open'); }

async function saveGoal() {
  const name  =document.getElementById('goalName').value.trim();
  const target=parseFloat(document.getElementById('goalTarget').value);
  if(!name)       { showToast('Inserisci il nome','error'); return; }
  if(!target||target<=0){ showToast('Importo obiettivo non valido','error'); return; }
  const payload={
    name, icon:document.getElementById('goalIcon').value.trim()||'🎯',
    target_amount:target, current_amount:parseFloat(document.getElementById('goalCurrent').value)||0,
    deadline:document.getElementById('goalDeadline').value||null,
    color:document.getElementById('goalColor').value,
    notes:document.getElementById('goalNotes').value.trim()
  };
  const url=goalEditId?`/api/goals/${goalEditId}`:'/api/goals';
  const method=goalEditId?'PUT':'POST';
  await fetch(url,{method,headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
  showToast(goalEditId?'Obiettivo aggiornato':'Obiettivo creato','success');
  closeGoalModal(); loadGoals();
}

function editGoal(id) { const g=goals.find(x=>x.id===id); if(g) openGoalModal(g); }
function deleteGoal(id) {
  openConfirm(async()=>{
    await fetch(`/api/goals/${id}`,{method:'DELETE'});
    showToast('Obiettivo eliminato'); loadGoals();
  });
}

// ── Contribute ────────────────────────────────────────────────────────────────
function openContrib(id, name) {
  contribGoalId=id;
  document.getElementById('contribTitle').textContent=`Contribuisci a: ${name}`;
  document.getElementById('contribAmount').value='';
  document.getElementById('contribModal').classList.add('open');
  setTimeout(()=>document.getElementById('contribAmount').focus(),50);
}
async function saveContrib() {
  const amt=parseFloat(document.getElementById('contribAmount').value);
  if(!amt||amt<=0){ showToast('Importo non valido','error'); return; }
  await fetch(`/api/goals/${contribGoalId}/contribute`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({amount:amt})});
  showToast(`${fmt(amt)} aggiunto all'obiettivo`,'success');
  document.getElementById('contribModal').classList.remove('open');
  loadGoals();
}

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