// Atlas — main app router + demo navigation bar
const { useState, useEffect } = React;

const DEMO_FLOW = [
  { id: 'login',       label: '00 Login',          component: 'S00Login'            },
  { id: 'onboarding',  label: '01 Onboarding',     component: 'S01Onboarding'       },
  { id: 'home',        label: '02a Mis clases',    component: 'S02aHome'            },
  { id: 'dashboard',   label: '02 Dashboard',      component: 'S02Dashboard'        },
  { id: 'notebook',    label: '03 Notebook',       component: 'S03Notebook'         },
  { id: 'contrato',    label: '05 Contrato',       component: 'S05Contrato'         },
  { id: 'saldo',       label: '06 Saldo ✦',        component: 'S06Saldo'            },
  { id: 'submit',      label: '07 Submit',          component: 'S07Submit'           },
  { id: 'reflection',  label: '08 Reflexión',       component: 'S08Reflection'       },
  { id: 'zoom',        label: '09 Zoom ✦',          component: 'S09Zoom'             },
  { id: 't01',         label: 'T1 Cohorte',         component: 'T01CohortDashboard'  },
  { id: 't02',         label: 'T2 Estudiantes',     component: 'T02StudentCards'     },
  { id: 't03',         label: 'T3 Gates',           component: 'T03GateDefinition'   },
  { id: 'portafolio',  label: '11 Portafolio',     component: 'S11Portafolio'       },
  { id: 'silencio',    label: '12 Silencio',       component: 'S12Silencio'         },
];

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "navCollapsed": false,
  "crunchDemo": false,
  "postSessionDemo": false
}/*EDITMODE-END*/;

function DemoNav({ screen, collapsed, onToggle }) {
  const [appState, set] = useAtlasState();
  const currentIdx = DEMO_FLOW.findIndex(s => s.id === screen);

  if (collapsed) return (
    <div style={{ height: 36, background: 'hsl(var(--atlas-ink-900))', display: 'flex',
      alignItems: 'center', justifyContent: 'space-between', padding: '0 16px', flexShrink: 0 }}>
      <span style={{ fontFamily: 'var(--atlas-font-mono)', fontSize: '0.75rem',
        color: 'hsl(var(--atlas-warm-400))' }}>
        atlas demo · {DEMO_FLOW[currentIdx]?.label || screen}
      </span>
      <button onClick={onToggle}
        style={{ background: 'none', border: 'none', cursor: 'pointer',
          color: 'hsl(var(--atlas-ink-400))', fontFamily: 'var(--atlas-font-mono)', fontSize: '0.6875rem' }}>
        mostrar nav ▴
      </button>
    </div>
  );

  return (
    <div style={{ background: 'hsl(var(--atlas-ink-900))', flexShrink: 0, userSelect: 'none' }}>
      <div style={{ display: 'flex', alignItems: 'center', padding: '8px 16px 6px', gap: 6, flexWrap: 'wrap' }}>
        <span style={{ fontFamily: 'var(--atlas-font-mono)', fontSize: '0.6875rem',
          color: 'hsl(var(--atlas-ink-500))', marginRight: 6 }}>demo →</span>

        {DEMO_FLOW.map((s, idx) => {
          const isCurrent = s.id === screen;
          const isPast    = idx < currentIdx;
          return (
            <button key={s.id} onClick={() => set({ screen: s.id })}
              style={{
                fontFamily: 'var(--atlas-font-mono)', fontSize: '0.6875rem', fontWeight: isCurrent ? 700 : 400,
                padding: '4px 10px', borderRadius: 4, border: 'none', cursor: 'pointer',
                transition: 'background 120ms, color 120ms',
                background: isCurrent
                  ? 'hsl(var(--atlas-warm-500))'
                  : isPast ? 'hsl(30 16% 16%)' : 'transparent',
                color: isCurrent
                  ? 'hsl(var(--atlas-paper-50))'
                  : isPast ? 'hsl(var(--atlas-ink-500))' : 'hsl(var(--atlas-ink-400))',
              }}>
              {s.label}
            </button>
          );
        })}

        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, alignItems: 'center' }}>
          {/* Prev / Next */}
          {currentIdx > 0 && (
            <button onClick={() => set({ screen: DEMO_FLOW[currentIdx - 1].id })}
              style={{ background: 'none', border: '1px solid hsl(var(--atlas-ink-700))', borderRadius: 4,
                color: 'hsl(var(--atlas-ink-400))', fontFamily: 'var(--atlas-font-mono)', fontSize: '0.6875rem',
                padding: '3px 8px', cursor: 'pointer' }}>
              ← prev
            </button>
          )}
          {currentIdx < DEMO_FLOW.length - 1 && (
            <button onClick={() => set({ screen: DEMO_FLOW[currentIdx + 1].id })}
              style={{ background: 'hsl(var(--atlas-warm-600))', border: 'none', borderRadius: 4,
                color: 'white', fontFamily: 'var(--atlas-font-mono)', fontSize: '0.6875rem',
                padding: '3px 10px', cursor: 'pointer', fontWeight: 700 }}>
              next →
            </button>
          )}
          <button onClick={onToggle}
            style={{ background: 'none', border: 'none', cursor: 'pointer',
              color: 'hsl(var(--atlas-ink-600))', fontFamily: 'var(--atlas-font-mono)', fontSize: '0.6875rem' }}>
            ▾
          </button>
        </div>
      </div>
    </div>
  );
}

