{% extends 'base.html' %}
{% set active = 'calendar' %}
{% block page_title %}Calendario{% endblock %}
{% block header_title %}Calendario{% endblock %}

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

{% block content %}
<div style="display:grid;grid-template-columns:1fr 320px;gap:16px;align-items:start">

  <!-- Calendar -->
  <div class="chart-card" style="padding:16px">
    <!-- Day headers -->
    <div class="cal-grid" style="margin-bottom:6px">
      <div class="cal-head">Lun</div><div class="cal-head">Mar</div><div class="cal-head">Mer</div>
      <div class="cal-head">Gio</div><div class="cal-head">Ven</div>
      <div class="cal-head" style="color:var(--expense)">Sab</div>
      <div class="cal-head" style="color:var(--expense)">Dom</div>
    </div>
    <div class="cal-grid" id="calGrid"></div>

    <!-- Legend -->
    <div style="display:flex;gap:14px;margin-top:12px;font-size:.72rem;color:var(--muted);flex-wrap:wrap">
      <span><span style="display:inline-block;width:10px;height:10px;border-radius:3px;background:#d1fae5;margin-right:3px"></span>Saldo positivo</span>
      <span><span style="display:inline-block;width:10px;height:10px;border-radius:3px;background:#fee2e2;margin-right:3px"></span>Saldo negativo</span>
      <span><span style="display:inline-block;width:10px;height:10px;border-radius:3px;border:2px solid var(--primary);margin-right:3px"></span>Oggi</span>
    </div>
  </div>

  <!-- Day detail panel -->
  <div>
    <div class="chart-card" id="dayPanel">
      <div id="dayPanelEmpty" style="text-align:center;padding:32px 10px;color:var(--muted)">
        <div style="font-size:2rem;margin-bottom:8px">👆</div>
        <div style="font-size:.82rem">Clicca su un giorno per vedere le transazioni</div>
      </div>
      <div id="dayPanelContent" style="display:none">
        <h6 id="dayPanelTitle" style="margin-bottom:14px"></h6>
        <div id="dayPanelSummary" style="display:flex;gap:10px;margin-bottom:12px;flex-wrap:wrap"></div>
        <div id="dayPanelTxList"></div>
        <button class="btn btn-primary btn-sm" id="dayAddBtn" style="width:100%;margin-top:12px" onclick="addForDay()">
          + Aggiungi transazione
        </button>
      </div>
    </div>

    <!-- Month summary -->
    <div class="chart-card" style="margin-top:12px">
      <h6>Riepilogo mese</h6>
      <div style="display:flex;flex-direction:column;gap:8px" id="monthSummary">
        <div style="display:flex;justify-content:space-between;font-size:.85rem">
          <span style="color:var(--muted)">Entrate</span>
          <span class="amt-in" id="ms-in">—</span>
        </div>
        <div style="display:flex;justify-content:space-between;font-size:.85rem">
          <span style="color:var(--muted)">Uscite</span>
          <span class="amt-out" id="ms-out">—</span>
        </div>
        <div style="display:flex;justify-content:space-between;font-size:.85rem;border-top:1px solid var(--border);padding-top:8px">
          <span style="font-weight:700">Saldo</span>
          <span id="ms-bal" style="font-weight:700">—</span>
        </div>
        <div style="display:flex;justify-content:space-between;font-size:.78rem">
          <span style="color:var(--muted)">Giorni con spese</span>
          <span id="ms-days">—</span>
        </div>
        <div style="display:flex;justify-content:space-between;font-size:.78rem">
          <span style="color:var(--muted)">Media giornaliera</span>
          <span class="amt-out" id="ms-avg">—</span>
        </div>
      </div>
    </div>
  </div>
</div>

{% endblock %}

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

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

async function loadCal(){
  updateLabel();
  calData=await fetch(`/api/calendar?year=${curYear}&month=${curMonth}`).then(r=>r.json());
  renderCal();
  updateMonthSummary();
  selectedDay=null;
  document.getElementById('dayPanelEmpty').style.display='block';
  document.getElementById('dayPanelContent').style.display='none';
}

