
const { useState, useEffect } = React;

// ─── Certificate PDF Generator ────────────────────────────────────────────────
function generateCertificatePDF(cert) {
  const lv = LEVEL[cert.level];
  const recipientName = cert.userName || 'Usuario';
  const win = window.open('', '_blank', 'width=1200,height=850');
  if (!win) return;
  win.document.write(`<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Certificado ${cert.id}</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=Outfit:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
  *{box-sizing:border-box;margin:0;padding:0}
  @page{size:A4 landscape;margin:0}
  html,body{width:297mm;height:210mm;overflow:hidden;font-family:'Outfit',sans-serif}
  body{display:flex;print-color-adjust:exact;-webkit-print-color-adjust:exact}
  .left{width:31%;background:linear-gradient(160deg,${lv.dark} 0%,${lv.color} 100%);display:flex;flex-direction:column;align-items:center;justify-content:space-between;padding:36px 24px;position:relative;overflow:hidden}
  .dots{position:absolute;inset:0;width:100%;height:100%;opacity:.08}
  .logo-text{font-family:'Space Grotesk',sans-serif;font-weight:700;font-size:22px;color:white;line-height:1;letter-spacing:-0.01em}
  .logo-sub{font-size:10px;color:rgba(255,255,255,.5);letter-spacing:.12em;text-transform:uppercase;margin-top:4px}
  .shield{width:64px;height:64px;border-radius:50%;border:2.5px solid rgba(255,255,255,.8);background:rgba(255,255,255,.1);display:flex;align-items:center;justify-content:center;margin:18px auto 0}
  .level-pill{background:${lv.color};border:2px solid rgba(255,255,255,.7);border-radius:6px;padding:8px 18px;text-align:center;margin-bottom:10px}
  .level-pill .nl{font-size:8px;color:rgba(255,255,255,.65);letter-spacing:.1em;text-transform:uppercase;font-family:'DM Mono',monospace}
  .level-pill .lv{font-family:'Space Grotesk',sans-serif;font-weight:700;font-size:13px;color:white}
  .cert-id{font-family:'DM Mono',monospace;font-size:8px;color:rgba(255,255,255,.45)}
  .right{flex:1;padding:40px 50px;display:flex;flex-direction:column;justify-content:space-between;background:white;position:relative}
  .gold-strip{position:absolute;top:0;right:0;width:62%;height:5px;background:linear-gradient(90deg,transparent,${BRAND.amber.main})}
  .eyebrow{font-size:10px;font-weight:500;letter-spacing:.15em;text-transform:uppercase;color:${BRAND.text.light};font-family:'DM Mono',monospace;margin-bottom:6px}
  .cert-type{font-family:'Space Grotesk',sans-serif;font-weight:500;font-size:12px;color:${BRAND.text.muted};letter-spacing:.06em;text-transform:uppercase;margin-bottom:4px}
  .title{font-family:'Space Grotesk',sans-serif;font-weight:700;font-size:26px;color:${BRAND.text.primary};line-height:1.1;margin-bottom:18px}
  .to-label{font-size:12px;color:${BRAND.text.muted};margin-bottom:4px}
  .recipient{font-family:'Space Grotesk',sans-serif;font-weight:700;font-size:22px;color:${lv.color};margin-bottom:14px}
  .body-text{font-size:12px;color:${BRAND.text.muted};line-height:1.75;max-width:400px;margin-bottom:20px}
  .meta{display:flex;gap:28px}
  .meta-item .mk{font-size:9px;color:${BRAND.text.light};text-transform:uppercase;letter-spacing:.08em}
  .meta-item .mv{font-size:13px;font-weight:600;color:${BRAND.text.primary}}
  .sigs{display:flex;gap:44px;border-top:1px solid ${BRAND.border};padding-top:18px}
  .sig-line{height:28px;margin-bottom:5px;border-bottom:1.5px solid ${BRAND.text.primary};width:150px}
  .sig-name{font-size:12px;font-weight:600;color:${BRAND.text.primary}}
  .sig-role{font-size:10px;color:${BRAND.text.light}}
  @media print{body{width:297mm;height:210mm}}
</style>
</head>
<body>
<div class="left">
  <svg class="dots" viewBox="0 0 200 600"><pattern id="d" width="24" height="24" patternUnits="userSpaceOnUse"><circle cx="12" cy="12" r="1.3" fill="white"/></pattern><rect width="200" height="600" fill="url(#d)"/></svg>
  <div style="position:relative;text-align:center">
    <div class="logo-text">eGuardian</div>
    <div class="logo-sub">Academia</div>
    <div class="shield">
      <svg width="32" height="36" viewBox="0 0 34 38" fill="none">
        <path d="M17 2L31 7.5V19C31 27 24.5 33.5 17 36C9.5 33.5 3 27 3 19V7.5Z" fill="rgba(255,255,255,.15)" stroke="white" stroke-width="1.5"/>
        <polyline points="10,19 14.5,24 24,13" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>
    </div>
  </div>
  <div style="position:relative;text-align:center">
    <div class="level-pill"><div class="nl">Nivel</div><div class="lv">${lv.name}</div></div>
    <div class="cert-id">${cert.id}</div>
  </div>
</div>
<div class="right">
  <div class="gold-strip"></div>
  <div>
    <div class="eyebrow">Soitel · Academia eGuardian</div>
    <div class="cert-type">Certificado de Aprobación</div>
    <h1 class="title">${cert.title}</h1>
    <div class="to-label">Otorgado a</div>
    <div class="recipient">${recipientName}</div>
    <p class="body-text">Por haber completado satisfactoriamente el curso <strong>${cert.title}</strong>, demostrando dominio de los contenidos y aprobando la evaluación con nota <strong>${cert.grade}/100</strong>.</p>
    <div class="meta">
      <div class="meta-item"><div class="mk">Fecha de emisión</div><div class="mv">${cert.date}</div></div>
      <div class="meta-item"><div class="mk">Calificación</div><div class="mv" style="color:${lv.color}">${cert.grade} / 100</div></div>
      <div class="meta-item"><div class="mk">Código del curso</div><div class="mv" style="font-family:'DM Mono',monospace;font-size:12px">${cert.code}</div></div>
    </div>
  </div>
  <div class="sigs">
    <div><div class="sig-line"></div><div class="sig-name">Miguel Salgado</div><div class="sig-role">Director Academico</div></div>
    <div><div class="sig-line"></div><div class="sig-name">Hugo Villa</div><div class="sig-role">Gerente General, Soitel</div></div>
  </div>
</div>
<script>window.onload=()=>{setTimeout(()=>window.print(),400)}</script>
</body></html>`);
  win.document.close();
}

