// Screens 05 · Contrato  +  06 · Saldo (momento de oro)  +  07 · Submit  +  08 · Reflection
const { useState, useEffect, useRef } = React;

// ═══════════════════════════════════════════════════════════
// 05 · Contrato explícito de deuda
// ═══════════════════════════════════════════════════════════
function S05Contrato() {
  const [appState, set] = useAtlasState();
  const [expanded, setExpanded] = useState(false);
  const modes = ['Cuestionario — 5 preguntas sobre el concepto', 'Modificación — cambias el código y explicas qué cambia',
    'Explicación — lo explicas en video de 1 min', 'Enseñarle a un compañero', 'Mini-problema — resuelves una variante'];

  function sign() {
    set({ debtSigned: true, screen: 'notebook' });
  }

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', overflow:'auto',
      background: `hsl(var(--atlas-paper-50))` }}>
      {/* Back */}
      <div style={{ padding:'16px 24px 0', flexShrink:0 }}>
        <button onClick={() => set({ screen: 'notebook' })}
          style={{ background:'none', border:'none', cursor:'pointer', fontFamily:T.sans, fontSize:'0.875rem', color:T.ink5, padding:0 }}>
          ← volver al notebook
        </button>
      </div>

      {/* Sheet */}
      <div style={{ flex:1, display:'flex', alignItems:'flex-end', justifyContent:'center', padding:'0 24px 24px' }}>
        <div style={{ width:'100%', maxWidth:640, background:T.paper0, borderRadius:12,
          boxShadow:'var(--atlas-shadow-xl)', padding:'40px 40px 32px',
          animation:'slideUpSheet 280ms cubic-bezier(.2,.8,.2,1) both' }}>

          <h1 style={{ fontFamily:T.serif, fontSize:'1.5rem', fontWeight:500, color:T.ink9,
            marginBottom:14, fontVariationSettings:'"opsz" 32' }}>
            Contrato de deuda cognitiva
          </h1>
          <p style={{ fontFamily:T.serif, fontSize:'1.0625rem', color:T.ink7, lineHeight:1.6,
            marginBottom:24, fontVariationSettings:'"opsz" 18' }}>
            Atlas va a resolver la regresión por ti. Lo hacemos con un trato.
          </p>

          {/* Terms card */}
          <div style={{ background:`hsl(var(--atlas-warm-400) / 0.06)`, border:`1px solid ${T.warm4}`,
            borderRadius:8, padding:'18px 20px', marginBottom:28 }}>
            <div style={{ display:'grid', gap:8 }}>
              {[
                ['Deuda anotada', <span>15 min en <Ref>regresión lineal</Ref></span>],
                ['Plazo para saldar', '48 horas'],
                ['Aviso antes del parcial', 'Con 48h de antelación'],
              ].map(([label, val]) => (
                <div key={label} style={{ display:'flex', justifyContent:'space-between', alignItems:'center',
                  fontFamily:T.sans, fontSize:'0.9375rem' }}>
                  <span style={{ color:T.ink5 }}>{label}</span>
                  <span style={{ color:T.ink9, fontWeight:500 }}>{val}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Modos */}
          <h2 style={{ fontFamily:T.serif, fontSize:'1.125rem', fontWeight:500, color:T.ink8, marginBottom:12,
            fontVariationSettings:'"opsz" 18' }}>
            Cómo puedes saldar (tú eliges, cuando quieras):
          </h2>
          <ul style={{ listStyle:'none', padding:0, marginBottom:24 }}>
            {modes.map((m, i) => (
              <li key={i} style={{ display:'flex', gap:10, alignItems:'flex-start', padding:'9px 0',
                borderBottom: i < modes.length-1 ? `1px solid ${T.paper3}` : 'none',
                fontFamily:T.sans, fontSize:'0.9375rem', color:T.ink7, lineHeight:1.5,
                animation:`fadeSlideUp 240ms ease-out ${i*50+100}ms both`,
                cursor: m.includes('Mini-problema') ? 'pointer' : 'default' }}
                onClick={m.includes('Mini-problema') ? () => set({ debtSigned:true, screen:'saldo' }) : undefined}>
                <span style={{ width:6, height:6, borderRadius:'50%', background: T.warm5,
                  flexShrink:0, marginTop:6, display:'inline-block' }}/>
                {m}
                {m.includes('Mini-problema') && <span style={{ marginLeft:'auto', color:T.warm6, fontSize:'0.75rem' }}>→ disponible</span>}
              </li>
            ))}
          </ul>

          <p style={{ fontFamily:T.serif, fontStyle:'italic', fontSize:'0.9375rem',
            color:`hsl(var(--atlas-critical-600))`, marginBottom: 24,
            fontVariationSettings:'"opsz" 14' }}>
            El tiempo no te lo perdono. Sólo la evidencia.
          </p>

          {/* Crunch */}
          <button onClick={() => setExpanded(e => !e)}
            style={{ fontFamily:T.sans, fontSize:'0.875rem', color:T.ink4, background:'none',
              border:'none', cursor:'pointer', padding:0, marginBottom:20, display:'block' }}>
            {expanded ? '▾' : '▸'} ¿Y si estoy en crunch?
          </button>
          {expanded && (
            <div style={{ background:T.paper1, borderRadius:6, padding:'12px 16px', marginBottom:20,
              fontFamily:T.sans, fontSize:'0.875rem', color:T.ink7, lineHeight:1.6 }}>
              Si tienes ≤ 4h al deadline, el contrato se diferirá automáticamente. Podrás firmarlo cuando tengas calma.
            </div>
          )}

          {/* CTA */}
          <div style={{ borderTop:`1px solid ${T.paper3}`, paddingTop:20, display:'flex', flexDirection:'column', gap:12 }}>
            <Btn onClick={sign} variant="primary" size="lg"
              style={{ width:'100%', display:'flex', justifyContent:'space-between' }}>
              <span>Acepto saldar con evidencia propia</span><span>→</span>
            </Btn>
            <button onClick={() => set({ screen:'notebook', namingChoice:'dismissed' })}
              style={{ background:'none', border:'none', cursor:'pointer', fontFamily:T.sans,
                fontSize:'0.875rem', color:T.ink4, textAlign:'center' }}>
              Cancelar y pensarlo
            </button>
          </div>

          <p style={{ fontFamily:T.sans, fontSize:'0.75rem', color:T.ink4, marginTop:16, textAlign:'center' }}>
            Versión contract@2026-04-01.v1
          </p>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// 06 · Saldo mini-problema — MOMENTO DE ORO
// ═══════════════════════════════════════════════════════════
function S06Saldo() {
  const [appState, set] = useAtlasState();
  const [answer, setAnswer] = useState('');
  const [phase, setPhase] = useState('idle'); // idle | submitting | accepted | opened
  const [animActive, setAnimActive] = useState(false);

  const minChars = 40;
  const canSubmit = answer.length >= minChars && phase === 'idle';

  function handleSubmit() {
    if (!canSubmit) return;
    setPhase('submitting');
    setTimeout(() => {
      setPhase('accepted');
      setAnimActive(true);
      setTimeout(() => {
        setPhase('opened');
        set({ saldoComplete: true });
      }, 1300);
    }, 800);
  }

  const questionText = 'Acabamos de ajustar el modelo de regresión lineal sobre el dataset de rentas. Observa que el modelo da R² = 0.731. Al examinar los residuales del modelo: ¿la linealidad es plausible? Si ves un patrón en los residuales, ¿qué transformación propondrías para corregirlo?';

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', overflow:'hidden' }}>
      <TopBar
        left={
          <>
            <button onClick={() => set({ screen:'notebook' })}
              style={{ background:'none', border:'none', cursor:'pointer', color:T.ink5, fontSize:18, padding:'0 4px' }}>←</button>
            <span style={{ fontFamily:T.sans, fontSize:'0.875rem', color:T.ink5 }}>Saldo · 15 min en reg. lineal</span>
          </>
        }
        right={<Chip style={{ color:T.warm6, borderColor:T.warm4 }}>Gate: residual_analysis</Chip>}
      />

      <div style={{ flex:1, display:'grid', gridTemplateColumns:'58% 42%', overflow:'hidden' }}>
        {/* Left: problem */}
        <div style={{ borderRight:`1px solid ${T.paper3}`, overflow:'auto', padding:'28px 32px' }}>
          <h2 style={{ fontFamily:T.serif, fontSize:'1.25rem', fontWeight:500, color:T.ink9, marginBottom:18,
            fontVariationSettings:'"opsz" 24' }}>Mini-problema</h2>
          <p style={{ fontFamily:T.serif, fontSize:'1rem', color:T.ink8, lineHeight:1.65, marginBottom:20,
            fontVariationSettings:'"opsz" 18' }}>{questionText}</p>

          {/* Mock residual scatter */}
          <div style={{ background:T.paper1, border:`1px solid ${T.paper3}`, borderRadius:8,
            padding:'16px', marginBottom:24, display:'flex', flexDirection:'column', alignItems:'center' }}>
            <div style={{ fontFamily:T.sans, fontSize:'0.75rem', color:T.ink4, marginBottom:10 }}>Residuales vs Valores ajustados</div>
            <svg width="260" height="120" viewBox="0 0 260 120">
              <line x1="20" y1="100" x2="240" y2="100" stroke={T.paper4} strokeWidth="1"/>
              <line x1="20" y1="10" x2="20" y2="100" stroke={T.paper4} strokeWidth="1"/>
              <line x1="20" y1="60" x2="240" y2="60" stroke={T.cool4} strokeWidth="1" strokeDasharray="4 3"/>
              {[[30,45],[55,52],[80,65],[100,58],[120,72],[140,68],[160,80],[175,75],[195,85],[215,82],[230,90]].map(([x,y],i) => (
                <circle key={i} cx={x} cy={y} r={3} fill="hsl(var(--atlas-warm-500))" opacity={0.7}/>
              ))}
            </svg>
            <div style={{ fontFamily:T.sans, fontSize:'0.75rem', color:T.ink4, marginTop:6 }}>
              Patrón visible — los residuales crecen con los valores ajustados
            </div>
          </div>

          {phase === 'accepted' || phase === 'opened' ? (
            <div style={{ background:`hsl(var(--atlas-accent-50))`, border:`1px solid ${T.acc5}`,
              borderRadius:8, padding:'14px 18px', animation:'fadeSlideUp 180ms ease-out' }}>
              <div style={{ fontFamily:T.sans, fontWeight:600, color:T.acc6, marginBottom:4 }}>Evidencia recibida</div>
              <div style={{ fontFamily:T.sans, fontSize:'0.875rem', color:T.ink6, lineHeight:1.55 }}>
                Interpreta el patrón de residuales con justificación propia. — judge score: 0.83
              </div>
            </div>
          ) : (
            <>
              <label style={{ fontFamily:T.sans, fontWeight:600, color:T.ink8, display:'block', marginBottom:10 }}>
                Tu respuesta:
              </label>
              <textarea value={answer} onChange={e => setAnswer(e.target.value)}
                placeholder="Escribe tu análisis aquí…"
                style={{ width:'100%', minHeight:120, fontFamily:T.serif, fontSize:'0.9375rem', color:T.ink8,
                  background:T.paper1, border:`1px solid ${T.paper4}`, borderRadius:6, padding:'12px 14px',
                  resize:'vertical', outline:'none', lineHeight:1.65, fontVariationSettings:'"opsz" 18',
                  boxSizing:'border-box' }}/>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:10 }}>
                <span style={{ fontFamily:T.mono, fontSize:'0.75rem', color: answer.length < minChars ? T.ink4 : T.acc5 }}>
                  {answer.length}/{minChars} caracteres mínimo
                </span>
                <Btn onClick={handleSubmit} disabled={!canSubmit || phase==='submitting'} variant="primary">
                  {phase==='submitting' ? '…evaluando' : 'Enviar evidencia →'}
                </Btn>
              </div>
            </>
          )}
        </div>

        {/* Right: graph */}
        <div style={{ overflow:'hidden', padding:'28px 20px', display:'flex', flexDirection:'column', alignItems:'center' }}>
          <h3 style={{ fontFamily:T.sans, fontSize:'0.8125rem', fontWeight:600, color:T.ink5,
            textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:16, alignSelf:'flex-start' }}>
            Tu grafo
          </h3>
          <SVGGraph
            nodes={AtlasData.nodes}
            edges={AtlasData.edges}
            width={270} height={310}
            openAnimation={animActive}
            openedEdgeId={phase==='opened' ? AtlasData.animEdgeId : null}
            onAnimDone={() => {}}
          />

          {phase === 'opened' && (
            <div style={{ marginTop:16, textAlign:'center', animation:'fadeSlideUp 260ms ease-out' }}>
              <p style={{ fontFamily:T.serif, fontSize:'1rem', color:T.warm6, marginBottom:16, fontVariationSettings:'"opsz" 18' }}>
                Conexión desbloqueada: <Ref>regLin</Ref> → <Ref>residuales</Ref>
              </p>
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                <Btn onClick={() => { set({ postSession:true, screen:'submit' }); }} variant="primary" size="sm">
                  Entregar ahora →
                </Btn>
                <Btn onClick={() => { set({ postSession:true, screen:'notebook' }); }} variant="secondary" size="sm">
                  Seguir en notebook
                </Btn>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// 07 · Submit a Canvas
// ═══════════════════════════════════════════════════════════
function S07Submit() {
  const [appState, set] = useAtlasState();
  const [file, setFile] = useState(null);
  const [phase, setPhase] = useState('ready'); // ready | uploading | submitting | confirmed | closure
  const [showClosure, setShowClosure] = useState(appState.saldoComplete);

  useEffect(() => {
    if (!showClosure) return;
    const t = setTimeout(() => {
      setShowClosure(false);
      setPhase('confirmed');
      setTimeout(() => set({ submitted: true, screen: 'reflection' }), 1800);
    }, 2100);
    return () => clearTimeout(t);
  }, [showClosure]);

  function handleSubmit() {
    setPhase('submitting');
    setTimeout(() => {
      setPhase('confirmed');
      set({ submitted: true });
      setTimeout(() => set({ screen: 'reflection' }), 1800);
    }, 400);
  }

  // Closure overlay (micro-cierre 2s)
  if (showClosure) return (
    <div style={{ height:'100%', display:'flex', alignItems:'center', justifyContent:'center',
      background:`rgba(255,250,240,.92)`, animation:'fadeIn 180ms ease-out' }}>
      <div style={{ textAlign:'center', animation:'fadeSlideUp 260ms ease-out' }}>
        <svg width="52" height="52" viewBox="0 0 52 52" style={{ marginBottom:16 }}>
          <circle cx="26" cy="26" r="24" fill="none" stroke={T.warm6} strokeWidth="2.5" opacity="0.3"/>
          <polyline points="14,26 22,34 38,18" fill="none" stroke={T.warm6} strokeWidth="2.5"
            strokeLinecap="round" strokeLinejoin="round"
            style={{ strokeDasharray:40, strokeDashoffset:40, animation:'drawCheck 380ms ease-out 180ms forwards' }}/>
        </svg>
        <p style={{ fontFamily:T.serif, fontSize:'1.375rem', fontWeight:500, color:T.warm6,
          lineHeight:1.35, fontVariationSettings:'"opsz" 24' }}>
          Conexión desbloqueada,<br/>tu trabajo está listo.
        </p>
      </div>
    </div>
  );

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <TopBar
        left={
          <>
            <button onClick={() => set({ screen:'notebook' })}
              style={{ background:'none', border:'none', cursor:'pointer', color:T.ink5, fontSize:18, padding:'0 4px' }}>←</button>
            <span style={{ fontFamily:T.sans, fontSize:'0.875rem', color:T.ink5 }}>Entregar Tarea 3</span>
          </>
        }
        right={<Chip>Tarea 3 · MAT-PMD</Chip>}
      />

      <div style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', padding:40 }}>
        <div style={{ width:'100%', maxWidth:520 }}>
          {phase === 'confirmed' ? (
            <div style={{ textAlign:'center', animation:'fadeSlideUp 240ms ease-out' }}>
              <div style={{ width:56, height:56, borderRadius:'50%', background:`hsl(var(--atlas-accent-100))`,
                display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 20px' }}>
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke={T.acc6} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
              </div>
              <h2 style={{ fontFamily:T.serif, fontSize:'1.5rem', fontWeight:500, color:T.ink9, marginBottom:8, fontVariationSettings:'"opsz" 24' }}>
                Entregado a Canvas
              </h2>
              <p style={{ fontFamily:T.mono, fontSize:'0.875rem', color:T.ink5 }}>
                Tarea 3 · Regresión sobre dataset de rentas · {new Date().toLocaleTimeString('es-MX', {hour:'2-digit', minute:'2-digit'})}
              </p>
            </div>
          ) : (
            <>
              <h2 style={{ fontFamily:T.serif, fontSize:'1.375rem', fontWeight:500, color:T.ink9, marginBottom:8, fontVariationSettings:'"opsz" 24' }}>
                Entregar Tarea 3
              </h2>
              <p style={{ fontFamily:T.sans, fontSize:'0.9375rem', color:T.ink6, marginBottom:24 }}>
                Sube tu archivo final.
              </p>

              {file ? (
                <div style={{ background:T.paper1, border:`1px solid ${T.paper3}`, borderRadius:8,
                  padding:'16px', marginBottom:20, display:'flex', alignItems:'center', gap:12 }}>
                  <span style={{ fontSize:20 }}>📎</span>
                  <div>
                    <div style={{ fontFamily:T.sans, fontWeight:600, color:T.ink8 }}>{file.name}</div>
                    <div style={{ fontFamily:T.mono, fontSize:'0.75rem', color:T.ink4 }}>
                      {(file.size/1024).toFixed(0)} KB
                    </div>
                  </div>
                  <button onClick={() => setFile(null)}
                    style={{ marginLeft:'auto', background:'none', border:'none', cursor:'pointer', color:T.ink4, fontSize:16 }}>×</button>
                </div>
              ) : (
                <label style={{ display:'block', border:`2px dashed ${T.paper4}`, borderRadius:8,
                  padding:'32px 20px', textAlign:'center', marginBottom:20, cursor:'pointer',
                  background:T.paper1, transition:'background 150ms' }}
                  onDragOver={e => e.preventDefault()}
                  onDrop={e => { e.preventDefault(); setFile(e.dataTransfer.files[0]); }}>
                  <input type="file" style={{ display:'none' }} onChange={e => setFile(e.target.files[0])} accept=".ipynb,.py,.pdf,.zip"/>
                  <div style={{ fontSize:24, marginBottom:10 }}>📎</div>
                  <div style={{ fontFamily:T.sans, fontWeight:500, color:T.ink7, marginBottom:6 }}>Arrastra o elige archivo</div>
                  <div style={{ fontFamily:T.sans, fontSize:'0.8125rem', color:T.ink4 }}>.ipynb · .py · .pdf · .zip (≤ 20 MB)</div>
                </label>
              )}

              <Btn onClick={handleSubmit} variant="calm" size="lg"
                style={{ width:'100%', display:'flex', justifyContent:'space-between' }}>
                <span>{phase==='submitting' ? 'Entregando…' : 'Entregar a Canvas'}</span><span>→</span>
              </Btn>
              <p style={{ fontFamily:T.sans, fontSize:'0.8125rem', color:T.ink4, textAlign:'center', marginTop:12 }}>
                Puedes entregar sin archivo. El botón nunca se bloquea.
              </p>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// 08 · Post-submit Reflection
// ═══════════════════════════════════════════════════════════
function S08Reflection() {
  const [appState, set] = useAtlasState();
  const [text, setText] = useState('');
  const [hotNodes, setHotNodes] = useState([]);
  const touchedNodes = AtlasData.nodes.slice(0, 3); // eda, limpieza, regLin

  function toggleNode(id) {
    setHotNodes(n => n.includes(id) ? n.filter(x => x !== id) : [...n, id]);
  }

  function save() {
    set({ reflectionDone: true, postSession: true, screen: 'zoom' });
  }

  return (
    <div style={{ height:'100%', display:'flex', alignItems:'center', justifyContent:'center',
      background:`rgba(251,250,247,.8)`, backdropFilter:'blur(4px)' }}>
      <div style={{ width:'100%', maxWidth:600, background:T.paper0, borderRadius:12,
        boxShadow:'var(--atlas-shadow-xl)', padding:'40px', animation:'scaleIn 240ms ease-out' }}>
        <p style={{ fontFamily:T.sans, fontSize:'0.875rem', color:T.ink4, marginBottom:8 }}>Un momento antes de cerrar.</p>
        <h2 style={{ fontFamily:T.serif, fontSize:'1.375rem', fontWeight:500, color:T.ink9, lineHeight:1.4,
          marginBottom:28, fontVariationSettings:'"opsz" 24' }}>
          ¿Qué de lo que entregaste hoy no podrías explicar en clase mañana?
        </h2>

        <textarea value={text} onChange={e => setText(e.target.value)}
          placeholder="(opcional)"
          style={{ width:'100%', height:100, fontFamily:T.serif, fontSize:'0.9375rem', color:T.ink8,
            background:T.paper1, border:`1px solid ${T.paper3}`, borderRadius:6, padding:'12px 14px',
            resize:'none', outline:'none', lineHeight:1.65, fontVariationSettings:'"opsz" 18',
            marginBottom:24, boxSizing:'border-box' }}/>

        <p style={{ fontFamily:T.sans, fontSize:'0.9375rem', color:T.ink7, marginBottom:14 }}>
          Marca los temas que quieras repasar:
        </p>
        <div style={{ display:'flex', gap:10, flexWrap:'wrap', marginBottom:32 }}>
          {touchedNodes.map(n => {
            const sel = hotNodes.includes(n.id);
            return (
              <button key={n.id} onClick={() => toggleNode(n.id)}
                style={{ fontFamily:T.sans, fontSize:'0.875rem', fontWeight:500,
                  padding:'8px 16px', borderRadius:20, cursor:'pointer', transition:'all 120ms',
                  background: sel ? `hsl(var(--atlas-warm-400) / 0.18)` : 'transparent',
                  color: sel ? T.warm6 : T.ink7,
                  border: `1px solid ${sel ? T.warm4 : T.paper4}` }}>
                {n.label}
              </button>
            );
          })}
        </div>

        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <button onClick={() => set({ screen:'zoom' })}
            style={{ fontFamily:T.sans, fontSize:'0.9375rem', color:T.ink5, background:'none', border:'none', cursor:'pointer', padding:0 }}>
            Saltar reflexión
          </button>
          <Btn onClick={save} variant="primary">Guardar y volver →</Btn>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { S05Contrato, S06Saldo, S07Submit, S08Reflection });
