const API = '../api';

function getToken() {
  return localStorage.getItem('token');
}

function authHeaders() {
  return { Authorization: `Bearer ${getToken()}` };
}

async function apiFetch(url, opts = {}) {
  opts.headers = { ...authHeaders(), ...(opts.headers || {}) };
  opts.cache = 'no-store';
  const res  = await fetch(url, opts);
  if (res.status === 401) {
    cerrarSesion();
    return null;
  }
  return res;
}

function cerrarSesion() {
  localStorage.clear();
  location.href = 'index.html';
}

function toggleTema() {
  const html  = document.documentElement;
  const light = html.getAttribute('data-theme') === 'light';
  const nuevo = light ? 'dark' : 'light';
  html.setAttribute('data-theme', nuevo);
  localStorage.setItem('tema', nuevo);
  document.getElementById('themeBtn').textContent = nuevo === 'light' ? '🌙' : '☀️';
}

(function initTema() {
  const tema = localStorage.getItem('tema') || 'dark';
  document.documentElement.setAttribute('data-theme', tema);
  window.addEventListener('DOMContentLoaded', () => {
    const btn = document.getElementById('themeBtn');
    if (btn) btn.textContent = tema === 'light' ? '🌙' : '☀️';
  });
})()

function showMsg(elId, msg, type = 'error') {
  const el = document.getElementById(elId);
  if (!el) return;
  el.innerHTML = `<div class="alert alert-${type}">${msg}</div>`;
  setTimeout(() => { el.innerHTML = ''; }, 4000);
}

function cerrarModal(id) {
  document.getElementById(id).classList.remove('open');
}

function abrirModal(id) {
  document.getElementById(id).classList.add('open');
}

// Cerrar modal al clic en backdrop
document.querySelectorAll('.modal-backdrop').forEach(bd => {
  bd.addEventListener('click', (e) => {
    if (e.target === bd) bd.classList.remove('open');
  });
});

// Tabs
document.querySelectorAll('.tab-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
    btn.classList.add('active');
    document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
  });
});

// File upload preview helper
function setupFilePreview(inputId, previewId, labelId) {
  const input   = document.getElementById(inputId);
  const preview = document.getElementById(previewId);
  const label   = document.getElementById(labelId);
  if (!input) return;

  input.addEventListener('change', () => {
    const file = input.files[0];
    if (!file) return;
    if (file.size > 3 * 1024 * 1024) {
      alert('El archivo supera los 3 MB.');
      input.value = '';
      return;
    }
    const reader = new FileReader();
    reader.onload = (e) => {
      preview.src           = e.target.result;
      preview.style.display = 'block';
      label.style.display   = 'none';
    };
    reader.readAsDataURL(file);
  });

  // Solo agregar click handler si el área NO es un <label>
  // (el label ya abre el selector automáticamente)
  const area = input.closest('.file-upload-area');
  if (area && area.tagName !== 'LABEL') {
    area.addEventListener('click', (e) => {
      if (e.target === input) return;
      input.click();
    });
  }
}

function resetFilePreview(inputId, previewId, labelId) {
  const input   = document.getElementById(inputId);
  const preview = document.getElementById(previewId);
  const label   = document.getElementById(labelId);
  if (input)   input.value = '';
  if (preview) { preview.src = ''; preview.style.display = 'none'; }
  if (label)   label.style.display = 'block';
}

function estadoBadge(activo, fechaInicio, fechaFin) {
  const hoy = new Date().toISOString().slice(0, 10);
  if (fechaFin < hoy)       return '<span class="badge badge-expired">Vencida</span>';
  if (!activo)              return '<span class="badge badge-inactive">Pausada</span>';
  if (fechaInicio > hoy)    return '<span class="badge badge-inactive">Programada</span>';
  return '<span class="badge badge-active">Activa</span>';
}

function formatFecha(f) {
  if (!f) return '';
  const [y, m, d] = f.split('-');
  return `${d}/${m}/${y}`;
}
