/* admin-support.jsx — Panel de Soporte Técnico (Admin) */
const { useState: useStateSupp, useEffect: useEffectSupp } = React;

var SUPPORT_KEY_SV = 'sst_support_v2';

function loadSupportData() {
  try {
    var s = localStorage.getItem(SUPPORT_KEY_SV);
    if (s) {
      var p = JSON.parse(s);
      if (Array.isArray(p)) return p;
    }
  } catch (e) {}
  return [];
}

function saveSupportData(list) {
  try { localStorage.setItem(SUPPORT_KEY_SV, JSON.stringify(list)); } catch (e) {}
  if (typeof window.sbSave === 'function') window.sbSave(SUPPORT_KEY_SV, list);
}

/* ── API global ─────────────────────────────────────────── */
window.addSupportRequest = function (req) {
  var list = loadSupportData();
  list.unshift(req);
  saveSupportData(list);
  window.dispatchEvent(new CustomEvent('sst_support_added'));
};

/* ── Helpers ─────────────────────────────────────────────── */
function supportStatusStyle(estado) {
  if (estado === 'Resuelto')   return { background: '#dcfce7', color: '#15803d' };
  if (estado === 'En proceso') return { background: '#fef9c3', color: '#a16207' };
  return { background: '#fee2e2', color: '#b91c1c' };
}

function formatSupportDate(iso) {
  try {
    return new Date(iso).toLocaleDateString('es-CO', {
      year: 'numeric', month: 'short', day: 'numeric',
      hour: '2-digit', minute: '2-digit',
    });
  } catch (e) { return iso; }
}

var thSupp = {
  padding: '12px 18px', textAlign: 'left',
  fontSize: 11, fontWeight: 700, color: '#6b7280',
  textTransform: 'uppercase', letterSpacing: '0.07em', whiteSpace: 'nowrap',
};
var tdSupp = { padding: '14px 18px', verticalAlign: 'middle' };