// ─── Certificates View ────────────────────────────────────────────────────────
function formatCertificateDate(value) {
  if (!value) return 'Sin fecha';

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return String(value);

  return new Intl.DateTimeFormat('es-CL', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  }).format(date);
}

function CertificatesView({ currentUser = null }) {
  const isMobile = useViewportMatch(960);
  const isCompact = useViewportMatch(720);
  const [selected, setSelected] = useState(null);
  const [certs, setCerts] = useState([]);

  useEffect(() => {
    let cancelled = false;

    apiCall('/api/certificates')
      .then((data) => {
        if (cancelled || !Array.isArray(data)) return;

        const visibleCertificates = currentUser?.id
          ? data.filter((certificate) => Number(certificate.userId) === Number(currentUser.id))
          : data;

        const mappedCertificates = visibleCertificates.map((certificate) => ({
          id: certificate.code,
          code: certificate.course?.code || `CURSO-${certificate.courseId}`,
          title: certificate.course?.title || `Curso ${certificate.courseId}`,
          level: certificate.course?.level || 1,
          grade: certificate.score,
          date: formatCertificateDate(certificate.issuedAt),
          userName: certificate.user?.name || currentUser?.name || 'Usuario',
        }));

        setCerts(mappedCertificates);
      })
      .catch((error) => {
        console.error('No se pudieron cargar los certificados:', error);
        if (!cancelled) setCerts([]);
      });

    return () => {
      cancelled = true;
    };
  }, [currentUser]);

  if (selected) {
    const lv = LEVEL[selected.level];
    return (
      <div>
        <button onClick={() => setSelected(null)}
          style={{ display:'flex', alignItems:'center', gap:6, background:'none', border:'none',
            cursor:'pointer', color:BRAND.text.muted, fontSize:13, fontWeight:500, marginBottom:20,
            fontFamily:'Outfit,sans-serif', padding:0 }}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M10 3L5 8L10 13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          Volver a mis certificados
        </button>

        {/* A4 Certificate Preview */}
        <div style={{ maxWidth:800, margin:'0 auto', overflowX:isMobile ? 'auto' : 'visible' }}>
          <Card style={{ padding:0, overflow:'hidden', aspectRatio:isMobile ? 'auto' : '1.414/1', display:'flex', flexDirection:isMobile ? 'column' : 'row', minWidth:isMobile ? 0 : 'auto' }}>
            {/* Left column */}
            <div style={{ width:isMobile ? '100%' : '30%', background:`linear-gradient(160deg, ${lv.dark} 0%, ${lv.color} 100%)`,
              display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'space-between',
              padding:isCompact ? '28px 20px' : '40px 24px', position:'relative', overflow:'hidden' }}>
              {/* Dots */}
              <svg style={{ position:'absolute', inset:0, width:'100%', height:'100%', opacity:0.08 }}>
                {[...Array(10)].map((_,r) => [...Array(6)].map((_,c) => (
                  <circle key={`${r}-${c}`} cx={16+c*28} cy={16+r*28} r="1.5" fill="white"/>
                )))}
              </svg>
              <div style={{ position:'relative', textAlign:'center' }}>
                <Logo dark={true}/>
                <div style={{ marginTop:20, width:64, height:64, borderRadius:'50%',
                  border:'3px solid rgba(255,255,255,0.8)',
                  background:'rgba(255,255,255,0.1)',
                  display:'flex', alignItems:'center', justifyContent:'center', margin:'20px auto 0' }}>
                  <svg width="32" height="36" viewBox="0 0 34 38" fill="none">
                    <path d="M17 2L31 7.5V19C31 27 24.5 33.5 17 36C9.5 33.5 3 27 3 19V7.5Z"
                          fill="rgba(255,255,255,0.15)" stroke="white" strokeWidth="1.5"/>
                    <polyline points="10,19 14.5,24 24,13" fill="none" stroke="white" strokeWidth="2.5"
                              strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </div>
              </div>
              <div style={{ position:'relative', textAlign:'center' }}>
                <div style={{ background:`${lv.color}`, border:'2px solid rgba(255,255,255,0.6)',
                  borderRadius:6, padding:'8px 16px', marginBottom:12 }}>
                  <div style={{ fontSize:8, color:'rgba(255,255,255,0.7)', letterSpacing:'0.1em', textTransform:'uppercase', fontFamily:'DM Mono,monospace' }}>Nivel</div>
                  <div style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:14, color:'white' }}>{lv.name}</div>
                </div>
                <div style={{ fontSize:8, color:'rgba(255,255,255,0.5)', fontFamily:'DM Mono,monospace' }}>{selected.id}</div>
              </div>
            </div>

            {/* Right column */}
            <div style={{ flex:1, padding:isCompact ? '28px 20px' : isMobile ? '32px 24px' : '40px 48px', display:'flex', flexDirection:'column', justifyContent:'space-between',
              position:'relative', background:'white' }}>
              {/* Gold top strip */}
              <div style={{ position:'absolute', top:0, right:0, width:'60%', height:6,
                background:`linear-gradient(90deg, transparent, ${BRAND.amber.main})` }}/>

              <div>
                <div style={{ fontSize:11, fontWeight:500, letterSpacing:'0.15em', textTransform:'uppercase',
                  color:BRAND.text.light, marginBottom:8, fontFamily:'DM Mono,monospace' }}>
                  Soitel · Academia eGuardian
                </div>
                <div style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:300, fontSize:13, color:BRAND.text.muted,
                  letterSpacing:'0.06em', textTransform:'uppercase', marginBottom:4 }}>
                  Certificado de Aprobación
                </div>
                <h1 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:28, color:BRAND.text.primary,
                  margin:'0 0 20px', lineHeight:1.1 }}>
                  {selected.title}
                </h1>
                <div style={{ fontSize:12, color:BRAND.text.muted, marginBottom:6 }}>Otorgado a</div>
                <div style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:700, fontSize:22, color:lv.color, marginBottom:16 }}>
                  {selected.userName}
                </div>
                <p style={{ fontSize:12, color:BRAND.text.muted, lineHeight:1.7, maxWidth:380, margin:'0 0 20px' }}>
                  Por haber completado satisfactoriamente el curso <strong>{selected.title}</strong>, demostrando dominio de los contenidos y aprobando la evaluación con nota <strong>{selected.grade}/100</strong>.
                </p>
                <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : 'repeat(auto-fit, minmax(160px, 1fr))', gap:16 }}>
                  <div>
                    <div style={{ fontSize:10, color:BRAND.text.light, textTransform:'uppercase', letterSpacing:'0.08em' }}>Fecha de emisión</div>
                    <div style={{ fontSize:13, fontWeight:600, color:BRAND.text.primary }}>{selected.date}</div>
                  </div>
                  <div>
                    <div style={{ fontSize:10, color:BRAND.text.light, textTransform:'uppercase', letterSpacing:'0.08em' }}>Calificación</div>
                    <div style={{ fontSize:13, fontWeight:700, color:lv.color }}>{selected.grade} / 100</div>
                  </div>
                </div>
              </div>

              {/* Signatures */}
              <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : 'repeat(auto-fit, minmax(180px, 1fr))', gap:20, borderTop:`1px solid ${BRAND.border}`, paddingTop:20 }}>
                {[['Miguel Salgado','Director Academico'],['Hugo Villa','Gerente General, Soitel']].map(([name,role]) => (
                  <div key={name}>
                    <div style={{ height:28, marginBottom:6, borderBottom:`1.5px solid ${BRAND.text.primary}`,
                      width:140, background:`repeating-linear-gradient(-45deg, transparent, transparent 3px, ${BRAND.text.light}08 3px, ${BRAND.text.light}08 6px)` }}/>
                    <div style={{ fontSize:12, fontWeight:600, color:BRAND.text.primary }}>{name}</div>
                    <div style={{ fontSize:10, color:BRAND.text.light }}>{role}</div>
                  </div>
                ))}
              </div>
            </div>
          </Card>

          <div style={{ display:'flex', flexDirection:isCompact ? 'column' : 'row', gap:12, marginTop:16, justifyContent:'flex-end' }}>
            <button onClick={() => setSelected(null)}
              style={{ padding:'10px 20px', borderRadius:8, border:`1.5px solid ${BRAND.border}`,
                background:'white', color:BRAND.text.secondary, fontSize:13, fontWeight:500,
                cursor:'pointer', fontFamily:'Outfit,sans-serif', display:'flex', alignItems:'center', gap:6 }}>
              <Icon name="share" size={14}/> Compartir
            </button>
            <button onClick={() => generateCertificatePDF(selected)}
              style={{ padding:'10px 20px', borderRadius:8, border:'none',
                background:BRAND.green.main, color:'white', fontSize:13, fontWeight:600,
                cursor:'pointer', fontFamily:'Outfit,sans-serif', display:'flex', alignItems:'center', gap:7,
                boxShadow:'0 4px 14px rgba(27,153,112,0.3)' }}>
              <Icon name="download" size={14}/> Descargar PDF
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:24, color:BRAND.text.primary, margin:'0 0 4px' }}>
          Mis Certificados
        </h2>
        <p style={{ fontSize:14, color:BRAND.text.muted, margin:0 }}>Acreditaciones obtenidas en la Academia eGuardian</p>
      </div>

      {certs.length > 0 ? (
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(280px, 1fr))', gap:16 }}>
          {certs.map(c => {
            const lv = LEVEL[c.level];
            return (
              <Card key={c.id} style={{ padding:0, overflow:'hidden', cursor:'pointer' }}
                onClick={() => setSelected(c)}>
                <div style={{ height:8, background:`linear-gradient(90deg, ${lv.dark}, ${lv.color})` }}/>
                <div style={{ padding:20 }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:12 }}>
                    <div>
                      <span style={{ fontFamily:'DM Mono,monospace', fontSize:10, color:BRAND.text.light }}>{c.code}</span>
                      <h3 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:700, fontSize:15, color:BRAND.text.primary, margin:'4px 0 0' }}>{c.title}</h3>
                    </div>
                    <div style={{ width:44, height:44, borderRadius:'50%', background:lv.light,
                      border:`2px solid ${lv.color}30`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:20 }}><Icon name='award' size={22} color={lv.color}/></div>
                  </div>
                  <div style={{ display:'flex', gap:16, marginBottom:14 }}>
                    <div><div style={{ fontSize:10, color:BRAND.text.light }}>Calificación</div><div style={{ fontWeight:700, color:lv.color }}>{c.grade}/100</div></div>
                    <div><div style={{ fontSize:10, color:BRAND.text.light }}>Emitido</div><div style={{ fontWeight:600, color:BRAND.text.primary, fontSize:13 }}>{c.date}</div></div>
                  </div>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                    <span style={{ fontFamily:'DM Mono,monospace', fontSize:10, color:BRAND.text.light }}>{c.id}</span>
                    <span style={{ fontSize:12, color:lv.color, fontWeight:500 }}>Ver certificado →</span>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      ) : (
        <Card style={{ padding:48, textAlign:'center' }}>
          <div style={{ marginBottom:16 }}><Icon name="scroll" size={40} color={BRAND.text.light}/></div>
          <div style={{ fontSize:16, fontWeight:600, color:BRAND.text.primary, marginBottom:6 }}>Aún no tienes certificados</div>
          <p style={{ fontSize:13, color:BRAND.text.muted }}>Completa cursos para obtener tus primeras acreditaciones.</p>
        </Card>
      )}
    </div>
  );
}

