// TeacherPanel.jsx — panel de la profesora (solo admin). window.TeacherPanel
const { useState: useStateT, useEffect: useEffectT } = React;

function studentStats(data) {
  const S = window.CourseStore;
  const units = S.units();
  let unitsDone = 0, partsPassed = 0, finals = 0, sumNota = 0;
  units.forEach(u => {
    const up = data && data.progress && data.progress[u.slug];
    if (!up) return;
    if (up.final && up.final.passed) { unitsDone++; finals++; sumNota += (up.final.best / S.FINAL.N) * 10; }
    [1, 2, 3, 4].forEach(n => { if (up.parts && up.parts[n] && up.parts[n].passed) partsPassed++; });
  });
  return { unitsDone, partsPassed, media: finals ? (sumNota / finals) : null, total: units.length };
}
function fechaCorta(iso) {
  if (!iso) return '—';
  try { const d = new Date(iso); return d.toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: '2-digit' }); } catch (e) { return '—'; }
}

function TeacherPanel({ onBack }) {
  const C = window.ECCCloud;
  const [rows, setRows] = useStateT(null);
  const [err, setErr] = useStateT('');
  const [sel, setSel] = useStateT(null);

  const cargar = async () => {
    setErr('');
    try {
      const data = await C.adminListAll();
      setRows(data);
    } catch (e) { setErr('No se pudo cargar la lista.'); setRows([]); }
  };
  useEffectT(() => { cargar(); }, []);

  const reiniciar = async (r) => {
    const nombre = (r.data && (r.data.name || r.data.email)) || r.user_id;
    if (!confirm('¿Reiniciar el progreso de ' + nombre + '? No se puede deshacer.')) return;
    await C.adminReset(r.user_id, { email: r.data && r.data.email, name: r.data && r.data.name });
    cargar();
  };

  const total = (window.CourseStore.units() || []).length;

  return (
    <main style={{ maxWidth: 1040, margin: '0 auto', padding: '28px var(--pad-page) 80px' }}>
      <button onClick={onBack} style={{ background: 'transparent', border: 0, color: 'var(--terracotta-deep)', font: 'var(--type-ui-sm)', cursor: 'pointer', padding: 0, marginBottom: 12 }}>← Volver</button>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', marginBottom: 22 }}>
        <div>
          <div style={{ font: 'var(--type-label)', letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Panel del profesorado</div>
          <h1 style={{ font: 'var(--type-h1)', letterSpacing: 'var(--tracking-tight)', margin: '6px 0 0' }}>Alumnado</h1>
        </div>
        <button onClick={cargar} style={{ background: 'var(--bg-surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: '9px 16px', font: 'var(--type-ui-sm)', color: 'var(--ink)', cursor: 'pointer' }}>↻ Actualizar</button>
      </div>

      {err && <div style={{ font: 'var(--type-body-sm)', color: 'var(--danger)', marginBottom: 12 }}>{err}</div>}

      {rows === null ? (
        <div style={{ font: 'var(--type-body)', color: 'var(--ink-3)' }}>Cargando alumnado…</div>
      ) : rows.length === 0 ? (
        <div style={{ background: 'var(--bg-surface)', border: '1px dashed var(--line-strong)', borderRadius: 'var(--r-lg)', padding: '40px 24px', textAlign: 'center', color: 'var(--ink-2)' }}>
          <p style={{ font: 'var(--type-body)', margin: 0 }}>Todavía no hay alumnos con progreso.</p>
          <p style={{ font: 'var(--type-body-sm)', color: 'var(--ink-3)', margin: '6px 0 0' }}>Aparecerán aquí en cuanto se registren y hagan su primer cuestionario.</p>
        </div>
      ) : (
        <div style={{ background: 'var(--bg-surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1.2fr 1fr 0.9fr', background: 'var(--bg-deep)', font: 'var(--type-ui-sm)', color: 'var(--ink-2)' }}>
            {['Alumno/a', 'Unidades', 'Avance', 'Nota media', ''].map((h, i) => <div key={i} style={{ padding: '10px 14px' }}>{h}</div>)}
          </div>
          {rows.map(r => {
            const st = studentStats(r.data || {});
            const pct = Math.round((st.unitsDone / st.total) * 100);
            const nombre = (r.data && r.data.name) || '';
            const email = (r.data && r.data.email) || r.user_id;
            return (
              <div key={r.user_id} onClick={() => setSel(r)} style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1.2fr 1fr 0.9fr', borderTop: '1px solid var(--line)', alignItems: 'center', font: 'var(--type-body-sm)', color: 'var(--ink)', cursor: 'pointer' }}>
                <div style={{ padding: '12px 14px' }}>
                  <div style={{ fontWeight: 600 }}>{nombre || '(Sin nombre)'}</div>
                  <div style={{ font: 'var(--type-ui-sm)', color: 'var(--ink-2)', wordBreak: 'break-all' }}>{email}</div>
                  <div style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>act. {fechaCorta(r.updated_at)}</div>
                </div>
                <div style={{ padding: '12px 14px' }}>{st.unitsDone} / {st.total}</div>
                <div style={{ padding: '12px 14px' }}>
                  <div style={{ height: 7, background: 'var(--bg-deep)', borderRadius: 999, overflow: 'hidden', marginBottom: 4 }}>
                    <div style={{ height: '100%', width: pct + '%', background: 'var(--forest)' }} />
                  </div>
                  <span style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>{pct}% · {st.partsPassed} partes</span>
                </div>
                <div style={{ padding: '12px 14px', fontWeight: 600, color: st.media === null ? 'var(--ink-3)' : 'var(--ink)' }}>{st.media === null ? '—' : st.media.toFixed(1).replace('.', ',')}</div>
                <div style={{ padding: '12px 14px' }}>
                  <button onClick={(e) => { e.stopPropagation(); reiniciar(r); }} style={{ background: 'transparent', border: '1px solid var(--line)', color: 'var(--ink-2)', borderRadius: 'var(--r-md)', padding: '6px 10px', font: 'var(--type-ui-sm)', cursor: 'pointer' }}>Reiniciar</button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      <p style={{ font: 'var(--type-meta)', color: 'var(--ink-3)', marginTop: 16 }}>
        {rows && rows.length > 0 ? rows.length + ' alumno(s). ' : ''}Solo tú (cuenta de profesora) puedes ver esta página. Cada alumno solo ve su propio progreso.
      </p>

      {sel && <window.StudentDetail row={sel} onClose={() => setSel(null)} onChanged={cargar} />}
    </main>
  );
}

window.TeacherPanel = TeacherPanel;

// ---- Detalle de un alumno (toda su información) ----
const DETAIL_GLYPH = { bolt: '⚡', star: '★', check: '✓', flame: '🔥', trophy: '🏆' };

function StudentDetail({ row, onClose, onChanged }) {
  const S = window.CourseStore;
  const units = S.units();
  const data = row.data || {};
  const pr = data.progress || {};
  const badges = data.badges || {};
  const st = studentStats(data);
  const pct = Math.round((st.unitsDone / st.total) * 100);
  const nombre = data.name || '(Sin nombre)';
  const email = data.email || row.user_id;

  const cell = (node) => {
    if (!node || node.best === null || node.best === undefined) return { txt: '—', col: 'var(--ink-4)', sub: '' };
    const nota = (Math.round((node.best / S.PARTIAL.N) * 100) / 10).toFixed(1).replace('.', ',');
    return { txt: nota, col: node.passed ? 'var(--success)' : 'var(--danger)', sub: node.attempts ? node.attempts + ' int.' : '' };
  };
  const finalCell = (node) => {
    if (!node || node.best === null || node.best === undefined) return { txt: '—', col: 'var(--ink-4)', sub: '' };
    const nota = (Math.round((node.best / S.FINAL.N) * 100) / 10).toFixed(1).replace('.', ',');
    return { txt: nota, col: node.passed ? 'var(--success)' : 'var(--danger)', sub: node.attempts ? node.attempts + ' int.' : '' };
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(26,31,26,0.55)', zIndex: 70, overflowY: 'auto', display: 'flex', justifyContent: 'center' }}>
      <div onClick={e => e.stopPropagation()} style={{ background: 'var(--bg-canvas)', width: 'min(820px, 100%)', minHeight: '100%', padding: '0 0 60px' }}>
        <div style={{ position: 'sticky', top: 0, zIndex: 2, background: 'rgba(251,248,240,0.94)', backdropFilter: 'blur(8px)', borderBottom: '1px solid var(--line)', padding: '14px 22px', display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ font: 'var(--type-h4)', color: 'var(--ink)' }}>{nombre}</div>
            <div style={{ font: 'var(--type-meta)', color: 'var(--ink-3)', wordBreak: 'break-all' }}>{email} · última actividad {fechaCorta(row.updated_at)}</div>
          </div>
          <button onClick={onClose} style={{ border: '1px solid var(--line)', background: 'var(--bg-surface)', borderRadius: 'var(--r-md)', padding: '7px 14px', cursor: 'pointer', font: 'var(--type-ui-sm)', color: 'var(--ink-2)' }}>Cerrar</button>
        </div>

        <div style={{ padding: '22px' }}>
          {/* resumen */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 22 }}>
            {[{ k: 'Avance', v: pct + '%' }, { k: 'Unidades superadas', v: st.unitsDone + ' / ' + st.total }, { k: 'Nota media (finales)', v: st.media === null ? '—' : st.media.toFixed(1).replace('.', ',') }].map(c => (
              <div key={c.k} style={{ background: 'var(--bg-surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: '14px 16px' }}>
                <div style={{ font: 'var(--type-h3)', color: 'var(--ink)' }}>{c.v}</div>
                <div style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>{c.k}</div>
              </div>
            ))}
          </div>

          {/* insignias */}
          {Object.keys(badges).length > 0 && (
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 22 }}>
              {S.BADGES.filter(b => badges[b.id]).map(b => (
                <span key={b.id} title={b.desc} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'var(--amber-soft)', border: '1px solid var(--amber)', borderRadius: 'var(--r-pill)', padding: '5px 12px', font: 'var(--type-ui-sm)', color: 'var(--ink)' }}>
                  {DETAIL_GLYPH[b.icon] || '★'} {b.title}
                </span>
              ))}
            </div>
          )}

          {/* tabla por unidad */}
          <div style={{ background: 'var(--bg-surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', overflow: 'hidden' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr repeat(4, 1fr) 1fr', background: 'var(--bg-deep)', font: 'var(--type-ui-sm)', color: 'var(--ink-2)' }}>
              {['Unidad', 'P1', 'P2', 'P3', 'P4', 'Final'].map(h => <div key={h} style={{ padding: '9px 12px' }}>{h}</div>)}
            </div>
            {units.map(u => {
              const up = pr[u.slug] || { parts: {}, final: null };
              return (
                <div key={u.slug} style={{ display: 'grid', gridTemplateColumns: '2fr repeat(4, 1fr) 1fr', borderTop: '1px solid var(--line)', alignItems: 'center', font: 'var(--type-body-sm)' }}>
                  <div style={{ padding: '9px 12px' }}><span style={{ color: 'var(--ink-3)', font: 'var(--type-ui-sm)' }}>{u.ud}</span> {u.topic}</div>
                  {[1, 2, 3, 4].map(n => { const c = cell(up.parts && up.parts[n]); return (
                    <div key={n} style={{ padding: '9px 12px', color: c.col }}>{c.txt}{c.sub && <span style={{ font: 'var(--type-meta)', color: 'var(--ink-4)' }}> · {c.sub}</span>}</div>
                  ); })}
                  {(() => { const c = finalCell(up.final); return <div style={{ padding: '9px 12px', fontWeight: 600, color: c.col }}>{c.txt}</div>; })()}
                </div>
              );
            })}
          </div>

          <button onClick={async () => { if (confirm('¿Reiniciar TODO el progreso de ' + nombre + '?')) { await window.ECCCloud.adminReset(row.user_id, { email: data.email, name: data.name }); onClose(); if (onChanged) onChanged(); } }}
            style={{ marginTop: 18, background: 'transparent', border: '1px solid var(--line)', color: 'var(--ink-3)', borderRadius: 'var(--r-md)', padding: '9px 16px', font: 'var(--type-ui-sm)', cursor: 'pointer' }}>
            Reiniciar progreso de este alumno
          </button>
        </div>
      </div>
    </div>
  );
}

window.StudentDetail = StudentDetail;
