// Screen S02a · Home ("Mis clases")
// Root screen for the logged-in student. Bridges Login/Onboarding and the per-course Dashboard.
const { useState } = React;

function S02aHome() {
  const [appState, set] = useAtlasState();

  // ── Resolve current user (default to 'mariana' if null) ──────────────────
  const currentUserId = appState.currentUserId || 'mariana';
  const user = AtlasData.users.find(u => u.id === currentUserId) || AtlasData.users.find(u => u.id === 'mariana');
  const firstName = (user?.name || 'Mariana').split(' ')[0];

  // ── Greeting adapts to hour-of-day ──────────────────────────────────────
  const h = new Date().getHours();
  const greeting = h < 12 ? 'Buenos días' : h < 19 ? 'Buenas tardes' : 'Buenas noches';

  const courses = AtlasData.courses || [];

  // ── Aggregated vistazo stats (neutral activity framing) ─────────────────
  const totalDebt = courses.reduce((acc, c) => acc + (c.openDebtMinutes || 0), 0);
  const debtCourses = courses.filter(c => (c.openDebtMinutes || 0) > 0).length;
  const submittedThisMonth = Object.values(AtlasData.sessionsByCourse || {})
    .flat()
    .filter(s => s.state === 'submitted').length;
  // Next evaluation — pick earliest deadline that's future-ish (mock: just first course with activeSessions)
  const nextEvalCourse = courses.find(c => c.activeSessions > 0) || courses[0];

  // ── Sparkline-as-bar: shows completedNodes/totalNodes as proportion ─────
  function GraphBar({ course }) {
    const pct = course.totalNodes > 0 ? course.completedNodes / course.totalNodes : 0;
    const barWidth = Math.round(140 * pct);
    const fill = course.inProgressNodes > 0
      ? 'hsl(var(--atlas-warm-500))'
      : 'hsl(var(--atlas-accent-500))';
    return (
      <svg width="140" height="24" viewBox="0 0 140 24" style={{ display: 'block' }}>
        <rect x="0" y="10" width="140" height="4" rx="2" fill={T.paper3} />
        <rect x="0" y="10" width={barWidth} height="4" rx="2" fill={fill} />
        {/* in-progress tick */}
        {course.inProgressNodes > 0 && (
          <circle cx={barWidth} cy={12} r={3} fill={fill} />
        )}
      </svg>
    );
  }

  // ── Course card ─────────────────────────────────────────────────────────
  function CourseCard({ course, index }) {
    const [hov, setHov] = useState(false);
    const borderColor = course.color === 'warm'
      ? 'hsl(var(--atlas-warm-500))'
      : course.color === 'accent'
        ? 'hsl(var(--atlas-accent-500))'
        : T.paper4;
    const hasDebt = (course.openDebtMinutes || 0) > 0;
    const isActive = (course.activeSessions || 0) > 0;

    return (
      <div
        onMouseEnter={() => setHov(true)}
        onMouseLeave={() => setHov(false)}
        onClick={() => set({ currentCourseId: course.id, screen: 'dashboard' })}
        style={{
          background: T.paper1,
          border: `1px solid ${T.paper3}`,
          borderLeft: isActive ? `3px solid ${borderColor}` : `1px solid ${T.paper3}`,
          borderRadius: 10,
          padding: 24,
          cursor: 'pointer',
          transition: 'transform 180ms ease-out, box-shadow 180ms ease-out',
          transform: hov ? 'translateY(-2px)' : 'translateY(0)',
          boxShadow: hov ? 'var(--atlas-shadow-md)' : 'var(--atlas-shadow-sm)',
          display: 'flex',
          flexDirection: 'column',
          gap: 12,
          animation: `fadeSlideUp 280ms ease-out ${index * 80}ms both`,
        }}>

        {/* Top row: chip + teacher */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <Chip>{course.code}</Chip>
          {isActive && (
            <span style={{
              fontFamily: T.sans, fontSize: '0.6875rem', fontWeight: 600,
              color: 'hsl(var(--atlas-warm-600))',
              textTransform: 'uppercase', letterSpacing: '0.06em',
            }}>
              sesión activa
            </span>
          )}
        </div>

        {/* Course name */}
        <div>
          <div style={{
            fontFamily: T.serif, fontSize: '1.125rem', fontWeight: 500,
            color: T.ink9, lineHeight: 1.3, marginBottom: 4,
            fontVariationSettings: '"opsz" 18',
          }}>
            {course.name}
          </div>
          <div style={{ fontFamily: T.sans, fontSize: '0.8125rem', color: T.ink5 }}>
            {course.teacher}
          </div>
        </div>

        {/* Meta rows */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ fontFamily: T.sans, fontSize: '0.875rem', color: T.ink7 }}>
            <span style={{ marginRight: 6 }}>⏱</span>
            {course.nextDeadline || 'sin deadline próximo'}
          </div>

          {hasDebt ? (
            <div style={{
              fontFamily: T.serif, fontSize: '1rem', fontWeight: 500,
              color: 'hsl(var(--atlas-warm-700))',
              fontVariationSettings: '"opsz" 18',
              lineHeight: 1.4,
            }}>
              {course.openDebtMinutes} min de deuda en <Ref>regresión lineal</Ref>
            </div>
          ) : (
            <div style={{ fontFamily: T.sans, fontSize: '0.875rem', color: T.ink5 }}>
              sin deuda abierta
            </div>
          )}
        </div>

        {/* Graph progression — visual only, no X/Y framing for tasks */}
        <div style={{ marginTop: 4 }}>
          <GraphBar course={course} />
          <div style={{
            fontFamily: T.mono, fontSize: '0.6875rem', color: T.ink4,
            marginTop: 6,
          }}>
            {course.completedNodes} de {course.totalNodes} nodos abiertos
          </div>
        </div>

        {/* CTA */}
        <div style={{ marginTop: 8 }}>
          <Btn
            onClick={(e) => {
              e.stopPropagation();
              set({ currentCourseId: course.id, screen: 'dashboard' });
            }}
            variant="secondary"
            size="sm"
            style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>Abrir curso</span><span>→</span>
          </Btn>
        </div>
      </div>
    );
  }

  // ── Empty state: no courses ─────────────────────────────────────────────
  if (courses.length === 0) {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <TopBar
          left={<><AtlasLogo/><span style={{ fontFamily: T.sans, fontSize: '0.875rem', color: T.ink5 }}>· mis clases</span></>}
          right={
            <button onClick={() => set({ screen: 'silencio' })}
              style={{ fontFamily: T.sans, fontSize: '0.875rem', color: T.ink5,
                background: 'none', border: `1px solid ${T.paper4}`, borderRadius: 6,
                padding: '4px 12px', cursor: 'pointer' }}>
              🔕 Silencio
            </button>
          }
        />
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40 }}>
          <div style={{ textAlign: 'center', maxWidth: 420 }}>
            <p style={{ fontFamily: T.serif, fontSize: '1.25rem', color: T.ink8, marginBottom: 12, fontVariationSettings: '"opsz" 24' }}>
              {greeting}, {firstName}.
            </p>
            <p style={{ fontFamily: T.sans, fontSize: '0.9375rem', color: T.ink5 }}>
              Aún no tienes clases activas este semestre.
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>

      {/* Top bar */}
      <TopBar
        left={
          <>
            <AtlasLogo/>
            <span style={{ fontFamily: T.sans, fontSize: '0.875rem', color: T.ink5 }}>
              · mis clases
            </span>
          </>
        }
        right={
          <>
            <button onClick={() => set({ screen: 'silencio' })}
              style={{ fontFamily: T.sans, fontSize: '0.875rem', color: T.ink5,
                background: 'none', border: `1px solid ${T.paper4}`, borderRadius: 6,
                padding: '4px 12px', cursor: 'pointer' }}>
              🔕 Modo silencio
            </button>
            <button
              style={{ fontFamily: T.sans, fontSize: '1rem', color: T.ink5,
                background: 'none', border: 'none', cursor: 'pointer', padding: '4px 6px' }}
              title="Ajustes">
              ⚙
            </button>
          </>
        }
      />

      {/* Body */}
      <div style={{ flex: 1, overflow: 'auto', padding: '32px 40px' }}>
        <div style={{ maxWidth: 880, margin: '0 auto' }}>

          {/* Greeting */}
          <div style={{ marginBottom: 32, animation: 'fadeSlideUp 240ms ease-out both' }}>
            <h1 style={{
              fontFamily: T.serif, fontSize: '1.375rem', fontWeight: 500,
              color: T.ink9, margin: '0 0 6px',
              fontVariationSettings: '"opsz" 24',
              lineHeight: 1.3,
            }}>
              {greeting}, {firstName}.
            </h1>
            <p style={{
              fontFamily: T.sans, fontSize: '0.9375rem', color: T.ink5, margin: 0,
            }}>
              Tus clases activas este semestre.
            </p>
          </div>

          {/* Course grid */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: 20,
            marginBottom: 36,
          }}>
            {courses.map((course, i) => (
              <CourseCard key={course.id} course={course} index={i} />
            ))}
          </div>

          {/* Divider */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            marginBottom: 18,
            animation: 'fadeIn 400ms ease-out 320ms both',
          }}>
            <span style={{
              fontFamily: T.sans, fontSize: '0.75rem', color: T.ink4,
              textTransform: 'uppercase', letterSpacing: '0.08em',
            }}>
              tu vistazo completo
            </span>
            <span style={{ flex: 1, height: 1, background: T.paper3 }} />
          </div>

          {/* Vistazo band */}
          <div style={{
            background: T.paper0,
            borderLeft: `3px solid ${T.paper4}`,
            borderRadius: 6,
            padding: 18,
            animation: 'fadeSlideUp 280ms ease-out 320ms both',
          }}>
            <p style={{
              fontFamily: T.sans, fontSize: '0.8125rem', color: T.ink5,
              margin: '0 0 12px',
            }}>
              Across todas las clases:
            </p>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {/* Bullet 1: debt */}
              <li style={{
                fontFamily: T.serif, fontSize: '0.9375rem', color: T.ink7,
                display: 'flex', gap: 10, alignItems: 'flex-start',
                fontVariationSettings: '"opsz" 18', lineHeight: 1.5,
              }}>
                <span style={{
                  width: 5, height: 5, borderRadius: '50%',
                  background: totalDebt > 0 ? 'hsl(var(--atlas-warm-500))' : T.paper4,
                  flexShrink: 0, marginTop: 8,
                }}/>
                {totalDebt > 0 ? (
                  <span>
                    {totalDebt} min de deuda abierta ({debtCourses === 1 ? '1 nodo' : `${debtCourses} nodos`})
                  </span>
                ) : (
                  <span>sin deuda abierta en ninguna clase</span>
                )}
              </li>

              {/* Bullet 2: raw activity count, NEVER X/Y */}
              <li style={{
                fontFamily: T.serif, fontSize: '0.9375rem', color: T.ink7,
                display: 'flex', gap: 10, alignItems: 'flex-start',
                fontVariationSettings: '"opsz" 18', lineHeight: 1.5,
              }}>
                <span style={{
                  width: 5, height: 5, borderRadius: '50%',
                  background: T.acc5, flexShrink: 0, marginTop: 8,
                }}/>
                <span>
                  {submittedThisMonth} {submittedThisMonth === 1 ? 'sesión entregada' : 'sesiones entregadas'} este mes
                </span>
              </li>

              {/* Bullet 3: upcoming evaluation */}
              <li style={{
                fontFamily: T.serif, fontSize: '0.9375rem', color: T.ink7,
                display: 'flex', gap: 10, alignItems: 'flex-start',
                fontVariationSettings: '"opsz" 18', lineHeight: 1.5,
              }}>
                <span style={{
                  width: 5, height: 5, borderRadius: '50%',
                  background: T.paper4, flexShrink: 0, marginTop: 8,
                }}/>
                <span>
                  próxima evaluación: parcial en 10 días
                  {nextEvalCourse && (
                    <span style={{ color: T.ink5 }}> · {nextEvalCourse.code}</span>
                  )}
                </span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { S02aHome });