// ─── Badges View ──────────────────────────────────────────────────────────────
function BadgesView() {
  const isCompact = useViewportMatch(720);
  const allBadges = [
    { type:'nv1', earned:true }, { type:'nv2', earned:false },
    { type:'nv3', earned:false }, { type:'nv4', earned:false },
    { type:'week1', earned:true }, { type:'streak14', earned:false },
    { type:'certs5', earned:false }, { type:'top', earned:false },
  ];
  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:24, color:BRAND.text.primary, margin:'0 0 4px' }}>
          Logros e Insignias
        </h2>
        <p style={{ fontSize:14, color:BRAND.text.muted, margin:0 }}>
          {allBadges.filter(b=>b.earned).length} de {allBadges.length} logros obtenidos
        </p>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : 'repeat(auto-fit, minmax(190px, 1fr))', gap:16, marginBottom:24 }}>
        <StatCard label="Obtenidos" value={allBadges.filter(b=>b.earned).length} sub={`de ${allBadges.length} disponibles`} color={BRAND.green.main} icon="award"/>
        <StatCard label="En progreso" value="3" sub="cerca de obtener" color={BRAND.amber.main} icon="clock"/>
        <StatCard label="Racha actual" value="7 días" sub="continúa así" color={BRAND.red.main} icon="fire"/>
      </div>
      <Card style={{ padding:32 }}>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(140px, 1fr))', gap:isCompact ? 20 : 32 }}>
          {allBadges.map(b => <AchievementBadge key={b.type} type={b.type} earned={b.earned}/>)}
        </div>
      </Card>
    </div>
  );
}