/* ── Componente principal ────────────────────────────────── */
function AdminSupport() {
  var _reqs   = useStateSupp(function () { return loadSupportData(); });
  var requests = _reqs[0]; var setRequests = _reqs[1];
  var _detail  = useStateSupp(null);
  var detailReq = _detail[0]; var setDetailReq = _detail[1];
  var _dis     = useStateSupp([]);
  var dissolvingIds = _dis[0]; var setDissolvingIds = _dis[1];

  /* Escuchar solicitudes nuevas enviadas desde la vista de estudiante */
  useEffectSupp(function () {
    function onNew() { setRequests(loadSupportData()); }
    window.addEventListener('sst_support_added', onNew);
    return function () { window.removeEventListener('sst_support_added', onNew); };
  }, []);

  function updateSupportStatus(id, newStatus) {
    /* Capturar el request antes de actualizar estado */
    var req = requests.find(function (r) { return r.id === id; });

    /* Actualizar estado en lista y modal */
    setRequests(function (prev) {
      var next = prev.map(function (r) {
        return r.id === id ? Object.assign({}, r, { estado: newStatus }) : r;
      });
      saveSupportData(next);
      return next;
    });
    setDetailReq(function (prev) {
      return prev && prev.id === id ? Object.assign({}, prev, { estado: newStatus }) : prev;
    });

    /* ── Flujo automático de cierre ──────────────────────── */
    if (newStatus === 'Resuelto' && req) {
      /* 1. Notificación al estudiante */
      var notif = {
        id: 'notif_res_' + Date.now(),
        type: 'support_resolved',
        text: 'Tu solicitud de soporte "' + req.asunto + '" fue resuelta. Si necesitas más ayuda, crea una nueva solicitud.',
        time: Date.now(),
        read: false,
      };
      if (req.estudianteId && window.pushStudentNotifById) {
        window.pushStudentNotifById(req.estudianteId, notif);
      } else if (window.pushStudentNotif) {
        window.pushStudentNotif(notif);
      }

      /* 2. Toast de confirmación */
      if (window.showToast) {
        window.showToast('Solicitud marcada como resuelta. Notificación enviada al estudiante.', 'success');
      }

      /* 3. Animación de desaparición a los 2.4 s → eliminación a los 3 s */
      setTimeout(function () {
        setDissolvingIds(function (prev) { return prev.concat([id]); });
        setDetailReq(function (prev) { return prev && prev.id === id ? null : prev; });
      }, 2400);

      setTimeout(function () {
        setRequests(function (prev) {
          var next = prev.filter(function (r) { return r.id !== id; });
          saveSupportData(next);
          return next;
        });
        setDissolvingIds(function (prev) { return prev.filter(function (d) { return d !== id; }); });
      }, 3000);
    }
  }

  var pending    = requests.filter(function (r) { return r.estado === 'Pendiente'; }).length;
  var inProgress = requests.filter(function (r) { return r.estado === 'En proceso'; }).length;
  var resolved   = requests.filter(function (r) { return r.estado === 'Resuelto'; }).length;

  return (
    <div>
      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes suppRowFadeOut {
          0%   { opacity: 1;   background: #dcfce7; }
          40%  { opacity: 0.8; background: #bbf7d0; }
          100% { opacity: 0;   background: #dcfce7; }
        }
        .supp-row-dissolving {
          animation: suppRowFadeOut 0.62s ease-in forwards;
          pointer-events: none;
        }
        .supp-row-dissolving td { background: transparent !important; }
      ` }} />
      {/* Encabezado */}
      <div style={{ marginBottom: 22 }}>
        <h2 style={{ margin: '0 0 4px', fontSize: 20, fontWeight: 800, color: '#1c79b4' }}>Solicitudes de Soporte</h2>
        <p style={{ margin: 0, fontSize: 13, color: '#6b7280' }}>{requests.length} solicitud(es) registrada(s)</p>
      </div>

      {/* Chips de resumen */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 22, flexWrap: 'wrap' }}>
        <div style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: 10, padding: '11px 18px', display: 'flex', alignItems: 'center', gap: 9 }}>
          <div style={{ width: 9, height: 9, borderRadius: '50%', background: '#ef4444', flexShrink: 0 }}></div>
          <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>{pending} Pendiente{pending !== 1 ? 's' : ''}</span>
        </div>
        <div style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: 10, padding: '11px 18px', display: 'flex', alignItems: 'center', gap: 9 }}>
          <div style={{ width: 9, height: 9, borderRadius: '50%', background: '#eab308', flexShrink: 0 }}></div>
          <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>{inProgress} En proceso</span>
        </div>
        <div style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: 10, padding: '11px 18px', display: 'flex', alignItems: 'center', gap: 9 }}>
          <div style={{ width: 9, height: 9, borderRadius: '50%', background: '#22c55e', flexShrink: 0 }}></div>
          <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>{resolved} Resuelto{resolved !== 1 ? 's' : ''}</span>
        </div>
      </div>

      {/* Tabla */}
      <div style={{ background: 'white', borderRadius: 14, border: '1px solid #e5e7eb', overflow: 'hidden' }}>
        {requests.length === 0 ? (
          <div style={{ padding: '56px 24px', textAlign: 'center', color: '#9ca3af' }}>
            <div style={{ fontSize: 36, marginBottom: 10 }}>🎫</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#6b7280' }}>No hay solicitudes de soporte pendientes</div>
            <div style={{ fontSize: 12, marginTop: 4 }}>Las solicitudes de los estudiantes aparecerán aquí</div>
          </div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 720 }}>
              <thead>
                <tr style={{ background: '#f8fafc', borderBottom: '2px solid #e5e7eb' }}>
                  <th style={thSupp}>Estudiante</th>
                  <th style={thSupp}>Asunto</th>
                  <th style={thSupp}>Descripción</th>
                  <th style={thSupp}>Fecha</th>
                  <th style={thSupp}>Estado</th>
                  <th style={thSupp}>Acción</th>
                </tr>
              </thead>
              <tbody>
                {requests.map(function (req, i) {
                  var sc = supportStatusStyle(req.estado);
                  var isDissolving = dissolvingIds.indexOf(req.id) !== -1;
                  return (
                    <tr
                      key={req.id}
                      className={isDissolving ? 'supp-row-dissolving' : ''}
                      style={{ borderBottom: i < requests.length - 1 ? '1px solid #f1f5f9' : 'none', background: isDissolving ? '#f0fdf4' : 'white', transition: 'background .3s' }}
                      onMouseOver={function (e) { if (!isDissolving) e.currentTarget.style.background = '#fafbff'; }}
                      onMouseOut={function (e) { if (!isDissolving) e.currentTarget.style.background = 'white'; }}
                    >
                      <td style={tdSupp}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                          <div style={{ width: 34, height: 34, background: '#1c79b4', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#c4b400', fontSize: 13, fontWeight: 800, flexShrink: 0 }}>
                            {req.estudianteNombre.charAt(0)}
                          </div>
                          <span style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', whiteSpace: 'nowrap' }}>{req.estudianteNombre}</span>
                        </div>
                      </td>
                      <td style={tdSupp}>
                        <span style={{ fontSize: 13, color: '#374151', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', maxWidth: 190, lineHeight: 1.45 }}>{req.asunto}</span>
                      </td>
                      <td style={tdSupp}>
                        <span style={{ fontSize: 12, color: '#6b7280', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', maxWidth: 230, lineHeight: 1.45 }}>{req.descripcion}</span>
                      </td>
                      <td style={tdSupp}>
                        <span style={{ fontSize: 11, color: '#9ca3af', whiteSpace: 'nowrap' }}>{formatSupportDate(req.fecha)}</span>
                      </td>
                      <td style={tdSupp}>
                        <select
                          value={req.estado}
                          onChange={function (e) { updateSupportStatus(req.id, e.target.value); }}
                          style={{ background: sc.background, color: sc.color, border: 'none', borderRadius: 6, padding: '5px 10px', fontSize: 11, fontWeight: 700, cursor: 'pointer', fontFamily: "'Montserrat',sans-serif", outline: 'none', minWidth: 110 }}
                        >
                          <option value="Pendiente">Pendiente</option>
                          <option value="En proceso">En proceso</option>
                          <option value="Resuelto">Resuelto</option>
                        </select>
                      </td>
                      <td style={tdSupp}>
                        <button
                          onClick={function () { setDetailReq(req); }}
                          style={{ background: '#1c79b4', color: 'white', border: 'none', borderRadius: 7, padding: '8px 16px', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}
                          onMouseOver={function (e) { e.currentTarget.style.background = '#1565c0'; }}
                          onMouseOut={function (e) { e.currentTarget.style.background = '#1c79b4'; }}
                        >
                          Ver detalle
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* ── Modal detalle ─────────────────────────────────── */}
      {detailReq && (
        <div
          onClick={function () { setDetailReq(null); }}
          style={{ position: 'fixed', inset: 0, background: 'rgba(15,32,68,.45)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, fontFamily: "'Montserrat',sans-serif" }}
        >
          <div
            onClick={function (e) { e.stopPropagation(); }}
            style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 540, boxShadow: '0 24px 64px rgba(0,0,0,.22)', overflow: 'hidden' }}
          >
            {/* Cabecera */}
            <div style={{ background: '#1c79b4', padding: '20px 28px', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 10, color: '#c4b400', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 5 }}>Solicitud de Soporte</div>
                <div style={{ fontSize: 15, fontWeight: 800, color: 'white', lineHeight: 1.4 }}>{detailReq.asunto}</div>
              </div>
              <button
                onClick={function () { setDetailReq(null); }}
                style={{ background: 'rgba(255,255,255,.15)', border: 'none', borderRadius: 8, width: 34, height: 34, cursor: 'pointer', color: 'white', fontSize: 17, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, lineHeight: 1 }}
              >✕</button>
            </div>

            {/* Cuerpo */}
            <div style={{ padding: '24px 28px' }}>
              {/* Info estudiante + estado */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 22, padding: '14px 16px', background: '#f8fafc', borderRadius: 10 }}>
                <div style={{ width: 42, height: 42, background: '#1c79b4', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#c4b400', fontSize: 16, fontWeight: 800, flexShrink: 0 }}>
                  {detailReq.estudianteNombre.charAt(0)}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: '#1e293b' }}>{detailReq.estudianteNombre}</div>
                  <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 2 }}>{formatSupportDate(detailReq.fecha)}</div>
                </div>
                <select
                  value={detailReq.estado}
                  onChange={function (e) { updateSupportStatus(detailReq.id, e.target.value); }}
                  style={{
                    background: supportStatusStyle(detailReq.estado).background,
                    color: supportStatusStyle(detailReq.estado).color,
                    border: 'none', borderRadius: 6, padding: '6px 12px',
                    fontSize: 11, fontWeight: 700, cursor: 'pointer',
                    fontFamily: "'Montserrat',sans-serif", outline: 'none',
                  }}
                >
                  <option value="Pendiente">Pendiente</option>
                  <option value="En proceso">En proceso</option>
                  <option value="Resuelto">Resuelto</option>
                </select>
              </div>

              {/* Descripción */}
              <div style={{ marginBottom: 24 }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 9 }}>Descripción del problema</div>
                <div style={{ fontSize: 13, color: '#374151', lineHeight: 1.72, background: '#f8fafc', borderRadius: 10, padding: '16px 18px' }}>
                  {detailReq.descripcion}
                </div>
              </div>

              {/* Botón cerrar */}
              <button
                onClick={function () { setDetailReq(null); }}
                style={{ width: '100%', background: '#f1f5f9', color: '#374151', border: 'none', borderRadius: 10, padding: '12px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}
                onMouseOver={function (e) { e.currentTarget.style.background = '#e2e8f0'; }}
                onMouseOut={function (e) { e.currentTarget.style.background = '#f1f5f9'; }}
              >
                Cerrar
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.AdminSupport = AdminSupport;
