/* forum.jsx — Foro del curso ASSYST con edición, eliminación y respuestas */
const { useState: useStateForum } = React;

/* ── Storage ─────────────────────────────────────────────── */
var FORUM_ANN_KEY = 'sst_forum_announcements';
var FORUM_CMT_KEY = 'sst_forum_comments';

var SAMPLE_ANNOUNCEMENTS = [
  {
    id: 'ann_sample_1',
    author: 'Equipo ASSYST',
    text: '¡Bienvenidos al curso SG-SST! Este foro es el canal oficial de comunicación entre el equipo instructor y los estudiantes. Aquí encontrarán novedades, recordatorios y orientaciones importantes durante su proceso de formación. ¡Mucho éxito a todos!',
    date: new Date(Date.now() - 7 * 86400000).toISOString()
  },
  {
    id: 'ann_sample_2',
    author: 'Equipo ASSYST',
    text: 'Recordatorio: el Módulo 2 incluye documentos descargables esenciales para sus actividades prácticas (matrices de riesgo y formatos de inspección). Por favor revísenlos con detenimiento antes de continuar con el Módulo 3.',
    date: new Date(Date.now() - 3 * 86400000).toISOString()
  },
  {
    id: 'ann_sample_3',
    author: 'Equipo ASSYST',
    text: '¡Felicitaciones a todos los estudiantes que ya completaron el Módulo 1! Están avanzando a muy buen ritmo. Recuerden que al completar el 100% del curso recibirán su certificado de manera automática. Ante cualquier duda, escriban en los comentarios.',
    date: new Date(Date.now() - 86400000).toISOString()
  }
];

function getAnnouncements() {
  try {
    var s = localStorage.getItem(FORUM_ANN_KEY);
    if (s) {
      var p = JSON.parse(s);
      if (Array.isArray(p) && p.length > 0) return p;
    }
  } catch (e) {}
  localStorage.setItem(FORUM_ANN_KEY, JSON.stringify(SAMPLE_ANNOUNCEMENTS));
  return SAMPLE_ANNOUNCEMENTS;
}
function saveAnnouncements(list) {
  localStorage.setItem(FORUM_ANN_KEY, JSON.stringify(list));
  if (typeof window.sbSave === 'function') window.sbSave(FORUM_ANN_KEY, list);
}
function getForumComments() {
  try {
    var s = localStorage.getItem(FORUM_CMT_KEY);
    if (s) return JSON.parse(s);
  } catch (e) {}
  return {};
}
function saveForumComments(obj) {
  localStorage.setItem(FORUM_CMT_KEY, JSON.stringify(obj));
  if (typeof window.sbSave === 'function') window.sbSave(FORUM_CMT_KEY, obj);
}

/* ── Date helpers ────────────────────────────────────────── */
function fmtDate(iso) {
  var d = new Date(iso);
  return d.toLocaleDateString('es-CO', { year: 'numeric', month: 'long', day: 'numeric' }) +
    ' · ' + d.toLocaleTimeString('es-CO', { hour: '2-digit', minute: '2-digit' });
}
function fmtDateShort(iso) {
  var d = new Date(iso);
  var diff = Math.floor((Date.now() - d) / 1000);
  if (diff < 60) return 'Ahora';
  if (diff < 3600) return Math.floor(diff / 60) + ' min';
  if (diff < 86400) return Math.floor(diff / 3600) + 'h';
  return d.toLocaleDateString('es-CO', { day: 'numeric', month: 'short' });
}