// ─── Users View ───────────────────────────────────────────────────────────────
function UsersView() {
  const isCompact = useViewportMatch(720);
  const [search, setSearch] = useState('');
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showUserForm, setShowUserForm] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const userRole = typeof window !== 'undefined' ? localStorage.getItem('eg_role') : null;
  const isAdmin = userRole === 'admin';

  const loadUsers = () => {
    setLoading(true);
    setError(null);
    apiCall('/api/users')
      .then(data => {
        if (data.error) {
          setError(data.error);
          setUsers([]);
        } else {
          setUsers(data || []);
        }
      })
      .catch(err => {
        console.error('Error cargando usuarios:', err);
        setError('No se pudieron cargar los usuarios');
        setUsers([]);
      })
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    loadUsers();
  }, []);

  const openCreateForm = () => {
    setEditingUser(null);
    setShowUserForm(true);
  };

  const openEditForm = (user) => {
    setEditingUser(user);
    setShowUserForm(true);
  };

  const closeUserForm = () => {
    setShowUserForm(false);
    setEditingUser(null);
  };

  const handleSaveUser = async (formData) => {
    setError(null);

    const payload = {
      name: formData.name,
      email: formData.email,
      role: formData.role,
      level: formData.level ? Number(formData.level) : null,
      avatarInitials: formData.avatarInitials || undefined,
      isActive: formData.isActive,
      ...(formData.password ? { password: formData.password } : {}),
    };

    const response = editingUser
      ? await apiCall(`/api/users/${editingUser.id}`, {
          method: 'PATCH',
          body: JSON.stringify(payload),
        })
      : await apiCall('/api/users', {
          method: 'POST',
          body: JSON.stringify(payload),
        });

    if (response.error) {
      setError(response.error);
      throw new Error(response.error);
    }

    closeUserForm();
    loadUsers();
  };

  const promptCreateUser = async () => {
    const name = window.prompt('Nombre del usuario:');
    if (!name) return;
    const email = window.prompt('Email del usuario:');
    if (!email) return;
    const password = window.prompt('Contraseña inicial (mínimo 4 caracteres):');
    if (!password) return;
    const role = (window.prompt('Rol: OPERATOR, SUPERVISOR o ADMIN', 'OPERATOR') || 'OPERATOR').toUpperCase();
    const levelInput = window.prompt('Nivel: 1, 2, 3, 4 o dejar vacío', '');
    const avatarInitials = window.prompt('Iniciales (opcional):', '') || undefined;
    const response = await apiCall('/api/users', {
      method: 'POST',
      body: JSON.stringify({
        name,
        email,
        password,
        role,
        level: levelInput ? Number(levelInput) : null,
        avatarInitials,
        isActive: true,
      }),
    });

    if (response.error) {
      setError(response.error);
      return;
    }

    loadUsers();
  };

  const promptEditUser = async (user) => {
    const name = window.prompt('Nombre del usuario:', user.name);
    if (!name) return;
    const email = window.prompt('Email del usuario:', user.email);
    if (!email) return;
    const role = (window.prompt('Rol: OPERATOR, SUPERVISOR o ADMIN', user.role) || user.role).toUpperCase();
    const levelInput = window.prompt('Nivel: 1, 2, 3, 4 o dejar vacío', user.level ? String(user.level) : '');
    const avatarInitials = window.prompt('Iniciales (opcional):', user.avatarInitials || '') || undefined;
    const isActive = window.confirm('Aceptar = usuario activo. Cancelar = usuario inactivo.');
    const password = window.prompt('Nueva contraseña (dejar vacío para mantener la actual):', '') || undefined;

    const payload = {
      name,
      email,
      role,
      level: levelInput ? Number(levelInput) : null,
      avatarInitials,
      isActive,
      ...(password ? { password } : {}),
    };

    const response = await apiCall(`/api/users/${user.id}`, {
      method: 'PATCH',
      body: JSON.stringify(payload),
    });

    if (response.error) {
      setError(response.error);
      return;
    }

    loadUsers();
  };

  const handleDeleteUser = async (user) => {
    if (!window.confirm(`¿Eliminar a ${user.name}?`)) return;

    const response = await apiCall(`/api/users/${user.id}`, {
      method: 'DELETE',
    });

    if (response.error) {
      setError(response.error);
      return;
    }

    loadUsers();
  };

  const roleMap = { OPERATOR: 'Operador', SUPERVISOR: 'Supervisor', ADMIN: 'Administrador' };
  const filtered = users.filter(u => !search || u.name.toLowerCase().includes(search.toLowerCase()) || u.email.includes(search));
  const operatorCount = users.filter(u => u.role === 'OPERATOR').length;
  const supervisorCount = users.filter(u => u.role === 'SUPERVISOR').length;

  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:isCompact ? 'stretch' : 'flex-start', flexDirection:isCompact ? 'column' : 'row', gap:12, marginBottom:24 }}>
        <div>
          <h2 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:24, color:BRAND.text.primary, margin:'0 0 4px' }}>Gestión de Usuarios</h2>
          <p style={{ fontSize:14, color:BRAND.text.muted, margin:0 }}>{users.length} usuarios registrados</p>
        </div>
        {isAdmin && (
          <button style={{ padding:'10px 18px', borderRadius:8, border:'none', background:BRAND.green.main,
            color:'white', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'Outfit,sans-serif',
            display:'flex', alignItems:'center', gap:6 }}
            onClick={openCreateForm}>
            + Nuevo usuario
          </button>
        )}
      </div>

      <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : 'repeat(auto-fit, minmax(190px, 1fr))', gap:16, marginBottom:20 }}>
        <StatCard label="Total usuarios" value={users.length} color={BRAND.green.main} icon="users"/>
        <StatCard label="Operadores" value={operatorCount} color={BRAND.blue.main} icon="user"/>
        <StatCard label="Supervisores" value={supervisorCount} color={BRAND.amber.main} icon="star"/>
        <StatCard label="Administradores" value={users.filter(u=>u.role==='ADMIN').length} color={BRAND.red.main} icon="alert"/>
      </div>

      <Card style={{ padding:24 }}>
        {loading ? (
          <div style={{ textAlign:'center', padding:'32px', color:BRAND.text.muted }}>Cargando usuarios...</div>
        ) : error ? (
          <div style={{ textAlign:'center', padding:'32px', color:BRAND.red.main }}>Error: {error}</div>
        ) : users.length === 0 ? (
          <div style={{ textAlign:'center', padding:'32px', color:BRAND.text.muted }}>No hay usuarios registrados</div>
        ) : (
          <>
            <div style={{ display:'flex', alignItems:'center', gap:8, background:BRAND.bg, border:`1.5px solid ${BRAND.border}`,
              borderRadius:8, padding:'8px 12px', width:isCompact ? '100%' : 260, marginBottom:16 }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <circle cx="6" cy="6" r="4.5" stroke={BRAND.text.light} strokeWidth="1.5"/>
            <line x1="9.5" y1="9.5" x2="13" y2="13" stroke={BRAND.text.light} strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Buscar usuario..."
            style={{ border:'none', background:'transparent', outline:'none', fontSize:13, fontFamily:'Outfit,sans-serif', width:'100%' }}/>
        </div>
        <div style={{ overflowX:'auto' }}>
        <table style={{ width:'100%', minWidth:isCompact ? 640 : '100%', borderCollapse:'collapse' }}>
          <thead>
            <tr style={{ borderBottom:`1.5px solid ${BRAND.border}` }}>
              {['Usuario','Rol','Nivel','Ingreso', ...(isAdmin ? ['Acciones'] : [])].map(h => (
                <th key={h} style={{ textAlign:'left', fontSize:11, fontWeight:500, color:BRAND.text.light,
                  padding:'0 10px 10px', letterSpacing:'0.04em', textTransform:'uppercase' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.map((u) => {
              const lv = LEVEL[u.level || 1];
              const createdDate = u.createdAt ? new Date(u.createdAt).toLocaleDateString('es-CL') : 'N/A';
              return (
                <tr key={u.id} style={{ borderBottom:`1px solid ${BRAND.border}` }}
                  onMouseEnter={e => e.currentTarget.style.background='#FAFBFA'}
                  onMouseLeave={e => e.currentTarget.style.background='transparent'}>
                  <td style={{ padding:'12px 10px' }}>
                    <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                      <div style={{ width:32, height:32, borderRadius:'50%', background:lv.light,
                        display:'flex', alignItems:'center', justifyContent:'center',
                        fontSize:12, fontWeight:700, color:lv.color, flexShrink:0 }}>
                        {u.avatarInitials || u.name.split(' ').map(n=>n[0]).join('').slice(0,2)}
                      </div>
                      <div>
                        <div style={{ fontSize:13, fontWeight:600, color:BRAND.text.primary }}>{u.name}</div>
                        <div style={{ fontSize:11, color:BRAND.text.light }}>{u.email}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding:'12px 10px', fontSize:12, color:BRAND.text.muted }}>{roleMap[u.role] || u.role}</td>
                  <td style={{ padding:'12px 10px' }}>
                    <span style={{ fontSize:11, fontWeight:600, padding:'2px 8px', borderRadius:5, background:lv.light, color:lv.color }}>NV{u.level || 1}</span>
                  </td>
                  <td style={{ padding:'12px 10px', fontSize:11, color:BRAND.text.muted, fontFamily:'DM Mono,monospace' }}>{createdDate}</td>
                  {isAdmin && (
                    <td style={{ padding:'12px 10px' }}>
                      <div style={{ display:'flex', gap:10 }}>
                        <button
                          onClick={() => openEditForm(u)}
                          style={{ border:'none', background:'none', color:BRAND.green.main, cursor:'pointer', fontSize:12, fontWeight:600 }}>
                          Editar
                        </button>
                        <button
                          onClick={() => handleDeleteUser(u)}
                          style={{ border:'none', background:'none', color:BRAND.red.main, cursor:'pointer', fontSize:12, fontWeight:600 }}>
                          Eliminar
                        </button>
                      </div>
                    </td>
                  )}
                </tr>
              );
            })}
          </tbody>
        </table>
        </div>
          </>
        )}
      </Card>

      {showUserForm && (
        <UserFormModal
          user={editingUser}
          onClose={closeUserForm}
          onSave={handleSaveUser}
        />
      )}
    </div>
  );
}

// ─── Grades View ──────────────────────────────────────────────────────────────
function UserFormModal({ user, onClose, onSave }) {
  const isCompact = useViewportMatch(720);
  const [formData, setFormData] = useState({
    name: user?.name || '',
    email: user?.email || '',
    password: '',
    role: user?.role || 'OPERATOR',
    level: user?.level ? String(user.level) : '',
    avatarInitials: user?.avatarInitials || '',
    isActive: user?.isActive ?? true,
  });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  const updateField = (key, value) => setFormData((current) => ({ ...current, [key]: value }));

  const handleSubmit = async (event) => {
    event.preventDefault();
    setSaving(true);
    setError(null);

    try {
      await onSave(formData);
    } catch (submitError) {
      console.error('Error guardando usuario:', submitError);
      setError('No se pudo guardar el usuario.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(14,31,24,0.45)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:2000, padding:24 }}>
      <div style={{ width:'100%', maxWidth:560, background:'#fff', border:`1.5px solid ${BRAND.border}`, borderRadius:20, boxShadow:'0 24px 80px rgba(14,31,24,0.22)', overflow:'hidden' }}>
        <div style={{ padding:'22px 24px 18px', borderBottom:`1px solid ${BRAND.border}`, background:'linear-gradient(135deg, #F8FCFA, #EEF7F2)' }}>
          <div style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:22, color:BRAND.text.primary }}>
            {user ? 'Editar usuario' : 'Nuevo usuario'}
          </div>
          <div style={{ marginTop:6, fontSize:13, color:BRAND.text.muted }}>
            {user ? 'Actualiza permisos, acceso y datos del usuario.' : 'Completa todos los datos para crear un nuevo usuario.'}
          </div>
        </div>

        <form onSubmit={handleSubmit} style={{ padding:isCompact ? 18 : 24, display:'grid', gap:16 }}>
          <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : '1fr 1fr', gap:14 }}>
            <label style={{ display:'grid', gap:6 }}>
              <span style={{ fontSize:12, fontWeight:600, color:BRAND.text.muted }}>Nombre</span>
              <input type="text" required value={formData.name} onChange={(e) => updateField('name', e.target.value)}
                style={{ border:`1.5px solid ${BRAND.border}`, borderRadius:10, padding:'11px 12px', fontSize:14, outline:'none' }} />
            </label>
            <label style={{ display:'grid', gap:6 }}>
              <span style={{ fontSize:12, fontWeight:600, color:BRAND.text.muted }}>Correo</span>
              <input type="email" required value={formData.email} onChange={(e) => updateField('email', e.target.value)}
                style={{ border:`1.5px solid ${BRAND.border}`, borderRadius:10, padding:'11px 12px', fontSize:14, outline:'none' }} />
            </label>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : '1fr 1fr', gap:14 }}>
            <label style={{ display:'grid', gap:6 }}>
              <span style={{ fontSize:12, fontWeight:600, color:BRAND.text.muted }}>{user ? 'Nueva contraseña' : 'Contraseña'}</span>
              <input type="password" required={!user} placeholder={user ? 'Dejar vacío para mantener actual' : ''} value={formData.password} onChange={(e) => updateField('password', e.target.value)}
                style={{ border:`1.5px solid ${BRAND.border}`, borderRadius:10, padding:'11px 12px', fontSize:14, outline:'none' }} />
            </label>
            <label style={{ display:'grid', gap:6 }}>
              <span style={{ fontSize:12, fontWeight:600, color:BRAND.text.muted }}>Iniciales</span>
              <input type="text" maxLength={4} value={formData.avatarInitials} onChange={(e) => updateField('avatarInitials', e.target.value.toUpperCase())}
                style={{ border:`1.5px solid ${BRAND.border}`, borderRadius:10, padding:'11px 12px', fontSize:14, outline:'none' }} />
            </label>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : '1fr 1fr 1fr', gap:14 }}>
            <label style={{ display:'grid', gap:6 }}>
              <span style={{ fontSize:12, fontWeight:600, color:BRAND.text.muted }}>Rol</span>
              <select value={formData.role} onChange={(e) => updateField('role', e.target.value)}
                style={{ border:`1.5px solid ${BRAND.border}`, borderRadius:10, padding:'11px 12px', fontSize:14, outline:'none', background:'#fff' }}>
                <option value="OPERATOR">Operador</option>
                <option value="SUPERVISOR">Supervisor</option>
                <option value="ADMIN">Administrador</option>
              </select>
            </label>
            <label style={{ display:'grid', gap:6 }}>
              <span style={{ fontSize:12, fontWeight:600, color:BRAND.text.muted }}>Nivel</span>
              <select value={formData.level} onChange={(e) => updateField('level', e.target.value)}
                style={{ border:`1.5px solid ${BRAND.border}`, borderRadius:10, padding:'11px 12px', fontSize:14, outline:'none', background:'#fff' }}>
                <option value="">Sin nivel</option>
                <option value="1">Nivel 1</option>
                <option value="2">Nivel 2</option>
                <option value="3">Nivel 3</option>
                <option value="4">Nivel 4</option>
              </select>
            </label>
            <label style={{ display:'flex', alignItems:'end', gap:10, paddingBottom:12, fontSize:13, color:BRAND.text.primary }}>
              <input type="checkbox" checked={formData.isActive} onChange={(e) => updateField('isActive', e.target.checked)} />
              Usuario activo
            </label>
          </div>

          {error && (
            <div style={{ border:`1px solid ${BRAND.red.main}33`, background:BRAND.red.light, color:BRAND.red.dark, borderRadius:10, padding:'10px 12px', fontSize:13 }}>
              {error}
            </div>
          )}

          <div style={{ display:'flex', flexDirection:isCompact ? 'column-reverse' : 'row', justifyContent:'flex-end', gap:10, paddingTop:4 }}>
            <button type="button" onClick={onClose}
              style={{ border:`1.5px solid ${BRAND.border}`, background:'#fff', color:BRAND.text.muted, borderRadius:10, padding:'10px 14px', fontSize:13, fontWeight:600, cursor:'pointer' }}>
              Cancelar
            </button>
            <button type="submit" disabled={saving}
              style={{ border:'none', background:BRAND.green.main, color:'#fff', borderRadius:10, padding:'10px 16px', fontSize:13, fontWeight:700, cursor:'pointer', opacity:saving ? 0.7 : 1 }}>
              {saving ? 'Guardando...' : user ? 'Guardar cambios' : 'Crear usuario'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function formatGradeDate(value) {
  if (!value) return 'Sin fecha';

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return String(value);

  return new Intl.DateTimeFormat('es-CL', {
    month: 'short',
    year: 'numeric',
  }).format(date);
}

function GradesView({ currentUser = null }) {
  const isCompact = useViewportMatch(720);
  const [graded, setGraded] = useState([]);

  useEffect(() => {
    let cancelled = false;

    apiCall('/api/enrollments')
      .then((data) => {
        if (cancelled || !Array.isArray(data)) return;

        const filtered = data
          .filter((enrollment) => {
            if (currentUser?.id && Number(enrollment.userId) !== Number(currentUser.id)) return false;
            return enrollment.grade !== null && enrollment.grade !== undefined;
          })
          .map((enrollment) => ({
            id: enrollment.id,
            code: enrollment.course?.code || `CURSO-${enrollment.courseId}`,
            title: enrollment.course?.title || `Curso ${enrollment.courseId}`,
            level: enrollment.course?.level || 1,
            grade: enrollment.grade,
            status: enrollment.status,
            date: enrollment.completedAt || enrollment.updatedAt || enrollment.createdAt || null,
          }));

        setGraded(filtered);
      })
      .catch((error) => {
        console.error('No se pudieron cargar las calificaciones:', error);
        if (!cancelled) setGraded([]);
      });

    return () => {
      cancelled = true;
    };
  }, [currentUser]);

  const avg = graded.length ? Math.round(graded.reduce((a, c) => a + c.grade, 0) / graded.length) : 0;

  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:24, color:BRAND.text.primary, margin:'0 0 4px' }}>Calificaciones</h2>
        <p style={{ fontSize:14, color:BRAND.text.muted, margin:0 }}>Historial de evaluaciones y notas obtenidas</p>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : 'repeat(auto-fit, minmax(190px, 1fr))', gap:16, marginBottom:24 }}>
        <StatCard label="Promedio general" value={avg} sub="puntos sobre 100" color={BRAND.green.main} icon="star"/>
        <StatCard label="Cursos evaluados" value={graded.length} sub="con nota registrada" color={BRAND.blue.main} icon="document"/>
        <StatCard label="Nota mas alta" value={graded.length ? Math.max(...graded.map(c => c.grade)) : '?'} sub="puntuacion maxima" color={BRAND.amber.main} icon="trophy"/>
      </div>
      <Card style={{ padding:24 }}>
        {graded.length === 0 ? (
          <div style={{ textAlign:'center', padding:40, color:BRAND.text.light }}>Aun no hay calificaciones registradas.</div>
        ) : (
          <div style={{ overflowX:'auto' }}>
          <table style={{ width:'100%', minWidth:isCompact ? 620 : '100%', borderCollapse:'collapse' }}>
            <thead>
              <tr style={{ borderBottom:`1.5px solid ${BRAND.border}` }}>
                {['Curso','Nivel','Calificacion','Estado','Fecha'].map(h => (
                  <th key={h} style={{ textAlign:'left', fontSize:11, fontWeight:500, color:BRAND.text.light,
                    padding:'0 10px 10px', letterSpacing:'0.04em', textTransform:'uppercase' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {graded.map(c => {
                const lv = LEVEL[c.level];
                const passed = c.status === 'COMPLETED' || c.grade >= 70;
                return (
                  <tr key={c.id} style={{ borderBottom:`1px solid ${BRAND.border}` }}>
                    <td style={{ padding:'12px 10px' }}>
                      <div style={{ fontSize:13, fontWeight:600, color:BRAND.text.primary }}>{c.title}</div>
                      <div style={{ fontFamily:'DM Mono,monospace', fontSize:10, color:BRAND.text.light }}>{c.code}</div>
                    </td>
                    <td style={{ padding:'12px 10px' }}>
                      <span style={{ fontSize:11, fontWeight:600, padding:'2px 8px', borderRadius:5, background:lv.light, color:lv.color }}>NV{c.level}</span>
                    </td>
                    <td style={{ padding:'12px 10px' }}>
                      <span style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:18, color: c.grade >= 90 ? BRAND.green.main : c.grade >= 70 ? BRAND.amber.main : BRAND.red.main }}>
                        {c.grade}
                      </span>
                      <span style={{ fontSize:12, color:BRAND.text.light }}>/100</span>
                    </td>
                    <td style={{ padding:'12px 10px' }}>
                      <span style={{ fontSize:11, fontWeight:500, padding:'2px 8px', borderRadius:5,
                        background: passed ? BRAND.green.light : BRAND.red.light,
                        color: passed ? BRAND.green.main : BRAND.red.main }}>
                        {passed ? 'Aprobado' : 'Reprobado'}
                      </span>
                    </td>
                    <td style={{ padding:'12px 10px', fontSize:12, color:BRAND.text.muted }}>{formatGradeDate(c.date)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          </div>
        )}
      </Card>
    </div>
  );
}

// ─── Simple placeholder views ─────────────────────────────────────────────────
function ComplianceView() {
  const isCompact = useViewportMatch(720);
  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:24, color:BRAND.text.primary, margin:'0 0 4px' }}>Cumplimiento del Equipo</h2>
        <p style={{ fontSize:14, color:BRAND.text.muted, margin:0 }}>Reporte detallado de avance y cumplimiento por nivel</p>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : 'repeat(2, minmax(0, 1fr))', gap:20, marginBottom:20 }}>
        {[[1,84,BRAND.green.main],[2,60,BRAND.amber.main],[3,20,BRAND.blue.main],[4,0,BRAND.red.main]].map(([lv,val,color]) => (
          <Card key={lv} style={{ padding:24, display:'flex', flexDirection:isCompact ? 'column' : 'row', alignItems:isCompact ? 'stretch' : 'center', gap:20 }}>
            <DonutChart value={val} color={color} size={96}/>
            <div>
              <div style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:700, fontSize:15, color:BRAND.text.primary, marginBottom:4 }}>Nivel {lv} — {LEVEL[lv].name}</div>
              <div style={{ fontSize:12, color:BRAND.text.muted, marginBottom:12 }}>Equipo Turno A</div>
              <ProgressBar value={val} color={color} height={8}/>
              <div style={{ fontSize:11, color:BRAND.text.light, marginTop:4 }}>{val}% de cumplimiento</div>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function ReportsView() {
  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:24, color:BRAND.text.primary, margin:'0 0 4px' }}>Reportes</h2>
        <p style={{ fontSize:14, color:BRAND.text.muted, margin:0 }}>Análisis y exportación de datos de la plataforma</p>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(220px, 1fr))', gap:16 }}>
        {[
          { title:'Reporte de Cumplimiento', desc:'Avance por operador y nivel de certificación', icon:'bar-chart', color:BRAND.green.main },
          { title:'Reporte de Calificaciones', desc:'Notas y resultados de evaluaciones', icon:'document', color:BRAND.blue.main },
          { title:'Reporte de Actividad', desc:'Log de accesos y tiempo en plataforma', icon:'trending-up', color:BRAND.amber.main },
          { title:'Certificados Emitidos', desc:'Listado completo de certificaciones otorgadas', icon:'award', color:BRAND.red.main },
          { title:'Usuarios en Riesgo', desc:'Operadores con progreso bajo o inactivos', icon:'alert', color:BRAND.amber.dark },
          { title:'Exportar Todo', desc:'Exportar datos completos en Excel o PDF', icon:'download', color:BRAND.text.secondary },
        ].map(r => (
          <Card key={r.title} style={{ padding:20, cursor:'pointer' }}
            onMouseEnter={e=>e.currentTarget.style.borderColor=r.color}
            onMouseLeave={e=>e.currentTarget.style.borderColor=BRAND.border}>
            <div style={{ width:40, height:40, borderRadius:10, background:`${r.color}12`, display:'flex', alignItems:'center', justifyContent:'center', color:r.color, marginBottom:12 }}><Icon name={r.icon} size={20}/></div>
            <h3 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:700, fontSize:14, color:BRAND.text.primary, margin:'0 0 6px' }}>{r.title}</h3>
            <p style={{ fontSize:12, color:BRAND.text.muted, margin:'0 0 16px', lineHeight:1.5 }}>{r.desc}</p>
            <button style={{ fontSize:12, color:r.color, background:'none', border:`1px solid ${r.color}30`,
              borderRadius:6, padding:'5px 12px', cursor:'pointer', fontFamily:'Outfit,sans-serif', fontWeight:500 }}>
              Generar →
            </button>
          </Card>
        ))}
      </div>
    </div>
  );
}

