// Screens · Teacher T01 — Cohort Dashboard
// Teacher-facing cohort view: quadrant distribution + differentiated alerts feed.
// Materializes PRD Journey 3 (Dr. Cervantes) + the 4.15/5 docente signal:
// "no_gate" vs "no_submit" must be visually distinct.

const { useState } = React;

function T01CohortDashboard() {
  const [appState, set] = useAtlasState();
  const t = AtlasData.teacher;
  const c = AtlasData.cohort;

  // Aggregate debt across the 20 peers → "7h 45min" format
  const totalDebtMin = AtlasData.peers.reduce((a, p) => a + (p.debtMinutes || 0), 0);
  const hours = Math.floor(totalDebtMin / 60);
  const mins  = totalDebtMin % 60;
  const totalDebtLabel = hours > 0 ? `${hours}h ${mins}min` : `${mins}min`;
  const avgPerStudent = Math.round(totalDebtMin / c.totalStudents);

  // Animate histogram bars from 0 → final%
  const [barsLoaded, setBarsLoaded] = useState(false);
  React.useEffect(() => {
    const id = requestAnimationFrame(() => setBarsLoaded(true));
    return () => cancelAnimationFrame(id);
  }, []);

  // Reporte toast (auto-dismiss 2.5s)
  const [toast, setToast] = useState(false);
  function handleReport() {
    setToast(true);
    setTimeout(() => setToast(false), 2500);
  }

  // Map quadrant color keys to bar fill
  const barColorFor = q => ({
    'coherente-plus':  T.acc5,
    'subestima':       T.cool5,
    'coherente-minus': 'hsl(var(--atlas-paper-500))',
    'riesgo':          T.crit5,
  }[q.id] || T.paper4);

  // Render context with inline `code` → <Ref>
  function renderContext(text) {
    const parts = text.split(/(`[^`]+`)/);
    return parts.map((p, i) => {
      if (p.startsWith('`') && p.endsWith('`')) {
        return <Ref key={i}>{p.slice(1, -1)}</Ref>;
      }
      return <span key={i}>{p}</span>;
    });
  }

  // Sparkline for cohort debt trend (7 ints)
  function TrendSparkline({ data }) {
    const W = 180, H = 40, pad = 3;
    const max = Math.max(...data), min = Math.min(...data);
    const range = max - min || 1;
    const step = (W - pad * 2) / (data.length - 1);
    const pts = data.map((v, i) => [
      pad + i * step,
      H - pad - ((v - min) / range) * (H - pad * 2),
    ]);
    const d = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' ');
    const last = pts[pts.length - 1];
    return (
      <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} style={{ display: 'block' }}>
        <defs>
          <linearGradient id="t01SpGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%"   stopColor="hsl(var(--atlas-warm-600))" stopOpacity="0.15"/>
            <stop offset="100%" stopColor="hsl(var(--atlas-warm-600))" stopOpacity="0"/>
          </linearGradient>
        </defs>
        <path d={`${d} L${last[0].toFixed(1)},${H} L${pts[0][0].toFixed(1)},${H} Z`} fill="url(#t01SpGrad)"/>
        <path d={d} fill="none" stroke="hsl(var(--atlas-warm-600))" strokeWidth="1.5" strokeLinecap="round"/>
        <circle cx={last[0]} cy={last[1]} r={3} fill="hsl(var(--atlas-warm-600))"/>
      </svg>
    );
  }

  // Severity chip style
  const sevStyle = sev => {
    if (sev === 'high')   return { border: `1px solid ${T.crit5}`, color: T.crit7, background: 'hsl(var(--atlas-critical-50, var(--atlas-paper-100)))' };
    if (sev === 'medium') return { border: `1px solid ${T.warm5}`, color: T.warm7, background: T.paper1 };
    return { border: `1px solid ${T.paper4}`, color: T.ink4, background: T.paper1 };
  };
  const sevLabel = sev => ({ high: 'urgente', medium: 'atención', low: 'revisar' }[sev] || sev);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden', background: T.paper0 }}>
      {/* TopBar — teacher breadcrumb */}
      <TopBar
        left={
          <>
            <AtlasLogo/>
            <span style={{ fontFamily: T.sans, fontSize: '0.875rem', color: T.ink5 }}>
              {'  /  '}
              <span style={{ color: T.ink8, fontWeight: 500 }}>MAT-PMD</span>
              {'  ·  '}
              <span style={{ color: T.ink7 }}>{t.name}</span>
            </span>
          </>
        }
        right={
          <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 10 }}>
            <button
              onClick={handleReport}
              style={{
                fontFamily: T.sans, fontSize: '0.875rem', color: T.ink7,
                background: 'none', border: `1px solid ${T.paper4}`,
                borderRadius: 6, padding: '4px 12px', cursor: 'pointer',
              }}
            >
              Reporte semanal
            </button>
            <span style={{ fontSize: 18, color: T.ink4, cursor: 'default', userSelect: 'none' }}>⚙</span>
            {toast && (
              <div style={{
                position: 'absolute', top: 'calc(100% + 8px)', right: 0,
                background: T.ink8, color: T.paper0, fontFamily: T.sans,
                fontSize: '0.8125rem', padding: '10px 14px', borderRadius: 6,
                boxShadow: 'var(--atlas-shadow-md)', whiteSpace: 'nowrap',
                animation: 'fadeIn 180ms ease-out', zIndex: 20,
              }}>
                Se envía cada lunes 7:00am al correo institucional · Fase 2
              </div>
            )}
          </div>
        }
      />

      {/* Body */}
      <div style={{ flex: 1, overflow: 'auto', padding: '28px 32px' }}>
        {/* Header block */}
        <div style={{ marginBottom: 28, animation: 'fadeSlideUp 360ms ease-out both' }}>
          <h1 style={{
            fontFamily: T.serif, fontSize: '1.375rem', fontWeight: 500,
            color: T.ink9, margin: 0, lineHeight: 1.3,
            fontVariationSettings: '"opsz" 24',
          }}>
            Cohorte Primavera 2026 · {c.totalStudents} estudiantes
          </h1>
          <p style={{
            fontFamily: T.sans, fontSize: '0.9375rem', color: T.ink5,
            margin: '6px 0 0', lineHeight: 1.5,
          }}>
            Materia: Programación para Minería de Datos
          </p>
        </div>

        {/* Top 2-column grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 28 }}>
          {/* Card A — Cómo usan IA (quadrants histogram) */}
          <Card style={{ animation: 'fadeSlideUp 420ms ease-out 120ms both' }}>
            <div style={{
              fontFamily: T.sans, fontSize: '0.8125rem', color: T.ink5,
              textTransform: 'uppercase', letterSpacing: '0.06em',
              marginBottom: 18,
            }}>
              Cómo usan IA
            </div>

            {c.quadrants.map((q, i) => {
              const pct = (q.count / c.totalStudents) * 100;
              const barW = barsLoaded ? `${pct}%` : '0%';
              const isRisk = q.id === 'riesgo';
              return (
                <div key={q.id} style={{ marginBottom: i === c.quadrants.length - 1 ? 22 : 16 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 4 }}>
                    <span style={{
                      fontFamily: T.serif, fontSize: '1.5rem', fontWeight: 500,
                      color: T.ink9, minWidth: 28, fontVariationSettings: '"opsz" 24',
                    }}>{q.count}</span>
                    <span style={{
                      fontFamily: T.sans, fontSize: '0.9375rem', fontWeight: 600,
                      color: T.ink8,
                    }}>{q.label}</span>
                  </div>
                  <div style={{
                    fontFamily: T.sans, fontSize: '0.75rem', color: T.ink5,
                    marginBottom: 6, marginLeft: 38,
                  }}>{q.subtitle}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginLeft: 38 }}>
                    <div style={{
                      flex: 1, height: 10, background: T.paper2, borderRadius: 2,
                      overflow: 'hidden',
                    }}>
                      <div style={{
                        width: barW, height: '100%',
                        background: barColorFor(q), borderRadius: 2,
                        transition: `width 600ms cubic-bezier(0.2, 0.7, 0.2, 1) ${80 * i}ms`,
                      }}/>
                    </div>
                    {isRisk && (
                      <span style={{
                        fontFamily: T.serif, fontSize: '0.875rem', fontStyle: 'italic',
                        color: T.crit7, fontVariationSettings: '"opsz" 18',
                        whiteSpace: 'nowrap',
                      }}>
                        ← atención
                      </span>
                    )}
                  </div>
                </div>
              );
            })}

            <Btn
              onClick={() => set({ selectedStudentId: null, screen: 't02' })}
              variant="secondary"
              size="sm"
            >
              Ver todos los estudiantes →
            </Btn>
          </Card>

          {/* Card B — Deuda de la cohorte */}
          <Card style={{ animation: 'fadeSlideUp 420ms ease-out 200ms both' }}>
            <div style={{
              fontFamily: T.sans, fontSize: '0.8125rem', color: T.ink5,
              textTransform: 'uppercase', letterSpacing: '0.06em',
              marginBottom: 18,
            }}>
              Deuda de la cohorte
            </div>
            <div style={{
              fontFamily: T.serif, fontSize: '2rem', fontWeight: 500,
              color: 'hsl(var(--atlas-warm-700))', lineHeight: 1,
              marginBottom: 6, fontVariationSettings: '"opsz" 32',
            }}>
              {totalDebtLabel}
            </div>
            <div style={{
              fontFamily: T.sans, fontSize: '0.875rem', color: T.ink5,
              marginBottom: 18,
            }}>
              acumulada esta semana
            </div>

            <div style={{ marginBottom: 10 }}>
              <TrendSparkline data={c.cohortDebtTrend}/>
            </div>
            <div style={{
              fontFamily: T.sans, fontSize: '0.75rem', color: T.ink4,
              marginBottom: 22,
            }}>
              tendencia 7 días
            </div>

            <div style={{
              borderTop: `1px solid ${T.paper3}`, paddingTop: 14,
            }}>
              <div style={{
                fontFamily: T.sans, fontSize: '0.8125rem', color: T.ink5,
                marginBottom: 4,
              }}>
                promedio por estudiante
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <span style={{
                  fontFamily: T.serif, fontSize: '1.125rem', fontWeight: 500,
                  color: T.ink8, fontVariationSettings: '"opsz" 18',
                }}>
                  {avgPerStudent} min
                </span>
                <span style={{
                  fontFamily: T.sans, fontSize: '0.75rem', color: T.warm6,
                }}>
                  (↑ 4 min vs sem pasada)
                </span>
              </div>
            </div>
          </Card>
        </div>

        {/* Separator */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 14,
          margin: '10px 0 20px',
          animation: 'fadeIn 400ms ease-out 320ms both',
        }}>
          <div style={{ flex: 1, height: 1, borderTop: `1px dashed ${T.paper4}` }}/>
          <span style={{
            fontFamily: T.serif, fontSize: '1rem', color: T.ink7,
            fontVariationSettings: '"opsz" 18', fontWeight: 500,
            letterSpacing: '-0.005em',
          }}>
            Alertas accionables
          </span>
          <div style={{ flex: 1, height: 1, borderTop: `1px dashed ${T.paper4}` }}/>
        </div>

        {/* Alerts feed */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {c.alerts.map((alert, i) => (
            <AlertRow
              key={alert.id}
              alert={alert}
              index={i}
              renderContext={renderContext}
              sevStyle={sevStyle}
              sevLabel={sevLabel}
              onOpen={() => set({ selectedStudentId: alert.studentId, screen: 't02' })}
            />
          ))}
        </div>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Alert row — enforces visual distinction between no_gate and no_submit
// ───────────────────────────────────────────────────────────
function AlertRow({ alert, index, renderContext, sevStyle, sevLabel, onOpen }) {
  const [hov, setHov] = useState(false);
  const isNoGate = alert.type === 'no_gate';

  // Icon + color decision — the core of the differentiation
  // no_gate   → filled diamond ⚠, warm-600 (entregó pero no ejecutó gate)
  // no_submit → hollow circle  ○, ink-500 ghost (no entregó)
  const iconBlock = isNoGate ? (
    // filled warm diamond (SVG) — "gate pendiente"
    <div style={{
      width: 32, height: 32, flexShrink: 0,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'hsl(var(--atlas-warm-400) / 0.18)',
      border: `1px solid ${T.warm5}`,
      borderRadius: 6,
    }}>
      <svg width="14" height="14" viewBox="0 0 14 14">
        <path d="M7 1 L13 7 L7 13 L1 7 Z" fill={T.warm6}/>
      </svg>
    </div>
  ) : (
    // hollow ink circle — "no entregado"
    <div style={{
      width: 32, height: 32, flexShrink: 0,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'transparent',
      border: `1px dashed ${T.ink5}`,
      borderRadius: 6,
    }}>
      <svg width="14" height="14" viewBox="0 0 14 14">
        <circle cx="7" cy="7" r="5" fill="none" stroke={T.ink5} strokeWidth="1.5"/>
      </svg>
    </div>
  );

  const typeLabel = isNoGate ? 'gate pendiente' : 'no entregado';

  return (
    <div
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        display: 'flex', alignItems: 'flex-start', gap: 14,
        padding: '14px 12px', borderRadius: 6,
        background: hov ? T.paper1 : 'transparent',
        transition: 'background 150ms',
        borderBottom: `1px solid ${T.paper2}`,
        animation: `fadeSlideUp 320ms ease-out ${60 * index}ms both`,
      }}
    >
      {iconBlock}

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 4 }}>
          <span style={{
            fontFamily: T.sans, fontSize: '0.9375rem', fontWeight: 600, color: T.ink8,
          }}>
            {alert.student}
          </span>
          <span style={{
            fontFamily: T.mono, fontSize: '0.6875rem', fontWeight: 500,
            color: isNoGate ? T.warm7 : T.ink5,
            textTransform: 'uppercase', letterSpacing: '0.05em',
          }}>
            {typeLabel}
          </span>
          <span style={{
            fontFamily: T.mono, fontSize: '0.6875rem', fontWeight: 500,
            borderRadius: 3, padding: '2px 6px',
            ...sevStyle(alert.severity),
          }}>
            {sevLabel(alert.severity)}
          </span>
        </div>
        <div style={{
          fontFamily: T.sans, fontSize: '0.875rem', color: T.ink7,
          lineHeight: 1.55, marginBottom: 4,
        }}>
          {renderContext(alert.context)}
        </div>
        <div style={{
          fontFamily: T.mono, fontSize: '0.75rem', color: T.ink4,
        }}>
          {alert.time}
        </div>
      </div>

      <button
        onClick={onOpen}
        style={{
          fontFamily: T.sans, fontSize: '0.875rem', fontWeight: 500,
          color: hov ? T.acc7 : T.acc6,
          background: 'none', border: 'none', cursor: 'pointer',
          padding: '6px 2px', alignSelf: 'center',
          whiteSpace: 'nowrap', transition: 'color 150ms',
        }}
      >
        Abrir tarjeta →
      </button>
    </div>
  );
}

Object.assign(window, { T01CohortDashboard });