/* ── Confirm Delete Modal ────────────────────────────────── */
function ConfirmModal({ message, onConfirm, onCancel }) {
  return (
    <div style={{
      position: 'fixed', inset: 0,
      background: 'rgba(15,32,68,.5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 9999, fontFamily: 'inherit'
    }}>
      <div style={{
        background: 'white', borderRadius: 16,
        padding: '30px 28px 24px',
        boxShadow: '0 24px 64px rgba(0,0,0,.22)',
        maxWidth: 340, width: '90%', textAlign: 'center'
      }}>
        <div style={{ fontSize: 28, marginBottom: 10 }}>⚠️</div>
        <div style={{ fontSize: 14, fontWeight: 700, color: '#1e293b', marginBottom: 6 }}>{message}</div>
        <div style={{ fontSize: 12, color: '#9ca3af', marginBottom: 24 }}>Esta acción no se puede deshacer.</div>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
          <button
            onClick={onCancel}
            style={{
              background: '#f1f5f9', color: '#374151', border: 'none',
              borderRadius: 9, padding: '9px 20px', fontSize: 13,
              fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
              transition: 'background .12s'
            }}
            onMouseOver={function (e) { e.currentTarget.style.background = '#e2e8f0'; }}
            onMouseOut={function (e) { e.currentTarget.style.background = '#f1f5f9'; }}
          >Cancelar</button>
          <button
            onClick={onConfirm}
            style={{
              background: '#ef4444', color: 'white', border: 'none',
              borderRadius: 9, padding: '9px 20px', fontSize: 13,
              fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
              transition: 'background .12s'
            }}
            onMouseOver={function (e) { e.currentTarget.style.background = '#dc2626'; }}
            onMouseOut={function (e) { e.currentTarget.style.background = '#ef4444'; }}
          >Sí, eliminar</button>
        </div>
      </div>
    </div>
  );
}

/* ── Small hover action button ───────────────────────────── */
function HoverBtn({ label, danger, accent, onClick }) {
  return (
    <button
      onClick={function (e) { e.stopPropagation(); onClick(); }}
      style={{
        background: '#f8fafc', color: '#9ca3af',
        border: '1px solid #f0f0f0', borderRadius: 5,
        padding: '2px 8px', fontSize: 10, fontWeight: 700,
        cursor: 'pointer', fontFamily: 'inherit',
        transition: 'all .12s', lineHeight: 1.7,
        letterSpacing: '0.02em', whiteSpace: 'nowrap'
      }}
      onMouseOver={function (e) {
        if (danger)  { e.currentTarget.style.background = '#fee2e2'; e.currentTarget.style.color = '#ef4444'; e.currentTarget.style.borderColor = '#fca5a5'; }
        else if (accent) { e.currentTarget.style.background = '#eff6ff'; e.currentTarget.style.color = '#1c79b4'; e.currentTarget.style.borderColor = '#bfdbfe'; }
        else         { e.currentTarget.style.background = '#f1f5f9'; e.currentTarget.style.color = '#374151'; e.currentTarget.style.borderColor = '#e2e8f0'; }
      }}
      onMouseOut={function (e) {
        e.currentTarget.style.background = '#f8fafc';
        e.currentTarget.style.color = '#9ca3af';
        e.currentTarget.style.borderColor = '#f0f0f0';
      }}
    >{label}</button>
  );
}

/* ── Instructor badge ────────────────────────────────────── */
function InstructorBadge({ small }) {
  return (
    <span style={{
      fontSize: small ? 8 : 9, fontWeight: 800,
      background: '#c4b400', color: '#1c3a4a',
      padding: small ? '1px 6px' : '2px 9px',
      borderRadius: 8, textTransform: 'uppercase',
      letterSpacing: '0.07em', flexShrink: 0
    }}>Instructor</span>
  );
}

/* ── Inline edit box ─────────────────────────────────────── */
function InlineEdit({ value, onChange, onSave, onCancel, rows }) {
  return (
    <div>
      <textarea
        value={value}
        onChange={function (e) { onChange(e.target.value); }}
        rows={rows || 3}
        autoFocus
        style={{
          width: '100%', border: '1.5px solid #1c79b4', borderRadius: 8,
          padding: '8px 10px', fontFamily: 'inherit', fontSize: 13,
          color: '#374151', resize: 'vertical', outline: 'none',
          lineHeight: 1.65, display: 'block', marginBottom: 8,
          transition: 'border-color .15s'
        }}
      />
      <div style={{ display: 'flex', gap: 7 }}>
        <button
          onClick={onCancel}
          style={{
            background: '#f1f5f9', color: '#374151', border: 'none',
            borderRadius: 7, padding: '6px 14px', fontSize: 12,
            fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit'
          }}
        >Cancelar</button>
        <button
          onClick={onSave}
          disabled={!value.trim()}
          style={{
            background: value.trim() ? '#1c79b4' : '#e5e7eb',
            color: value.trim() ? 'white' : '#9ca3af',
            border: 'none', borderRadius: 7, padding: '6px 14px',
            fontSize: 12, fontWeight: 700, cursor: value.trim() ? 'pointer' : 'not-allowed',
            fontFamily: 'inherit', transition: 'all .15s'
          }}
        >Guardar</button>
      </div>
    </div>
  );
}