function SettingsView() {
  const isCompact = useViewportMatch(880);
  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:24, color:BRAND.text.primary, margin:'0 0 4px' }}>Configuración</h2>
        <p style={{ fontSize:14, color:BRAND.text.muted, margin:0 }}>Ajustes generales de la plataforma Academia eGuardian</p>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : '240px minmax(0, 1fr)', gap:20 }}>
        <Card style={{ padding:12, height:'fit-content' }}>
          {['General','Usuarios','Notificaciones','Seguridad','Integraciones'].map((s,i) => (
            <button key={s} style={{ width:'100%', textAlign:'left', padding:'10px 12px', borderRadius:7,
              border:'none', cursor:'pointer', fontSize:13, fontWeight: i===0 ? 600 : 400,
              background: i===0 ? BRAND.green.light : 'transparent',
              color: i===0 ? BRAND.green.dark : BRAND.text.muted,
              fontFamily:'Outfit,sans-serif', marginBottom:2 }}>
              {s}
            </button>
          ))}
        </Card>
        <Card style={{ padding:24 }}>
          <h3 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:700, fontSize:15, color:BRAND.text.primary, margin:'0 0 20px' }}>Configuración general</h3>
          {[['Nombre de la plataforma','Academia eGuardian'],['Empresa','Soitel SpA'],['País','Chile'],['Zona horaria','America/Santiago (UTC-3)']].map(([label,val]) => (
            <div key={label} style={{ marginBottom:16 }}>
              <label style={{ fontSize:12, fontWeight:500, color:BRAND.text.secondary, display:'block', marginBottom:6,
                letterSpacing:'0.04em', textTransform:'uppercase' }}>{label}</label>
              <input defaultValue={val} style={{ width:'100%', padding:'10px 14px', borderRadius:8,
                border:`1.5px solid ${BRAND.border}`, fontSize:13, fontFamily:'Outfit,sans-serif',
                color:BRAND.text.primary, background:'white', outline:'none', boxSizing:'border-box' }}/>
            </div>
          ))}
          <button style={{ padding:'10px 24px', borderRadius:8, border:'none', background:BRAND.green.main,
            color:'white', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'Outfit,sans-serif' }}>
            Guardar cambios
          </button>
        </Card>
      </div>
    </div>
  );
}

