// App — main state, routing, layout
function App() {
  const previewMode = typeof window !== 'undefined' && !!window.__BWC_PREVIEW_MODE;

  const [currentModule, setCurrentModule] = React.useState(() => {
    if (typeof window !== 'undefined' && window.__BWC_PREVIEW_MODE && typeof MODULES_DATA !== 'undefined' && MODULES_DATA[0]) {
      return MODULES_DATA[0];
    }
    return null;
  });
  const [currentSection, setCurrentSection] = React.useState(() => {
    if (typeof window !== 'undefined' && window.__BWC_PREVIEW_MODE && typeof MODULES_DATA !== 'undefined' && MODULES_DATA[0]?.sections?.[0]) {
      return MODULES_DATA[0].sections[0].id;
    }
    return null;
  });
  const [sidebarOpen, setSidebarOpen] = React.useState(false);
  const [searchOpen, setSearchOpen] = React.useState(false);
  const [certOpen, setCertOpen] = React.useState(false);
  const [keySetupOpen, setKeySetupOpen] = React.useState(false);
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const [tweaks, setTweaks] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('bwc_tweaks') || '{}'); }
    catch { return {}; }
  });

  React.useEffect(() => {
    localStorage.setItem('bwc_tweaks', JSON.stringify(tweaks));
  }, [tweaks]);

  // Keyboard shortcuts
  React.useEffect(() => {
    const handler = (e) => {
      // CMD+K or CTRL+K = search
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setSearchOpen(s => !s);
        return;
      }
      if (!currentModule) return;
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
      const sections = currentModule.sections;
      const idx = sections.findIndex(s => s.id === currentSection);
      if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
        e.preventDefault();
        if (idx < sections.length - 1) setCurrentSection(sections[idx + 1].id);
      }
      if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
        e.preventDefault();
        if (idx > 0) setCurrentSection(sections[idx - 1].id);
      }
      if (e.key === 'Escape') {
        if (searchOpen) { setSearchOpen(false); return; }
        if (certOpen) { setCertOpen(false); return; }
        setCurrentModule(null);
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [currentModule, currentSection, searchOpen, certOpen]);

  // Listen for next/prev nav from ModuleView
  React.useEffect(() => {
    const handler = (e) => selectModule(e.detail, null);
    window.addEventListener('selectModule', handler);
    return () => window.removeEventListener('selectModule', handler);
  }, []);

  // Tweaks toggle
  React.useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  function selectModule(mod, sectionId) {
    if (previewMode && mod && mod.id !== 1) return;
    setCurrentModule(mod);
    setCurrentSection(sectionId || mod.sections[0]?.id || null);
    setSidebarOpen(false);
    requestAnimationFrame(() => {
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
    });
  }

  const SIDEBAR_W = 260;

  return (
    <div style={{ minHeight:'100vh', background:'#000', color:'#fff' }}>

      {/* Top bar */}
      <header style={{
        position:'fixed', top:0, left:0, right:0, zIndex:30,
        background:'#000', borderBottom:'1px solid #1a1a1a',
        display:'flex', alignItems:'center', height:52
      }}>
        {/* Hamburger — mobile only */}
        <button onClick={() => setSidebarOpen(true)} id="nav-hamburger"
          style={{ width:52, height:52, background:'none', border:'none', borderRight:'1px solid #1a1a1a',
            cursor:'pointer', display:'none', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:4, flexShrink:0 }}>
          {[0,1,2].map(i => <span key={i} style={{ width:16, height:1, background:'#666', display:'block' }} />)}
        </button>

        {/* Brand */}
        <button onClick={() => { if (!previewMode) setCurrentModule(null); }}
          style={{ background:'none', border:'none', cursor: previewMode ? 'default' : 'pointer', padding:'0 20px', height:'100%',
            borderRight:'1px solid #1a1a1a', display:'flex', alignItems:'center', gap:10, flexShrink:0 }}>
          <span style={{ fontFamily:'Syne,sans-serif', fontWeight:700, fontSize:14, letterSpacing:'-0.01em', color:'#fff' }}>Build with Claude</span>
          <span style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.18em', color:'#444', textTransform:'uppercase' }}>Course</span>
          {previewMode && (
            <span style={{ fontFamily:'JetBrains Mono,monospace', fontSize:8, letterSpacing:'0.14em', color:'#C9A84C', textTransform:'uppercase', marginLeft:6 }}>Free · Mod 1</span>
          )}
        </button>

        {/* Breadcrumb */}
        {currentModule && (
          <div style={{ flex:1, padding:'0 20px', display:'flex', alignItems:'center', gap:8, overflow:'hidden' }}>
            <span style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.14em', color:'#444', textTransform:'uppercase' }}>MOD. {currentModule.num}</span>
            <span style={{ color:'#2a2a2a' }}>·</span>
            <span style={{ fontFamily:'Inter,sans-serif', fontSize:12, color:'#666', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{currentModule.title}</span>
            {currentSection && (() => {
              const idx = currentModule.sections.findIndex(s => s.id === currentSection);
              return idx >= 0 ? (
                <span style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, color:'#333', marginLeft:4, flexShrink:0 }}>
                  {idx+1}/{currentModule.sections.length}
                </span>
              ) : null;
            })()}
          </div>
        )}

        {/* Right side controls */}
        <div style={{ display:'flex', alignItems:'center', marginLeft:'auto', borderLeft:'1px solid #1a1a1a' }}>
          {/* Certificate button — only when all modules complete */}
          {!previewMode && MODULES_DATA.every(m => getModuleProgress(m.id) === 100) && (
            <button onClick={() => setCertOpen(true)} style={{ height:52, padding:'0 16px', background:'none', border:'none', borderRight:'1px solid #1a1a1a', cursor:'pointer', fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.16em', textTransform:'uppercase', color:'#C9A84C' }}>
              ✦ Certificate
            </button>
          )}
          {/* API Key settings */}
          <button onClick={() => setKeySetupOpen(true)} title="API Key Settings"
            style={{ height:52, width:42, background:'none', border:'none', borderRight:'1px solid #1a1a1a', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
            <span style={{ fontSize:14, color: (previewMode ? getPreviewApiKey() : localStorage.getItem('bwc_has_api_key') === '1') ? '#C9A84C' : '#333' }}>⚙</span>
          </button>
          {/* Search button */}
          <button onClick={() => setSearchOpen(true)} style={{ height:52, padding:'0 16px', background:'none', border:'none', cursor:'pointer', display:'flex', alignItems:'center', gap:8 }}>
            <span style={{ fontFamily:'JetBrains Mono,monospace', fontSize:14, color:'#444' }}>⌕</span>
            <kbd style={{ fontFamily:'JetBrains Mono,monospace', fontSize:8, color:'#2a2a2a', border:'1px solid #1a1a1a', padding:'2px 5px', letterSpacing:'0.08em' }}>⌘K</kbd>
          </button>
        </div>
      </header>

      {/* Sidebar */}
      <Sidebar
        currentModule={currentModule}
        currentSection={currentSection}
        onSelectModule={selectModule}
        onSelectSection={setCurrentSection}
        sidebarOpen={sidebarOpen}
        onClose={() => setSidebarOpen(false)}
        previewMode={previewMode}
      />

      {/* Main content — offset by sidebar on desktop */}
      <main id="main-content" style={{ paddingTop:52, paddingLeft: SIDEBAR_W }}>
        {currentModule
          ? <ModuleView module={currentModule} currentSection={currentSection} onSectionChange={setCurrentSection} previewMode={previewMode} />
          : <Dashboard onSelectModule={selectModule} previewMode={previewMode} />
        }
      </main>

      {/* Search modal */}
      {searchOpen && <Search onSelectModule={selectModule} onClose={() => setSearchOpen(false)} previewMode={previewMode} />}

      {/* Certificate */}
      {certOpen && <Certificate onClose={() => setCertOpen(false)} />}

      {/* API Key Setup */}
      {keySetupOpen && <ApiKeyPanel isOverlay={true} previewMode={previewMode} onClose={() => setKeySetupOpen(false)} />}

      {/* Tweaks panel */}
      {tweaksOpen && (
        <div style={{
          position:'fixed', bottom:24, right:24, zIndex:100,
          background:'#0d0d0d', border:'1px solid #2a2a2a', padding:'20px 22px', width:240
        }}>
          <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:10, letterSpacing:'0.2em', color:'#C9A84C', textTransform:'uppercase', marginBottom:18 }}>Tweaks</div>

          <div style={{ marginBottom:16 }}>
            <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.14em', color:'#555', textTransform:'uppercase', marginBottom:8 }}>Accent Color</div>
            <div style={{ display:'flex', gap:8 }}>
              {['#C9A84C','#3B82F6','#7BB7A8','#EF4444','#A78BFA'].map(c => (
                <button key={c} onClick={() => { setTweaks(t => ({...t, accent:c})); window.parent.postMessage({type:'__edit_mode_set_keys', edits:{accent:c}}, '*'); }}
                  style={{ width:22, height:22, background:c, border: tweaks.accent===c ? '2px solid #fff' : '2px solid transparent', cursor:'pointer' }} />
              ))}
            </div>
          </div>

          <div style={{ marginBottom:16 }}>
            <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.14em', color:'#555', textTransform:'uppercase', marginBottom:8 }}>Font Size: {tweaks.fontSize||14}px</div>
            <input type="range" min={12} max={18} step={1} value={tweaks.fontSize||14}
              onChange={e => { const v=parseInt(e.target.value); setTweaks(t=>({...t,fontSize:v})); window.parent.postMessage({type:'__edit_mode_set_keys',edits:{fontSize:v}},'*'); }}
              style={{ width:'100%', accentColor:'#C9A84C' }} />
          </div>

          <div style={{ marginBottom:16 }}>
            <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.14em', color:'#555', textTransform:'uppercase', marginBottom:8 }}>Keyboard Shortcuts</div>
            <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, color:'#444', lineHeight:1.8 }}>
              ← → Navigate sections<br/>ESC Back to dashboard
            </div>
          </div>

          <button onClick={() => { localStorage.removeItem('bwc_progress'); window.location.reload(); }}
            style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.14em', textTransform:'uppercase', background:'none', border:'1px solid #2a2a2a', color:'#666', padding:'6px 12px', cursor:'pointer', width:'100%' }}>
            Clear all progress
          </button>
        </div>
      )}

      {/* Responsive */}
      <style>{`
        @media (max-width: 900px) {
          #main-content { padding-left: 0 !important; }
          #nav-hamburger { display: flex !important; }
        }
      `}</style>
    </div>
  );
}

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