function renderCal(){
  const grid=document.getElementById('calGrid');
  grid.innerHTML='';
  const {first_weekday, days_in_month, days, year, month}=calData;

  // Empty cells before first day
  for(let i=0;i<first_weekday;i++){
    const d=document.createElement('div'); d.className='cal-day empty'; grid.appendChild(d);
  }

  for(let day=1;day<=days_in_month;day++){
    const dateStr=`${year}-${String(month).padStart(2,'0')}-${String(day).padStart(2,'0')}`;
    const data=days[dateStr];
    const div=document.createElement('div');
    div.className='cal-day'+(dateStr===today?' today':'');
    if(data){
      const net=data.entrate-data.uscite;
      if(net>0) div.style.background='#f0fdf4';
      else if(net<0) div.style.background='#fef2f2';
    }
    div.onclick=()=>selectDay(dateStr);

    const numDiv=document.createElement('div');
    numDiv.className='cal-day-num'; numDiv.textContent=day;
    if([6,0].includes((first_weekday+day-1)%7)) numDiv.style.color='var(--expense)';
    div.appendChild(numDiv);

    if(data){
      if(data.uscite>0){
        const b=document.createElement('span'); b.className='cal-day-badge cal-net-neg';
        b.textContent='−'+fmt(data.uscite); div.appendChild(b);
      }
      if(data.entrate>0){
        const b=document.createElement('span'); b.className='cal-day-badge cal-net-pos';
        b.textContent='+'+fmt(data.entrate); div.appendChild(b);
      }
    }
    grid.appendChild(div);
  }
}

function selectDay(dateStr){
  selectedDay=dateStr;
  const data=calData.days[dateStr];
  document.getElementById('dayPanelEmpty').style.display='none';
  document.getElementById('dayPanelContent').style.display='block';

  const [y,m,d]=dateStr.split('-');
  document.getElementById('dayPanelTitle').textContent=`${parseInt(d)} ${MONTHS[parseInt(m)-1]} ${y}`;

  const summary=document.getElementById('dayPanelSummary');
  summary.innerHTML='';
  if(data){
    if(data.entrate>0) summary.innerHTML+=`<span class="badge-pill" style="background:#d1fae5;color:#065f46">↑ ${fmt(data.entrate)}</span>`;
    if(data.uscite>0)  summary.innerHTML+=`<span class="badge-pill" style="background:#fee2e2;color:#991b1b">↓ ${fmt(data.uscite)}</span>`;
    const net=data.entrate-data.uscite;
    summary.innerHTML+=`<span class="badge-pill" style="background:#f1f5f9;color:var(--text)">= ${fmt(net)}</span>`;
  } else {
    summary.innerHTML='<span style="font-size:.8rem;color:var(--muted)">Nessuna transazione</span>';
  }

  const list=document.getElementById('dayPanelTxList');
  list.innerHTML='';
  if(data && data.transactions.length){
    data.transactions.forEach(tx=>{
      const div=document.createElement('div');
      div.style.cssText='display:flex;align-items:center;gap:8px;padding:7px 0;border-bottom:1px solid var(--border);font-size:.82rem';
      div.innerHTML=`
        <span style="font-size:1rem">${tx.icon||'📦'}</span>
        <div style="flex:1;min-width:0">
          <div style="font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${tx.description}</div>
          <div style="color:var(--muted);font-size:.72rem">${tx.cat_name||'—'}</div>
        </div>
        <span class="${tx.type==='entrata'?'amt-in':'amt-out'}" style="font-weight:700;flex-shrink:0">${tx.type==='entrata'?'+':'−'}${fmt(tx.amount)}</span>`;
      list.appendChild(div);
    });
  }
}

function updateMonthSummary(){
  let totIn=0, totOut=0, daysWithTx=0;
  Object.values(calData.days).forEach(d=>{
    totIn+=d.entrate; totOut+=d.uscite;
    if(d.transactions.length) daysWithTx++;
  });
  document.getElementById('ms-in').textContent=fmt(totIn);
  document.getElementById('ms-out').textContent=fmt(totOut);
  const bal=totIn-totOut;
  const balEl=document.getElementById('ms-bal');
  balEl.textContent=fmt(bal); balEl.style.color=bal>=0?'var(--income)':'var(--expense)';
  document.getElementById('ms-days').textContent=daysWithTx;
  document.getElementById('ms-avg').textContent=daysWithTx>0?fmt(totOut/daysWithTx):'—';
}

function addForDay(){
  // Pre-fill today's date with the selected day
  openTransactionModal();
  setTimeout(()=>{ if(selectedDay) document.getElementById('txDate').value=selectedDay; }, 20);
}

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