function NotificationsView() {
  const notifs = [
    { title:'Evaluación disponible', desc:'La evaluación de EG103 Sistemas CCTV está lista.', time:'Hace 2 horas', type:'info', read:false },
    { title:'¡Curso completado!', desc:'Completaste EG102 Protocolos de Operación con nota 88/100.', time:'Hace 1 día', type:'success', read:false },
    { title:'Racha de 7 días', desc:'Llevas 7 días seguidos estudiando. ¡Sigue así!', time:'Hace 1 día', type:'success', read:false },
    { title:'Nuevo curso disponible', desc:'EG309 IA Aplicada a CCTV ya está disponible en el catálogo.', time:'Hace 3 días', type:'info', read:true },
    { title:'Recordatorio de inactividad', desc:'No has accedido en 2 días. Tienes módulos pendientes en EG104.', time:'Hace 4 días', type:'warning', read:true },
  ];
  const typeColor = { info:BRAND.blue.main, success:BRAND.green.main, warning:BRAND.amber.main };
  const typeIcon = { info: <Icon name='info' size={16} color={BRAND.blue.main}/>, success: <Icon name='check-circle' size={16} color={BRAND.green.main}/>, warning: <Icon name='alert' size={16} color={BRAND.amber.main}/> };
  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:24 }}>
        <div>
          <h2 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:24, color:BRAND.text.primary, margin:'0 0 4px' }}>Notificaciones</h2>
          <p style={{ fontSize:14, color:BRAND.text.muted, margin:0 }}>{notifs.filter(n=>!n.read).length} sin leer</p>
        </div>
        <button style={{ fontSize:12, color:BRAND.green.main, background:'none', border:'none', cursor:'pointer', fontWeight:500 }}>
          Marcar todas como leídas
        </button>
      </div>
      <Card style={{ padding:0, overflow:'hidden' }}>
        {notifs.map((n,i) => (
          <div key={i} style={{ display:'flex', gap:14, padding:'16px 20px',
            borderBottom: i < notifs.length-1 ? `1px solid ${BRAND.border}` : 'none',
            background: n.read ? 'white' : `${typeColor[n.type]}08` }}>
            <div style={{ flexShrink:0, marginTop:2 }}>{typeIcon[n.type]}</div>
            <div style={{ flex:1 }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:3 }}>
                <div style={{ fontSize:13, fontWeight:600, color:BRAND.text.primary }}>{n.title}</div>
                {!n.read && <div style={{ width:7, height:7, borderRadius:'50%', background:typeColor[n.type], flexShrink:0, marginTop:3 }}/>}
              </div>
              <div style={{ fontSize:12, color:BRAND.text.muted, marginBottom:4 }}>{n.desc}</div>
              <div style={{ fontSize:11, color:BRAND.text.light, fontFamily:'DM Mono,monospace' }}>{n.time}</div>
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
}

Object.assign(window, { CertificatesView, BadgesView, UsersView, ComplianceView, GradesView, ReportsView, SettingsView, NotificationsView });