function TweaksPanel({ visible, tweaks, onClose, onTweak }) {
  const [appState, set] = useAtlasState();
  if (!visible) return null;
  return (
    <div style={{ position: 'fixed', bottom: 16, right: 16, width: 280, background: 'white',
      border: '1px solid hsl(var(--atlas-paper-300))', borderRadius: 10,
      boxShadow: 'var(--atlas-shadow-xl)', padding: '18px 20px', zIndex: 9999,
      fontFamily: 'var(--atlas-font-sans)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <span style={{ fontWeight: 600, fontSize: '0.9375rem', color: 'hsl(var(--atlas-ink-900))' }}>Tweaks</span>
        <button onClick={onClose}
          style={{ background: 'none', border: 'none', cursor: 'pointer',
            color: 'hsl(var(--atlas-ink-400))', fontSize: 16 }}>×</button>
      </div>

      {[
        { key: 'crunchDemo',       label: 'Modo crunch',        type: 'toggle',
          action: v => set({ crunchMode: v }) },
        { key: 'postSessionDemo',  label: 'Post-sesión banner', type: 'toggle',
          action: v => set({ postSession: v }) },
        { key: 'navCollapsed',     label: 'Nav colapsada',      type: 'toggle', action: () => {} },
        { key: 'saldoComplete',    label: 'Grafo desbloqueado (simular)', type: 'action',
          action: () => set({ saldoComplete: true }) },
        { key: 'reset',            label: 'Resetear todo',      type: 'action',
          action: () => { set({ namingChoice: null, debtSigned: false, saldoComplete: false, submitted: false, crunchMode: false, postSession: false }); } },
      ].map(item => (
        <div key={item.key} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '8px 0', borderBottom: '1px solid hsl(var(--atlas-paper-200))' }}>
          <span style={{ fontSize: '0.875rem', color: 'hsl(var(--atlas-ink-700))' }}>{item.label}</span>
          {item.type === 'toggle' ? (
            <button onClick={() => {
              const newVal = !tweaks[item.key];
              onTweak(item.key, newVal);
              item.action(newVal);
            }}
              style={{ width: 36, height: 20, borderRadius: 10, border: 'none', cursor: 'pointer',
                background: tweaks[item.key] ? 'hsl(var(--atlas-accent-500))' : 'hsl(var(--atlas-paper-300))',
                position: 'relative', transition: 'background 150ms' }}>
              <span style={{ position: 'absolute', top: 2, width: 16, height: 16, borderRadius: '50%',
                background: 'white', transition: 'left 150ms',
                left: tweaks[item.key] ? 18 : 2 }}/>
            </button>
          ) : (
            <button onClick={item.action}
              style={{ fontFamily: 'var(--atlas-font-sans)', fontSize: '0.75rem',
                background: 'hsl(var(--atlas-paper-200))', border: '1px solid hsl(var(--atlas-paper-400))',
                borderRadius: 4, padding: '3px 10px', cursor: 'pointer',
                color: 'hsl(var(--atlas-ink-600))' }}>
              run
            </button>
          )}
        </div>
      ))}
    </div>
  );
}

function App() {
  const [appState] = useAtlasState();
  const { screen } = appState;
  const [navCollapsed, setNavCollapsed] = useState(TWEAK_DEFAULTS.navCollapsed);
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);
  const [showTweaks, setShowTweaks] = useState(false);

  // Register tweaks panel availability
  useEffect(() => {
    window.addEventListener('message', e => {
      if (e.data?.type === '__activate_edit_mode')   setShowTweaks(true);
      if (e.data?.type === '__deactivate_edit_mode') setShowTweaks(false);
    });
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
  }, []);

  function handleTweak(key, val) {
    const next = { ...tweaks, [key]: val };
    setTweaks(next);
    if (key === 'navCollapsed') setNavCollapsed(val);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: val } }, '*');
  }

  const screenMap = {
    login:      'S00Login',
    onboarding: 'S01Onboarding',
    home:       'S02aHome',
    dashboard:  'S02Dashboard',
    notebook:   'S03Notebook',
    contrato:   'S05Contrato',
    saldo:      'S06Saldo',
    submit:     'S07Submit',
    reflection: 'S08Reflection',
    zoom:       'S09Zoom',
    t01:        'T01CohortDashboard',
    t02:        'T02StudentCards',
    t03:        'T03GateDefinition',
    grafo:      'S10Grafo',        // reachable via dashboard's "Ver completo" (no en DEMO_FLOW linear)
    portafolio: 'S11Portafolio',
    silencio:   'S12Silencio',
  };
  const ScreenComp = window[screenMap[screen]] || window['S00Login'];

  return (
    <div style={{ height: '100vh', display: 'flex', flexDirection: 'column',
      background: 'hsl(var(--atlas-paper-50))', fontFamily: 'var(--atlas-font-sans)',
      overflow: 'hidden' }}>
      <DemoNav screen={screen} collapsed={navCollapsed} onToggle={() => setNavCollapsed(c => !c)} />
      <div style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>
        {ScreenComp && <ScreenComp />}
      </div>
      <TweaksPanel visible={showTweaks} tweaks={tweaks} onClose={() => setShowTweaks(false)} onTweak={handleTweak} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
