// /views/js/perfil.js
(() => {
  const API = '/controllers/controller_usuario.php';

  /* ===== util ===== */
  const qs = (s, r = document) => r.querySelector(s);
  const qsa = (s, r = document) => [...r.querySelectorAll(s)];
  const toastBox = qs('#toast');

  const toast = (msg) => {
    if (!toastBox) return alert(msg);
    toastBox.textContent = msg;
    toastBox.style.display = 'block';
    setTimeout(() => toastBox.style.display = 'none', 1800);
  };
  const openModal = el => el && (el.style.display = 'flex');
  const closeModal = el => el && (el.style.display = 'none');
  const formParams = (form) => new URLSearchParams(new FormData(form));
  const postJSON = async (params) => {
    const res = await fetch(API, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      body: params
    });
    const txt = await res.text();
    try { return JSON.parse(txt); }
    catch { console.error('Respuesta no-JSON:', txt); throw new Error('Respuesta inválida del servidor'); }
  };

  /* ===== menú móvil (igual al resto) ===== */
  const toggle = qs('.menu-toggle');
  const menu = qs('#topbarMenu');
  if (toggle && menu) {
    toggle.addEventListener('click', (e) => {
      e.stopPropagation();
      const open = menu.classList.toggle('show');
      toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
    });
    document.addEventListener('click', (e) => {
      if (!menu.classList.contains('show')) return;
      if (!menu.contains(e.target) && e.target !== toggle) {
        menu.classList.remove('show');
        toggle.setAttribute('aria-expanded', 'false');
      }
    });
    window.addEventListener('resize', () => {
      if (window.innerWidth > 720) {
        menu.classList.remove('show');
        toggle.setAttribute('aria-expanded', 'false');
      }
    });
  }

  /* ===== puerta de administrador (contraseña) ===== */
  const gateModal = qs('#gateModal');
  const gateForm = qs('#gateForm');
  const gateMsg = qs('#gateMsg');

  // Mostrar puerta al cargar
  if (gateModal) openModal(gateModal);

  if (gateForm) {
    gateForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      gateMsg.textContent = '';
      try {
        const pass = qs('#gatePass').value;
        const data = await postJSON(new URLSearchParams({
          action: 'verify_password',
          password: pass
        }));
        if (!data.success) throw new Error(data.message || 'No autorizado');
        closeModal(gateModal);
        toast('Acceso de administrador concedido');
      } catch (err) {
        gateMsg.textContent = err.message;
      }
    });
  }

  // Cierre genérico de modales
  document.addEventListener('click', (e) => {
    const btn = e.target.closest('[data-close]');
    if (btn) closeModal(btn.closest('.modal'));
  });
  window.addEventListener('click', (e) => {
    if (e.target?.classList?.contains('modal')) closeModal(e.target);
  });

  /* ===== Copiar link de invitación ===== */
  const btnCopy = qs('#btnCopiarLink');
  if (btnCopy) {
    btnCopy.addEventListener('click', async () => {
      const url = document.body.dataset.inviteUrl;
      try {
        await navigator.clipboard.writeText(url);
        toast('Link de invitación copiado');
      } catch {
        toast(url); // fallback
      }
    });
  }

  /* ===== Editar MI perfil (modal) ===== */
  const btnEditarPerfil = qs('#btnEditarPerfil');
  const profileModal = qs('#profileModal');
  const profileForm = qs('#profileForm');

  if (btnEditarPerfil && profileModal && profileForm) {
    btnEditarPerfil.addEventListener('click', async () => {
      try {
        const r = await fetch(`${API}?action=get_user&id=1`);
        const data = await r.json();
        if (!data.success) throw new Error(data.message || 'No se pudo cargar');
        profileForm.nombre_completo.value = data.user.nombre || '';
        profileForm.correo.value = data.user.correo || '';
        profileForm.telefono.value = data.user.telefono || '';
        profileForm.new_password.value = '';
        openModal(profileModal);
      } catch (err) {
        toast(err.message || 'Error al abrir');
      }
    });

    profileForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      try {
        const p = formParams(profileForm);
        p.set('action', 'update_profile');
        const data = await postJSON(p);
        if (!data.success) throw new Error(data.message || 'No se guardó');
        toast('Perfil actualizado');
        closeModal(profileModal);
        // Refleja rápido en la UI (nombre/correo/teléfono en la card)
        const block = qs('.perfil-block');
        if (block) {
          block.querySelectorAll('.pair')[1].querySelector('strong').textContent = profileForm.nombre_completo.value;
          block.querySelectorAll('.pair')[2].querySelector('strong').textContent = profileForm.correo.value;
          block.querySelectorAll('.pair')[3].querySelector('strong').textContent = profileForm.telefono.value;
        }
      } catch (err) { toast(err.message); }
    });
  }

  /* ===== Ver / Editar OTRO usuario ===== */
  const userModal = qs('#userModal');
  const userForm = qs('#userForm');
  const btnToggle = qs('#btnToggle');
  const btnDelete = qs('#btnDelete');
  let currentActive = false;

  // Abrir desde las cards (delegación)
  document.addEventListener('click', async (e) => {
    const btnVer = e.target.closest('[data-ver]');
    if (!btnVer) return;
    const id = btnVer.dataset.ver;

    try {
      const r = await fetch(`${API}?action=get_user&id=${encodeURIComponent(id)}`);
      const data = await r.json();
      if (!data.success) throw new Error(data.message || 'No disponible');

      userForm.id.value = data.user.id;
      userForm.nombre_completo.value = data.user.nombre || '';
      userForm.correo.value = data.user.correo || '';
      userForm.telefono.value = data.user.telefono || '';
      userForm.new_password.value = '';
      userForm.activo.checked = !!data.user.activo;
      currentActive = !!data.user.activo;
      btnToggle.textContent = currentActive ? 'Desactivar' : 'Dar de alta';
      openModal(userModal);
    } catch (err) {
      toast(err.message);
    }
  });

  // Guardar usuario
  if (userForm) {
    userForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      try {
        const p = formParams(userForm);
        p.set('action', 'update_user');
        // Marca de activo si no está checkeado:
        if (!userForm.activo.checked) p.set('activo', '0');
        const data = await postJSON(p);
        if (!data.success) throw new Error(data.message || 'No se guardó');
        toast('Usuario actualizado');
        // Reflejar en la card
        const id = userForm.id.value;
        const card = qs(`.user-card[data-id="${id}"]`);
        if (card) {
          card.querySelector('h4').textContent = userForm.nombre_completo.value || '—';
          const badge = card.querySelector('.badge');
          const isAct = userForm.activo.checked;
          badge.classList.toggle('ok', isAct);
          badge.classList.toggle('warn', !isAct);
          badge.textContent = isAct ? 'ACTIVO' : 'PENDIENTE/INACTIVO';
        }
        closeModal(userModal);
      } catch (err) { toast(err.message); }
    });
  }

  // Activar / Desactivar
  if (btnToggle) {
    btnToggle.addEventListener('click', async () => {
      const id = userForm.id.value;
      const to = currentActive ? 'desactivar' : 'activar';
      try {
        const data = await postJSON(new URLSearchParams({ action: 'toggle_status', id, to }));
        if (!data.success) throw new Error(data.message || 'No se pudo cambiar');
        currentActive = !currentActive;
        userForm.activo.checked = currentActive;
        btnToggle.textContent = currentActive ? 'Desactivar' : 'Dar de alta';
        toast(data.message || 'Estado actualizado');

        // Reflejar en la card
        const card = qs(`.user-card[data-id="${id}"]`);
        if (card) {
          const badge = card.querySelector('.badge');
          badge.classList.toggle('ok', currentActive);
          badge.classList.toggle('warn', !currentActive);
          badge.textContent = currentActive ? 'ACTIVO' : 'PENDIENTE/INACTIVO';
          // Reescribir botones del footer para que coincidan
          const f = card.querySelector('.actions-row');
          f.innerHTML = currentActive
            ? `<button class="btn" data-ver="${id}">Ver / Editar</button>
                 <button class="btn danger" data-desactivar="${id}">Desactivar</button>`
            : `<button class="btn" data-ver="${id}">Ver / Editar</button>
                 <button class="btn primary" data-activar="${id}">Dar de alta</button>
                 <button class="btn danger" data-eliminar="${id}">Eliminar solicitud</button>`;
        }
      } catch (err) { toast(err.message); }
    });
  }

  // Eliminar
  if (btnDelete) {
    btnDelete.addEventListener('click', async () => {
      const id = userForm.id.value;
      if (!confirm('¿Eliminar usuario definitivamente?')) return;
      try {
        const data = await postJSON(new URLSearchParams({ action: 'delete_user', id }));
        if (!data.success) throw new Error(data.message || 'No se pudo eliminar');
        toast('Usuario eliminado');
        const card = qs(`.user-card[data-id="${id}"]`);
        if (card) card.remove();
        closeModal(userModal);
      } catch (err) { toast(err.message); }
    });
  }

  /* ===== atajos directos en card: activar/desactivar/eliminar ===== */
  document.addEventListener('click', async (e) => {
    const act = e.target.closest('[data-activar]');
    const des = e.target.closest('[data-desactivar]');
    const del = e.target.closest('[data-eliminar]');
    try {
      if (act || des) {
        const id = (act || des).dataset.activar || (act || des).dataset.desactivar;
        const to = act ? 'activar' : 'desactivar';
        const data = await postJSON(new URLSearchParams({ action: 'toggle_status', id, to }));
        if (!data.success) throw new Error(data.message || 'No se pudo cambiar');
        toast(data.message);
        // Refleja en UI
        const card = qs(`.user-card[data-id="${id}"]`);
        if (card) {
          const badge = card.querySelector('.badge');
          const on = !!act;
          badge.classList.toggle('ok', on);
          badge.classList.toggle('warn', !on);
          badge.textContent = on ? 'ACTIVO' : 'PENDIENTE/INACTIVO';
          const f = card.querySelector('.actions-row');
          f.innerHTML = on
            ? `<button class="btn" data-ver="${id}">Ver / Editar</button>
                 <button class="btn danger" data-desactivar="${id}">Desactivar</button>`
            : `<button class="btn" data-ver="${id}">Ver / Editar</button>
                 <button class="btn primary" data-activar="${id}">Dar de alta</button>
                 <button class="btn danger" data-eliminar="${id}">Eliminar solicitud</button>`;
        }
      }
      if (del) {
        const id = del.dataset.eliminar;
        if (!confirm('¿Eliminar solicitud/usuario?')) return;
        const data = await postJSON(new URLSearchParams({ action: 'delete_user', id }));
        if (!data.success) throw new Error(data.message || 'No se pudo eliminar');
        toast('Usuario eliminado');
        const card = qs(`.user-card[data-id="${id}"]`);
        if (card) card.remove();
      }
    } catch (err) { toast(err.message); }
  });

})();

// === Carrusel de activos ===
document.querySelectorAll('.carousel').forEach(carousel => {
  const viewport = carousel.querySelector('.carousel-viewport');
  const prev = carousel.querySelector('.carousel-prev');
  const next = carousel.querySelector('.carousel-next');

  function step() { return Math.max(280, viewport.clientWidth * 0.9); }
  function updateArrows() {
    if (!prev || !next) return;
    prev.disabled = viewport.scrollLeft <= 2;
    const maxScroll = viewport.scrollWidth - viewport.clientWidth - 2;
    next.disabled = viewport.scrollLeft >= maxScroll;
  }
  if (prev) prev.addEventListener('click', () => viewport.scrollBy({ left: -step(), behavior: 'smooth' }));
  if (next) next.addEventListener('click', () => viewport.scrollBy({ left: step(), behavior: 'smooth' }));
  viewport.addEventListener('scroll', updateArrows, { passive: true });
  window.addEventListener('resize', updateArrows);
  updateArrows();
});
