// Screen 03 · Notebook tri-columna (+ naming mode inline)
const { useState, useEffect, useRef } = React;

function S03Notebook() {
  const [appState, set] = useAtlasState();
  const [activeTab, setActiveTab] = useState('grafo');
  const [chatMsgs, setChatMsgs] = useState(AtlasData.chatHistory);
  const [input, setInput] = useState('');
  const [showNaming, setShowNaming] = useState(!appState.namingChoice);
  const [leftW] = useState(248);
  const [rightW] = useState(300);
  const chatEndRef = useRef(null);
  const [canvasFullscreen, setCanvasFullscreen] = useState(false);
  const [codeExpanded, setCodeExpanded] = useState(false);

  // Show naming msg at top of chat if not resolved
  const allMessages = showNaming
    ? [...chatMsgs, { ...AtlasData.namingMsg, type: 'naming_mode' }]
    : chatMsgs;

  const namingPending = showNaming && !appState.namingChoice;

  useEffect(() => {
    chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [allMessages.length]);

  function handleSend(e) {
    if (e) e.preventDefault();
    if (!input.trim() || namingPending) return;
    setChatMsgs(m => [...m, { role: 'student', text: input.trim(), time: '21:50' }]);
    setInput('');
  }

  function handleNamingChoice(choice) {
    set({ namingChoice: choice });
    setShowNaming(false);
    if (choice === 'resuelve') {
      setTimeout(() => set({ screen: 'contrato' }), 300);
    } else {
      setChatMsgs(m => [...m,
        { role: 'atlas', text: 'Empecemos por los supuestos. ¿Qué asume regresión lineal sobre los errores?', time: '21:48', serif: true }
      ]);
    }
  }

  const deadline = AtlasData.activeSession.hoursLeft;

  // ── Message bubble ──
  function MsgBubble({ msg }) {
    const isAtlas   = msg.role === 'atlas';
    const isNaming  = msg.role === 'atlas_naming_mode';
    const isStudent = msg.role === 'student';
    const chosen    = appState.namingChoice;

    if (isNaming) {
      return (
        <div style={{ borderLeft: `3px solid ${T.warm4}`, background: `hsl(var(--atlas-warm-50))`,
          borderRadius: '0 8px 8px 0', padding: '14px 18px', marginBottom: 12,
          animation: 'fadeSlideUp 320ms ease-out' }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:10 }}>
            <div style={{ width:22, height:22, borderRadius:'50%', background:T.acc6, display:'flex',
              alignItems:'center', justifyContent:'center', flexShrink:0 }}>
              <span style={{ fontFamily:T.mono, fontSize:8, fontWeight:700, color:'white' }}>at</span>
            </div>
            <span style={{ fontFamily:T.sans, fontSize:'0.8125rem', fontWeight:600, color:T.ink7 }}>atlas</span>
            <span style={{ fontFamily:T.mono, fontSize:'0.75rem', color:T.ink4, marginLeft:'auto' }}>{msg.time}</span>
          </div>
          <p style={{ fontFamily:T.serif, fontSize:'1.0625rem', color:T.ink9, lineHeight:1.55,
            marginBottom:8, fontVariationSettings:'"opsz" 18' }}>
            {msg.text.replace('`regresión lineal`', '')}
            <Ref>regresión lineal</Ref>
          </p>
          {msg.subtext && (
            <p style={{ fontFamily:T.sans, fontSize:'0.875rem', color:T.ink5, lineHeight:1.6, marginBottom:14 }}>
              {msg.subtext.split('\n').map((l,i) => <span key={i}>{l}{i===0&&<br/>}</span>)}
            </p>
          )}
          {!chosen ? (
            <div style={{ display:'flex', gap:10 }}>
              <Btn onClick={() => handleNamingChoice('acompana')} variant="secondary" size="sm">Acompáñame</Btn>
              <Btn onClick={() => handleNamingChoice('resuelve')} variant="warm"      size="sm">Resuélvelo</Btn>
            </div>
          ) : (
            <Chip style={{ background: chosen==='acompana' ? `hsl(var(--atlas-accent-100))` : `hsl(var(--atlas-warm-100))`,
              color: chosen==='acompana' ? T.acc6 : T.warm6, border:'none' }}>
              {chosen==='acompana' ? 'Vamos paso a paso →' : 'Elegiste Resuélvelo · 15 min anotados'}
            </Chip>
          )}
          <button onClick={() => {}}
            style={{ display:'block', marginTop:10, background:'none', border:'none',
              fontFamily:T.sans, fontSize:'0.75rem', color:T.ink4, cursor:'pointer', padding:0 }}>
            ¿por qué este modo?
          </button>
        </div>
      );
    }

    return (
      <div style={{ display:'flex', gap:8, alignItems:'flex-start', marginBottom:12,
        flexDirection: isStudent ? 'row-reverse' : 'row' }}>
        {isAtlas && (
          <div style={{ width:22, height:22, borderRadius:'50%', background:T.acc6,
            display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, marginTop:2 }}>
            <span style={{ fontFamily:T.mono, fontSize:8, fontWeight:700, color:'white' }}>at</span>
          </div>
        )}
        <div style={{ maxWidth:'75%', background: isStudent ? T.paper2 : T.paper1,
          borderRadius: isStudent ? '8px 2px 8px 8px' : '2px 8px 8px 8px',
          padding: '9px 13px', boxShadow:'var(--atlas-shadow-xs)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:5 }}>
            <span style={{ fontFamily:T.sans, fontSize:'0.8125rem', fontWeight:600, color:T.ink7 }}>
              {isAtlas ? 'atlas' : 'tú'}
            </span>
            <span style={{ fontFamily:T.mono, fontSize:'0.6875rem', color:T.ink4 }}>{msg.time}</span>
          </div>
          <p style={{ fontFamily: msg.serif ? T.serif : T.sans,
            fontSize: msg.serif ? '0.9375rem' : '0.9375rem', color:T.ink8, lineHeight:1.55, margin:0,
            fontVariationSettings: msg.serif ? '"opsz" 18' : 'normal' }}>
            {msg.text}
          </p>
        </div>
      </div>
    );
  }

  // ── Canvas block ──
  function CanvasBlock({ block }) {
    const [executed, setExecuted] = useState(!!block.executed);
    const [running, setRunning] = useState(false);
    if (block.kind === 'markdown') {
      return (
        <div style={{ padding:'12px 0', borderBottom:`1px solid ${T.paper3}` }}>
          {block.content.split('\n').map((line, i) => {
            if (line.startsWith('## ')) return <h3 key={i} style={{ fontFamily:T.sans, fontSize:'1rem', fontWeight:600, color:T.ink9, margin:'0 0 8px' }}>{line.slice(3)}</h3>;
            if (!line) return <br key={i}/>;
            return <p key={i} style={{ fontFamily:T.sans, fontSize:'0.9375rem', color:T.ink7, lineHeight:1.6, margin:'0 0 6px' }}>{line}</p>;
          })}
        </div>
      );
    }
    if (block.kind === 'code') {
      return (
        <div style={{ borderRadius:6, overflow:'hidden', border:`1px solid ${T.paper3}`, marginBottom:12 }}>
          <div style={{ background: T.paper2, padding:'7px 12px', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <span style={{ fontFamily:T.mono, fontSize:'0.75rem', color:T.ink5 }}>{block.language}</span>
            <div style={{ display:'flex', gap:8, alignItems:'center' }}>
              {executed && <Chip style={{ color:T.acc6, borderColor:T.acc5 }}>✓ ejecutado</Chip>}
              <button onClick={() => { setRunning(true); setTimeout(() => { setExecuted(true); setRunning(false); }, 400); }}
                style={{ fontFamily:T.sans, fontSize:'0.75rem', fontWeight:600, background:'none', border:'none',
                  cursor:'pointer', color: running ? T.ink4 : T.acc6, padding:'2px 6px' }}>
                {running ? '…' : '▶ ejecutar'}
              </button>
            </div>
          </div>
          <pre style={{ fontFamily:T.mono, fontSize:'0.8125rem', color:T.ink8, background: T.paper1,
            padding:'12px 14px', margin:0, overflowX:'auto', lineHeight:1.6 }}>
            {block.content}
          </pre>
          {executed && block.output && (
            <div style={{ background:T.paper2, padding:'8px 14px', borderTop:`1px solid ${T.paper3}` }}>
              <span style={{ fontFamily:T.sans, fontSize:'0.6875rem', color:T.ink4, display:'block', marginBottom:4 }}>output</span>
              <pre style={{ fontFamily:T.mono, fontSize:'0.8125rem', color: T.acc6, margin:0, lineHeight:1.55 }}>{block.output}</pre>
            </div>
          )}
        </div>
      );
    }
    return null;
  }

  // ── Right tab content ──
  function RightTabContent() {
    if (activeTab === 'grafo') return (
      <div style={{ display:'flex', flexDirection:'column', alignItems:'center', padding:'16px 8px' }}>
        <SVGGraph nodes={AtlasData.nodes} edges={AtlasData.edges}
          width={rightW - 32} height={240} miniMode={false}
          openedEdgeId={appState.saldoComplete ? AtlasData.animEdgeId : null}
        />
        <Btn onClick={() => set({ screen:'grafo' })} variant="ghost" size="sm" style={{ marginTop:8 }}>Ver completo →</Btn>
      </div>
    );
    if (activeTab === 'plan') return (
      <div style={{ padding:16 }}>
        <div style={{ fontFamily:T.sans, fontSize:'0.875rem', fontWeight:600, color:T.ink7, marginBottom:12 }}>Plan de sesión</div>
        {[
          { done: true,  label: 'Bibliografía revisada' },
          { done: true,  label: 'Dataset cargado' },
          { done: false, label: 'Gates pendientes (1)', cta: () => set({ screen:'saldo' }) },
          { done: false, label: 'Subir archivo final' },
          { done: false, label: 'Submit a Canvas' },
        ].map((item, i) => (
          <div key={i} style={{ display:'flex', gap:10, alignItems:'center', padding:'9px 0',
            borderBottom: i < 4 ? `1px solid ${T.paper3}` : 'none' }}>
            <span style={{ width:16, height:16, borderRadius:'50%', flexShrink:0, display:'flex',
              alignItems:'center', justifyContent:'center', fontSize:10,
              background: item.done ? T.acc6 : T.paper3, color: item.done ? 'white' : T.ink4 }}>
              {item.done ? '✓' : ''}
            </span>
            <span style={{ fontFamily:T.sans, fontSize:'0.875rem', color: item.done ? T.ink4 : T.ink7,
              textDecoration: item.done ? 'line-through' : 'none', flex:1 }}>{item.label}</span>
            {item.cta && !item.done && (
              <button onClick={item.cta} style={{ fontFamily:T.sans, fontSize:'0.75rem', color:T.warm6,
                background:'none', border:'none', cursor:'pointer', padding:0 }}>→</button>
            )}
          </div>
        ))}
      </div>
    );
    if (activeTab === 'recursos') return (
      <div style={{ padding:16 }}>
        <div style={{ fontFamily:T.sans, fontSize:'0.875rem', fontWeight:600, color:T.ink7, marginBottom:12 }}>Recursos</div>
        {AtlasData.bibliography.map((b) => (
          <div key={b.id} style={{ padding:'9px 0', borderBottom:`1px solid ${T.paper3}`,
            fontFamily:T.sans, fontSize:'0.875rem', color:T.ink7, display:'flex', gap:8, alignItems:'center' }}>
            <span style={{ fontSize:14 }}>{b.kind==='pdf' ? '📘' : '🔗'}</span>
            {b.title}
          </div>
        ))}
      </div>
    );
    return (
      <div style={{ padding:16 }}>
        <div style={{ fontFamily:T.sans, fontSize:'0.875rem', fontWeight:600, color:T.ink7, marginBottom:12 }}>Historial</div>
        <div style={{ fontFamily:T.sans, fontSize:'0.875rem', color:T.ink5 }}>
          <div style={{ padding:'8px 0', borderBottom:`1px solid ${T.paper3}` }}>Sesión actual · 22 abr · Reg. lineal</div>
          <div style={{ padding:'8px 0', borderBottom:`1px solid ${T.paper3}` }}>Sesión anterior · 20 abr · EDA</div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      {/* Top bar */}
      <TopBar
        left={
          <>
            <button onClick={() => set({ screen:'dashboard' })}
              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 }}>MAT-PMD · reg. lineal · Tarea 3</span>
          </>
        }
        center={
          deadline && (
            <span style={{ fontFamily:T.mono, fontSize:'0.875rem', color:T.ink5, tabularNums: true }}>
              ⏱ {deadline}h al deadline
            </span>
          )
        }
        right={
          <Btn onClick={() => set({ screen:'submit' })} variant="calm" size="sm">Submit →</Btn>
        }
      />

      {/* Tri-column */}
      <div style={{ flex:1, display:'grid', gridTemplateColumns:`${leftW}px 1fr ${rightW}px`,
        overflow:'hidden', borderTop:`1px solid ${T.paper3}` }}>

        {/* Left: Bibliography */}
        <div style={{ borderRight:`1px solid ${T.paper3}`, overflow:'auto', display:'flex', flexDirection:'column' }}>
          <div style={{ padding:'12px 14px', fontFamily:T.sans, fontSize:'0.75rem', fontWeight:600,
            color:T.ink4, textTransform:'uppercase', letterSpacing:'0.06em', borderBottom:`1px solid ${T.paper3}` }}>
            Bibliografía
          </div>
          <div style={{ flex:1, overflow:'auto', padding:'8px 0' }}>
            {AtlasData.bibliography.map(b => (
              <div key={b.id} style={{ padding:'10px 14px', borderBottom:`1px solid ${T.paper3}`, cursor:'pointer' }}
                onMouseEnter={e => e.currentTarget.style.background=T.paper1}
                onMouseLeave={e => e.currentTarget.style.background='transparent'}>
                <div style={{ display:'flex', gap:8, alignItems:'flex-start' }}>
                  <span style={{ fontSize:15, flexShrink:0 }}>{b.kind==='pdf'?'📘':'🔗'}</span>
                  <div>
                    <div style={{ fontFamily:T.sans, fontSize:'0.875rem', color:T.ink8, marginBottom:5, lineHeight:1.3 }}>{b.title}</div>
                    <div style={{ display:'flex', flexWrap:'wrap', gap:4 }}>
                      {b.anchors.map(a => (
                        <span key={a} style={{ fontFamily:T.mono, fontSize:'0.6875rem', background:T.paper2,
                          border:`1px solid ${T.paper4}`, borderRadius:3, padding:'1px 5px', color:T.ink5 }}>{a}</span>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ padding:'10px 14px', borderTop:`1px solid ${T.paper3}` }}>
            <button style={{ fontFamily:T.sans, fontSize:'0.875rem', color:T.acc6, background:'none', border:'none', cursor:'pointer', padding:0 }}>+ subir</button>
          </div>
        </div>

        {/* Center: Chat + Canvas */}
        <div style={{ display:'flex', flexDirection:'column', overflow:'hidden' }}>
          {/* Chat */}
          {!canvasFullscreen && (
            <div style={{ flex:'0 0 52%', display:'flex', flexDirection:'column', borderBottom:`1px solid ${T.paper3}` }}>
              <div style={{ flex:1, overflow:'auto', padding:'12px 16px' }}>
                {allMessages.map((msg, i) => <MsgBubble key={i} msg={msg}/>)}
                <div ref={chatEndRef}/>
              </div>
              <form onSubmit={handleSend}
                style={{ borderTop:`1px solid ${T.paper3}`, padding:'10px 14px', display:'flex', gap:8,
                  background: T.paper0, opacity: namingPending ? 0.4 : 1 }}>
                <input value={input} onChange={e => setInput(e.target.value)} disabled={namingPending}
                  placeholder={namingPending ? 'Elige una opción para continuar…' : 'escribe aquí…'}
                  style={{ flex:1, fontFamily:T.sans, fontSize:'0.9375rem', background:T.paper1,
                    border:`1px solid ${T.paper4}`, borderRadius:4, padding:'8px 12px', color:T.ink8,
                    outline:'none' }}/>
                <button type="submit" disabled={namingPending}
                  style={{ background: T.acc6, color:'white', border:'none', borderRadius:6,
                    padding:'8px 14px', cursor: namingPending ? 'not-allowed' : 'pointer', minHeight:40 }}>↵</button>
              </form>
            </div>
          )}

          {/* Canvas */}
          <div style={{ flex:1, overflow:'auto', display:'flex', flexDirection:'column' }}>
            <div style={{ padding:'8px 16px', borderBottom:`1px solid ${T.paper3}`, display:'flex',
              alignItems:'center', justifyContent:'space-between', background:T.paper1, flexShrink:0 }}>
              <span style={{ fontFamily:T.sans, fontSize:'0.75rem', fontWeight:600, color:T.ink5, textTransform:'uppercase', letterSpacing:'0.06em' }}>Canvas</span>
              <button onClick={() => setCanvasFullscreen(f => !f)}
                style={{ background:'none', border:'none', cursor:'pointer', color:T.ink4, fontSize:13, fontFamily:T.sans }}>
                {canvasFullscreen ? '⊟ colapsar' : '⊞ pantalla completa'}
              </button>
            </div>
            <div style={{ flex:1, overflow:'auto', padding:'12px 16px' }}>
              {AtlasData.canvas.map((b, i) => <CanvasBlock key={i} block={b}/>)}
              <button style={{ marginTop:12, fontFamily:T.sans, fontSize:'0.875rem', color:T.acc6,
                background:'none', border:`1px dashed ${T.paper4}`, borderRadius:6, padding:'8px 16px',
                cursor:'pointer', width:'100%' }}>+ bloque</button>
            </div>
          </div>
        </div>

        {/* Right: Tabs */}
        <div style={{ borderLeft:`1px solid ${T.paper3}`, display:'flex', flexDirection:'column', overflow:'hidden' }}>
          <div style={{ display:'flex', borderBottom:`1px solid ${T.paper3}`, flexShrink:0 }}>
            {['grafo','plan','recursos','historial'].map(tab => (
              <button key={tab} onClick={() => setActiveTab(tab)}
                style={{ flex:1, fontFamily:T.sans, fontSize:'0.6875rem', fontWeight:600, padding:'10px 4px',
                  background: activeTab===tab ? T.paper1 : 'transparent',
                  color: activeTab===tab ? T.ink9 : T.ink4,
                  border:'none', borderBottom: activeTab===tab ? `2px solid ${T.acc5}` : '2px solid transparent',
                  cursor:'pointer', textTransform:'uppercase', letterSpacing:'0.04em' }}>
                {tab}
              </button>
            ))}
          </div>
          <div style={{ flex:1, overflow:'auto' }}>
            <RightTabContent/>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { S03Notebook });