/* ── Main ForumView ──────────────────────────────────────── */
function ForumView({ user }) {
  var isAdmin = user.rol === 'admin';

  var [announcements, setAnnouncements] = useStateForum(getAnnouncements);
  var [comments, setComments]           = useStateForum(getForumComments);
  var [newText, setNewText]             = useStateForum('');
  var [commentTexts, setCommentTexts]   = useStateForum({});
  var [openComments, setOpenComments]   = useStateForum({});

  /* NEW state */
  var [editingAnn, setEditingAnn]     = useStateForum(null); // {annId, text}
  var [editingCmt, setEditingCmt]     = useStateForum(null); // {annId, commentId, replyId|null, text}
  var [replyingTo, setReplyingTo]     = useStateForum(null); // {annId, commentId, targetUserId}
  var [replyDraft, setReplyDraft]     = useStateForum('');
  var [pending, setPending]           = useStateForum(null); // {type:'ann'|'comment'|'reply', annId, commentId?, replyId?}
  var [hovId, setHovId]               = useStateForum(null); // id of hovered item

  /* ── Publish announcement ── */
  function publish() {
    var txt = newText.trim();
    if (!txt) return;
    var ann = { id: 'ann_' + Date.now(), author: user.nombre, userId: user.id, text: txt, date: new Date().toISOString() };
    var updated = [ann].concat(announcements);
    setAnnouncements(updated);
    saveAnnouncements(updated);
    setNewText('');
    if (window.pushStudentNotifById && typeof getUsers === 'function') {
      var students = getUsers().filter(function (u) { return u.rol === 'estudiante' && u.activo; });
      var notifText = 'Nuevo anuncio del instructor: "' + txt.substring(0, 80) + (txt.length > 80 ? '…' : '') + '"';
      var ts = Date.now();
      students.forEach(function (s) {
        window.pushStudentNotifById(s.id, { id: 'notif_ann_' + ts + '_' + s.id, type: 'new_announcement', text: notifText, time: ts, read: false });
      });
    }
    if (window.showToast) window.showToast('Anuncio publicado — estudiantes notificados 📢', 'success');
  }

  /* ── Save edited announcement ── */
  function saveAnnEdit() {
    if (!editingAnn || !editingAnn.text.trim()) return;
    var updated = announcements.map(function (a) {
      return a.id === editingAnn.annId
        ? Object.assign({}, a, { text: editingAnn.text.trim(), edited: true })
        : a;
    });
    setAnnouncements(updated);
    saveAnnouncements(updated);
    setEditingAnn(null);
    if (window.showToast) window.showToast('Anuncio actualizado ✅', 'success');
  }

  /* ── Delete announcement ── */
  function deleteAnn(annId) {
    var updated = announcements.filter(function (a) { return a.id !== annId; });
    setAnnouncements(updated);
    saveAnnouncements(updated);
    setPending(null);
    if (window.showToast) window.showToast('Anuncio eliminado', 'success');
  }

  /* ── Post comment ── */
  function postComment(annId) {
    var txt = (commentTexts[annId] || '').trim();
    if (!txt) return;
    var c = {
      id: 'c_' + Date.now(),
      author: user.nombre,
      userId: user.id,
      text: txt,
      date: new Date().toISOString(),
      replies: []
    };
    var updated = Object.assign({}, comments, { [annId]: (comments[annId] || []).concat(c) });
    setComments(updated);
    saveForumComments(updated);
    setCommentTexts(Object.assign({}, commentTexts, { [annId]: '' }));

    if (!isAdmin && window.pushAdminNotif) {
      window.pushAdminNotif({
        id: 'notif_fc_' + Date.now(), type: 'forum_comment',
        text: user.nombre + ' comentó en el Foro: "' + txt.substring(0, 60) + (txt.length > 60 ? '…' : '') + '"',
        time: Date.now(), read: false
      });
    }
    /* Admin posting general comment → notify ALL active students */
    if (isAdmin && window.pushStudentNotifById && typeof getUsers === 'function') {
      var students = getUsers().filter(function (u) { return u.rol === 'estudiante' && u.activo; });
      var notifText = 'El instructor comentó en el Foro: "' + txt.substring(0, 60) + (txt.length > 60 ? '…' : '') + '"';
      var repTime = Date.now();
      students.forEach(function (s) {
        window.pushStudentNotifById(s.id, {
          id: 'notif_rep_' + repTime + '_' + s.id,
          type: 'instructor_reply',
          text: notifText,
          time: repTime,
          read: false
        });
      });
    }
    if (window.showToast) window.showToast('Comentario enviado ✅', 'success');
  }

  /* ── Save edited comment or reply ── */
  function saveCommentEdit() {
    if (!editingCmt || !editingCmt.text.trim()) return;
    var annComments = comments[editingCmt.annId] || [];
    var updated;
    if (editingCmt.replyId) {
      updated = Object.assign({}, comments, {
        [editingCmt.annId]: annComments.map(function (c) {
          if (c.id !== editingCmt.commentId) return c;
          return Object.assign({}, c, {
            replies: (c.replies || []).map(function (r) {
              return r.id !== editingCmt.replyId
                ? r
                : Object.assign({}, r, { text: editingCmt.text.trim(), edited: true });
            })
          });
        })
      });
    } else {
      updated = Object.assign({}, comments, {
        [editingCmt.annId]: annComments.map(function (c) {
          return c.id !== editingCmt.commentId
            ? c
            : Object.assign({}, c, { text: editingCmt.text.trim(), edited: true });
        })
      });
    }
    setComments(updated);
    saveForumComments(updated);
    setEditingCmt(null);
    if (window.showToast) window.showToast('Actualizado ✅', 'success');
  }

  /* ── Delete comment ── */
  function deleteComment(annId, commentId) {
    var updated = Object.assign({}, comments, {
      [annId]: (comments[annId] || []).filter(function (c) { return c.id !== commentId; })
    });
    setComments(updated);
    saveForumComments(updated);
    setPending(null);
    if (window.showToast) window.showToast('Comentario eliminado', 'success');
  }

  /* ── Post instructor reply to specific comment ── */
  function postReply() {
    if (!replyingTo || !replyDraft.trim()) return;
    var { annId, commentId, targetUserId } = replyingTo;
    var r = {
      id: 'r_' + Date.now(),
      author: user.nombre,
      userId: user.id,
      text: replyDraft.trim(),
      date: new Date().toISOString(),
      isInstructorReply: true
    };
    var updated = Object.assign({}, comments, {
      [annId]: (comments[annId] || []).map(function (c) {
        return c.id !== commentId
          ? c
          : Object.assign({}, c, { replies: (c.replies || []).concat(r) });
      })
    });
    setComments(updated);
    saveForumComments(updated);
    setReplyingTo(null);
    setReplyDraft('');
    /* Notificar SOLO al estudiante cuyo comentario fue respondido */
    if (targetUserId && window.pushStudentNotifById) {
      window.pushStudentNotifById(targetUserId, {
        id: 'notif_rep_' + Date.now() + '_' + targetUserId,
        type: 'instructor_reply',
        text: 'El instructor respondió tu comentario en el Foro.',
        time: Date.now(), read: false
      });
    }
    if (window.showToast) window.showToast('Respuesta enviada ✅', 'success');
  }

  /* ── Delete reply ── */
  function deleteReply(annId, commentId, replyId) {
    var updated = Object.assign({}, comments, {
      [annId]: (comments[annId] || []).map(function (c) {
        if (c.id !== commentId) return c;
        return Object.assign({}, c, {
          replies: (c.replies || []).filter(function (r) { return r.id !== replyId; })
        });
      })
    });
    setComments(updated);
    saveForumComments(updated);
    setPending(null);
    if (window.showToast) window.showToast('Respuesta eliminada', 'success');
  }

  function toggleComments(annId) {
    setOpenComments(function (prev) {
      return Object.assign({}, prev, { [annId]: !prev[annId] });
    });
  }

  /* ── Resolve pending delete ── */
  function resolvePending() {
    if (!pending) return;
    if (pending.type === 'ann')     deleteAnn(pending.annId);
    if (pending.type === 'comment') deleteComment(pending.annId, pending.commentId);
    if (pending.type === 'reply')   deleteReply(pending.annId, pending.commentId, pending.replyId);
  }

  /* ── Confirm message by type ── */
  function pendingMsg() {
    if (!pending) return '';
    if (pending.type === 'ann')     return '¿Seguro que quieres eliminar este anuncio?';
    if (pending.type === 'reply')   return '¿Seguro que quieres eliminar esta respuesta?';
    return '¿Seguro que quieres eliminar este comentario?';
  }

  /* ────────────────────────────────────────────────────────
     RENDER
  ─────────────────────────────────────────────────────────── */
  return (
    <div style={{ maxWidth: 700 }}>

      {/* Confirm delete modal */}
      {pending && (
        <ConfirmModal
          message={pendingMsg()}
          onConfirm={resolvePending}
          onCancel={function () { setPending(null); }}
        />
      )}

      {/* Header */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: '#c4b400', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>
          Canal de comunicación
        </div>
        <h1 style={{ margin: '0 0 4px', fontSize: 24, fontWeight: 900, color: '#1c79b4' }}>
          Foro del Curso
        </h1>
        <p style={{ margin: 0, fontSize: 13, color: '#6b7280' }}>
          {isAdmin
            ? 'Publica anuncios y gestiona la comunicación con tus estudiantes.'
            : 'Anuncios oficiales del equipo instructor.'}
        </p>
      </div>

      {/* Admin: publish new announcement */}
      {isAdmin && (
        <div style={{ background: 'white', borderRadius: 14, border: '1px solid #e5e7eb', padding: '22px 24px', marginBottom: 24, boxShadow: '0 1px 4px rgba(28,121,180,.06)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
            <div style={{ width: 32, height: 32, background: '#1c79b4', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#c4b400" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
              </svg>
            </div>
            <span style={{ fontSize: 13, fontWeight: 700, color: '#1c79b4' }}>Nuevo anuncio</span>
          </div>
          <textarea
            value={newText}
            onChange={function (e) { setNewText(e.target.value); }}
            placeholder="Escribe un anuncio para todos los estudiantes…"
            rows={4}
            style={{
              width: '100%', border: '1.5px solid #e5e7eb', borderRadius: 10,
              padding: '12px 14px', fontFamily: 'inherit', fontSize: 13,
              color: '#374151', resize: 'vertical', outline: 'none',
              lineHeight: 1.65, transition: 'border-color .15s', display: 'block'
            }}
            onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
            onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
          />
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 12 }}>
            <button
              onClick={publish}
              disabled={!newText.trim()}
              style={{
                background: newText.trim() ? '#1c79b4' : '#e5e7eb',
                color: newText.trim() ? 'white' : '#9ca3af',
                border: 'none', borderRadius: 10,
                padding: '10px 24px', fontSize: 13, fontWeight: 700,
                cursor: newText.trim() ? 'pointer' : 'not-allowed',
                fontFamily: 'inherit', transition: 'all .15s'
              }}
            >Publicar anuncio</button>
          </div>
        </div>
      )}

      {/* Empty state */}
      {announcements.length === 0 && (
        <div style={{ textAlign: 'center', padding: '56px 24px', color: '#9ca3af' }}>
          <div style={{ fontSize: 36, marginBottom: 12 }}>📭</div>
          <div style={{ fontSize: 14, fontWeight: 600 }}>No hay anuncios publicados aún.</div>
        </div>
      )}

      {/* Announcements list */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {announcements.map(function (ann) {
          var annComments  = comments[ann.id] || [];
          var commentsOpen = !!openComments[ann.id];
          var isHovAnn     = hovId === ('ann_' + ann.id);
          var isEditingAnn = editingAnn && editingAnn.annId === ann.id;

          return (
            <div key={ann.id} style={{ background: 'white', borderRadius: 14, border: '1px solid #e5e7eb', overflow: 'hidden', boxShadow: '0 1px 4px rgba(28,121,180,.05)' }}>

              {/* ── Announcement body ── */}
              <div
                style={{ padding: '20px 24px' }}
                onMouseEnter={function () { setHovId('ann_' + ann.id); }}
                onMouseLeave={function () { setHovId(null); }}
              >
                {/* Author row */}
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14, gap: 12 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <StudentAvatar userId={ann.userId} userName={ann.author} size={38} style={{ flexShrink: 0 }} />
                    <div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap' }}>
                        <span style={{ fontSize: 13, fontWeight: 700, color: '#1e293b' }}>{ann.author}</span>
                        <InstructorBadge />
                        {ann.edited && <span style={{ fontSize: 9, color: '#9ca3af', fontStyle: 'italic' }}>(editado)</span>}
                      </div>
                      <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 2 }}>{fmtDate(ann.date)}</div>
                    </div>
                  </div>

                  {/* Admin: hover edit/delete for announcements */}
                  {isAdmin && !isEditingAnn && (
                    <div style={{
                      display: 'flex', gap: 5, flexShrink: 0,
                      opacity: isHovAnn ? 1 : 0,
                      transition: 'opacity .18s',
                      pointerEvents: isHovAnn ? 'auto' : 'none'
                    }}>
                      <HoverBtn label="Editar" onClick={function () { setEditingAnn({ annId: ann.id, text: ann.text }); }} />
                      <HoverBtn label="Eliminar" danger onClick={function () { setPending({ type: 'ann', annId: ann.id }); }} />
                    </div>
                  )}
                </div>

                {/* Announcement text or inline edit */}
                {isEditingAnn ? (
                  <InlineEdit
                    value={editingAnn.text}
                    onChange={function (v) { setEditingAnn(Object.assign({}, editingAnn, { text: v })); }}
                    onSave={saveAnnEdit}
                    onCancel={function () { setEditingAnn(null); }}
                    rows={4}
                  />
                ) : (
                  <p style={{ margin: 0, fontSize: 14, color: '#374151', lineHeight: 1.75, whiteSpace: 'pre-wrap' }}>
                    {ann.text}
                  </p>
                )}
              </div>

              {/* ── Comments section ── */}
              <div style={{ borderTop: '1px solid #f1f5f9' }}>
                <button
                  onClick={function () { toggleComments(ann.id); }}
                  style={{
                    width: '100%', padding: '10px 24px',
                    background: 'transparent', border: 'none',
                    cursor: 'pointer', fontFamily: 'inherit',
                    display: 'flex', alignItems: 'center', gap: 7,
                    color: '#6b7280', fontSize: 12, fontWeight: 600,
                    transition: 'background .12s', textAlign: 'left'
                  }}
                  onMouseOver={function (e) { e.currentTarget.style.background = '#f8fafc'; }}
                  onMouseOut={function (e) { e.currentTarget.style.background = 'transparent'; }}
                >
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                  </svg>
                  {annComments.length > 0
                    ? annComments.length + (annComments.length === 1 ? ' comentario' : ' comentarios')
                    : 'Comentar'}
                  <span style={{ marginLeft: 'auto', fontSize: 10, color: '#c4b400', transition: 'transform .15s', display: 'inline-block', transform: commentsOpen ? 'rotate(180deg)' : 'none' }}>▾</span>
                </button>

                {/* Expanded comments */}
                {commentsOpen && (
                  <div style={{ background: '#fafbff', borderTop: '1px solid #f1f5f9' }}>

                    {/* ── Each comment ── */}
                    {annComments.map(function (c) {
                      var isMyComment  = c.userId === user.id;
                      var isHovC       = hovId === c.id;
                      var isEditingC   = editingCmt && editingCmt.commentId === c.id && !editingCmt.replyId;
                      var isReplyingC  = replyingTo && replyingTo.commentId === c.id;
                      /* Show action buttons on hover (but not while editing this comment) */
                      var showBtns = isHovC && !isEditingC;

                      return (
                        <div key={c.id} style={{ borderBottom: '1px solid #f1f5f9' }}>

                          {/* Main comment row */}
                          <div
                            style={{ padding: '12px 24px', display: 'flex', gap: 10, alignItems: 'flex-start' }}
                            onMouseEnter={function () { setHovId(c.id); }}
                            onMouseLeave={function () { setHovId(null); }}
                          >
                            {/* Avatar */}
                            <StudentAvatar userId={c.userId} userName={c.author} size={28} style={{ flexShrink: 0 }} />

                            <div style={{ flex: 1, minWidth: 0 }}>
                              {/* Author + action buttons row */}
                              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4, flexWrap: 'wrap' }}>
                                <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>{c.author}</span>
                                <span style={{ fontSize: 10, color: '#9ca3af' }}>{fmtDateShort(c.date)}</span>
                                {c.edited && <span style={{ fontSize: 9, color: '#9ca3af', fontStyle: 'italic' }}>(editado)</span>}

                                {/* Action buttons — appear on hover */}
                                <div style={{
                                  marginLeft: 'auto',
                                  display: 'flex', gap: 4,
                                  opacity: showBtns ? 1 : 0,
                                  transition: 'opacity .18s',
                                  pointerEvents: showBtns ? 'auto' : 'none'
                                }}>
                                  {/* Student: edit + delete OWN comments only */}
                                  {!isAdmin && isMyComment && (
                                    <>
                                      <HoverBtn label="Editar" onClick={function () {
                                        setEditingCmt({ annId: ann.id, commentId: c.id, replyId: null, text: c.text });
                                      }} />
                                      <HoverBtn label="Eliminar" danger onClick={function () {
                                        setPending({ type: 'comment', annId: ann.id, commentId: c.id });
                                      }} />
                                    </>
                                  )}

                                  {/* Admin: reply + delete ANY comment */}
                                  {isAdmin && (
                                    <>
                                      <HoverBtn label="Responder" accent onClick={function () {
                                        setReplyingTo({ annId: ann.id, commentId: c.id, targetUserId: c.userId });
                                        setReplyDraft('');
                                      }} />
                                      <HoverBtn label="Eliminar" danger onClick={function () {
                                        setPending({ type: 'comment', annId: ann.id, commentId: c.id });
                                      }} />
                                    </>
                                  )}
                                </div>
                              </div>

                              {/* Comment text or inline edit */}
                              {isEditingC ? (
                                <InlineEdit
                                  value={editingCmt.text}
                                  onChange={function (v) { setEditingCmt(Object.assign({}, editingCmt, { text: v })); }}
                                  onSave={saveCommentEdit}
                                  onCancel={function () { setEditingCmt(null); }}
                                  rows={3}
                                />
                              ) : (
                                <p style={{ margin: 0, fontSize: 13, color: '#4b5563', lineHeight: 1.6 }}>{c.text}</p>
                              )}
                            </div>
                          </div>

                          {/* ── Instructor replies (indented) ── */}
                          {(c.replies || []).map(function (r) {
                            var isMyReply   = r.userId === user.id;
                            var isHovR      = hovId === r.id;
                            var isEditingR  = editingCmt && editingCmt.replyId === r.id;
                            var showRBtns   = isHovR && !isEditingR && isAdmin && isMyReply;

                            return (
                              <div
                                key={r.id}
                                style={{
                                  padding: '10px 24px 10px 66px',
                                  borderTop: '1px solid #f5f7fb',
                                  background: 'rgba(196,180,0,.03)',
                                  position: 'relative'
                                }}
                                onMouseEnter={function () { setHovId(r.id); }}
                                onMouseLeave={function () { setHovId(null); }}
                              >
                                {/* Gold left accent line */}
                                <div style={{ position: 'absolute', left: 52, top: 0, bottom: 0, width: 2, background: 'rgba(196,180,0,.35)', borderRadius: 2 }}></div>

                                <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                                  <StudentAvatar userId={r.userId} userName={r.author} size={26} style={{ flexShrink: 0 }} />
                                  <div style={{ flex: 1, minWidth: 0 }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3, flexWrap: 'wrap' }}>
                                      <span style={{ fontSize: 11, fontWeight: 700, color: '#1e293b' }}>{r.author}</span>
                                      <InstructorBadge small />
                                      <span style={{ fontSize: 9, color: '#9ca3af' }}>{fmtDateShort(r.date)}</span>
                                      {r.edited && <span style={{ fontSize: 9, color: '#9ca3af', fontStyle: 'italic' }}>(editado)</span>}

                                      {/* Admin: edit/delete own replies */}
                                      <div style={{
                                        marginLeft: 'auto',
                                        display: 'flex', gap: 4,
                                        opacity: showRBtns ? 1 : 0,
                                        transition: 'opacity .18s',
                                        pointerEvents: showRBtns ? 'auto' : 'none'
                                      }}>
                                        <HoverBtn label="Editar" onClick={function () {
                                          setEditingCmt({ annId: ann.id, commentId: c.id, replyId: r.id, text: r.text });
                                        }} />
                                        <HoverBtn label="Eliminar" danger onClick={function () {
                                          setPending({ type: 'reply', annId: ann.id, commentId: c.id, replyId: r.id });
                                        }} />
                                      </div>
                                    </div>

                                    {/* Reply text or inline edit */}
                                    {isEditingR ? (
                                      <InlineEdit
                                        value={editingCmt.text}
                                        onChange={function (v) { setEditingCmt(Object.assign({}, editingCmt, { text: v })); }}
                                        onSave={saveCommentEdit}
                                        onCancel={function () { setEditingCmt(null); }}
                                        rows={2}
                                      />
                                    ) : (
                                      <p style={{ margin: 0, fontSize: 12, color: '#4b5563', lineHeight: 1.6 }}>{r.text}</p>
                                    )}
                                  </div>
                                </div>
                              </div>
                            );
                          })}

                          {/* ── Reply input box (admin, for specific comment) ── */}
                          {isAdmin && isReplyingC && (
                            <div style={{ padding: '12px 24px 14px 66px', background: 'rgba(196,180,0,.04)', borderTop: '1px solid #f1f5f9', position: 'relative' }}>
                              <div style={{ position: 'absolute', left: 52, top: 0, bottom: 0, width: 2, background: '#c4b400', borderRadius: 2 }}></div>
                              <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                                <div style={{ width: 26, height: 26, background: '#1c79b4', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 9, fontWeight: 800, color: '#c4b400', flexShrink: 0 }}>
                                  {user.nombre.charAt(0).toUpperCase()}
                                </div>
                                <div style={{ flex: 1 }}>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 7 }}>
                                    <span style={{ fontSize: 11, fontWeight: 700, color: '#1e293b' }}>Tu respuesta</span>
                                    <InstructorBadge small />
                                  </div>
                                  <textarea
                                    value={replyDraft}
                                    onChange={function (e) { setReplyDraft(e.target.value); }}
                                    placeholder="Escribe tu respuesta al estudiante…"
                                    rows={3}
                                    autoFocus
                                    style={{
                                      width: '100%', border: '1.5px solid #c4b400', borderRadius: 8,
                                      padding: '8px 10px', fontFamily: 'inherit', fontSize: 12,
                                      color: '#374151', resize: 'vertical', outline: 'none',
                                      lineHeight: 1.6, display: 'block', marginBottom: 8,
                                      background: 'white'
                                    }}
                                    onFocus={function (e) { e.target.style.borderColor = '#c4b400'; }}
                                    onBlur={function (e) { e.target.style.borderColor = '#c4b400'; }}
                                  />
                                  <div style={{ display: 'flex', gap: 8 }}>
                                    <button
                                      onClick={function () { setReplyingTo(null); setReplyDraft(''); }}
                                      style={{ background: '#f1f5f9', color: '#374151', border: 'none', borderRadius: 7, padding: '6px 14px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
                                    >Cancelar</button>
                                    <button
                                      onClick={postReply}
                                      disabled={!replyDraft.trim()}
                                      style={{
                                        background: replyDraft.trim() ? '#c4b400' : '#f1f5f9',
                                        color: replyDraft.trim() ? '#1c3a4a' : '#9ca3af',
                                        border: 'none', borderRadius: 7, padding: '6px 18px',
                                        fontSize: 12, fontWeight: 700,
                                        cursor: replyDraft.trim() ? 'pointer' : 'not-allowed',
                                        fontFamily: 'inherit', transition: 'all .15s'
                                      }}
                                    >Enviar respuesta</button>
                                  </div>
                                </div>
                              </div>
                            </div>
                          )}

                        </div>
                      );
                    })}

                    {/* ── New comment input ── */}
                    <div style={{ padding: '12px 24px 14px', display: 'flex', gap: 10, alignItems: 'center' }}>
                      <input
                        type="text"
                        value={commentTexts[ann.id] || ''}
                        onChange={function (e) { setCommentTexts(Object.assign({}, commentTexts, { [ann.id]: e.target.value })); }}
                        onKeyDown={function (e) { if (e.key === 'Enter') postComment(ann.id); }}
                        placeholder="Escribe un comentario… (Enter para enviar)"
                        style={{
                          flex: 1, border: '1.5px solid #e5e7eb', borderRadius: 8,
                          padding: '7px 12px', fontFamily: 'inherit', fontSize: 12,
                          color: '#374151', outline: 'none', transition: 'border-color .15s',
                          background: 'white'
                        }}
                        onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
                        onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
                      />
                      <button
                        onClick={function () { postComment(ann.id); }}
                        disabled={!(commentTexts[ann.id] || '').trim()}
                        style={{
                          background: (commentTexts[ann.id] || '').trim() ? '#c4b400' : '#f1f5f9',
                          color: (commentTexts[ann.id] || '').trim() ? '#1c3a4a' : '#9ca3af',
                          border: 'none', borderRadius: 8, padding: '7px 16px',
                          fontSize: 12, fontWeight: 700,
                          cursor: (commentTexts[ann.id] || '').trim() ? 'pointer' : 'not-allowed',
                          fontFamily: 'inherit', transition: 'all .15s', whiteSpace: 'nowrap'
                        }}
                      >Enviar</button>
                    </div>

                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.ForumView = ForumView;
