'use strict';
(function () {

  /* ── Configuración ─────────────────────────────────────── */
  const YEAR  = 2026;
  const MONTH = 4; // Mayo (0-based)
  const USERNAME = document.querySelector('.user-email')?.textContent.trim() || 'guest';
  const KEY   = `planning_${YEAR}_${USERNAME}`;

  /* ── Persistencia ──────────────────────────────────────── */
  function load() {
    try {
      const s = JSON.parse(localStorage.getItem(KEY));
      return { completed: s?.completed || [], moved: s?.moved || {} };
    } catch { return { completed: [], moved: {} }; }
  }
  function save(s) { localStorage.setItem(KEY, JSON.stringify(s)); }

  /* ── Fecha actual ──────────────────────────────────────── */
  const now = new Date();
  const todayDay = (now.getFullYear() === YEAR && now.getMonth() === MONTH)
    ? now.getDate() : null;

  /* ── Mapa de días ──────────────────────────────────────── */
  // dayMap: { 8: diaDom, 9: diaDom, … }
  const dayMap = {};
  document.querySelectorAll('.dia').forEach(dia => {
    const numEl = dia.querySelector(':scope > .num');
    if (!numEl) return;
    const n = parseInt(numEl.textContent.trim(), 10);
    if (!isNaN(n)) dayMap[n] = dia;
  });

  /* ── Marcar hoy ────────────────────────────────────────── */
  if (todayDay && dayMap[todayDay]) {
    const d = dayMap[todayDay];
    d.classList.add('hoy');
    const numEl = d.querySelector(':scope > .num');
    if (numEl) numEl.insertAdjacentHTML('afterend', '<span class="hoy-label">HOY</span>');
  }

  /* ── Envolver .tema-btn en .tema-row ───────────────────── */
  document.querySelectorAll('.tema-btn').forEach(btn => {
    const row = document.createElement('div');
    row.className = 'tema-row';
    btn.before(row);
    row.appendChild(btn);
  });

  /* ── Aplicar temas movidos al cargar ───────────────────── */
  const state = load();
  Object.entries(state.moved).forEach(([href, dayNum]) => {
    const btn = [...document.querySelectorAll('.tema-btn')]
      .find(b => b.getAttribute('href') === href);
    const row = btn?.closest('.tema-row');
    const contenido = dayMap[Number(dayNum)]?.querySelector('.contenido');
    if (row && contenido && !contenido.contains(row)) {
      contenido.appendChild(row);
    }
  });

  /* ── Añadir controles a cada fila ──────────────────────── */
  const completedSet = new Set(state.completed);

  document.querySelectorAll('.tema-row').forEach(row => {
    const btn = row.querySelector('.tema-btn');
    if (!btn) return;
    const id = btn.getAttribute('href');
    const done = completedSet.has(id);

    // ── Botón ✓ / ○ ──
    const chk = document.createElement('button');
    chk.className = 'check-btn' + (done ? ' checked' : '');
    chk.title     = done ? 'Marcar como pendiente' : 'Marcar como hecho';
    chk.textContent = done ? '✓' : '○';
    row.insertBefore(chk, btn);
    if (done) btn.classList.add('completado');

    chk.addEventListener('click', e => {
      e.preventDefault();
      const s = load();
      const set = new Set(s.completed);
      const nowDone = !set.has(id);
      nowDone ? set.add(id) : set.delete(id);
      s.completed = [...set];
      save(s);
      chk.classList.toggle('checked', nowDone);
      chk.textContent = nowDone ? '✓' : '○';
      btn.classList.toggle('completado', nowDone);
      updateOverdue();
    });

    // ── Botón mover ──
    const mv = document.createElement('button');
    mv.className   = 'move-btn';
    mv.title       = 'Mover a otro día';
    mv.textContent = '⇌';
    row.appendChild(mv);
    mv.addEventListener('click', e => { e.preventDefault(); showPicker(row, id); });
  });

  /* ── Picker de día ─────────────────────────────────────── */
  function showPicker(row, id) {
    document.querySelectorAll('.move-picker').forEach(p => p.remove());
    const picker = document.createElement('div');
    picker.className = 'move-picker';
    picker.insertAdjacentHTML('afterbegin', '<div class="mp-label">Mover a:</div>');

    const days = Object.keys(dayMap).map(Number)
      .filter(d => !dayMap[d].classList.contains('vacio')
               && !dayMap[d].classList.contains('examen'))
      .sort((a, b) => a - b);

    days.forEach(d => {
      const b = document.createElement('button');
      b.textContent = `Día ${d}` + (d === todayDay ? ' · hoy' : '');
      if (d === todayDay) b.classList.add('mp-today');
      b.addEventListener('click', e => {
        e.stopPropagation();
        const s = load();
        s.moved[id] = d;
        save(s);
        const c = dayMap[d]?.querySelector('.contenido');
        if (c && !c.contains(row)) c.appendChild(row);
        picker.remove();
        updateOverdue();
      });
      picker.appendChild(b);
    });

    const rst = document.createElement('button');
    rst.className   = 'mp-reset';
    rst.textContent = '↺ Restaurar original';
    rst.addEventListener('click', e => {
      e.stopPropagation();
      const s = load();
      delete s.moved[id];
      save(s);
      location.reload();
    });
    picker.appendChild(rst);

    row.style.position = 'relative';
    row.appendChild(picker);

    setTimeout(() => {
      document.addEventListener('click', function h(e) {
        if (!picker.contains(e.target)) {
          picker.remove();
          document.removeEventListener('click', h);
        }
      });
    }, 0);
  }

  /* ── Indicadores de atrasados ──────────────────────────── */
  function updateOverdue() {
    const s    = load();
    const done = new Set(s.completed);
    Object.entries(dayMap).forEach(([dayStr, dia]) => {
      const d = Number(dayStr);
      dia.querySelectorAll('.tema-row').forEach(row => {
        const id = row.querySelector('.tema-btn')?.getAttribute('href');
        const overdue = !!id && todayDay != null && d < todayDay && !done.has(id);
        row.classList.toggle('atrasado', overdue);
      });
      const n = dia.querySelectorAll('.tema-row.atrasado').length;
      let badge = dia.querySelector('.overdue-badge');
      if (n > 0) {
        if (!badge) {
          badge = document.createElement('span');
          badge.className = 'overdue-badge';
          dia.querySelector(':scope > .num')?.insertAdjacentElement('afterend', badge);
        }
        badge.textContent = `${n} atrasado${n > 1 ? 's' : ''}`;
      } else if (badge) {
        badge.remove();
      }
    });
  }

  updateOverdue();

  /* ── Reiniciar progreso ────────────────────────────────── */
  document.getElementById('btn-reset-planning')?.addEventListener('click', () => {
    if (confirm('¿Reiniciar todo el progreso guardado?')) {
      localStorage.removeItem(KEY);
      location.reload();
    }
  });

})();
