/* Mayday Medical — root App + router */
const { useState: appUS, useEffect: appUE } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "accent": "clay"
}/*EDITMODE-END*/;

function App() {
  const data = window.MAYDAY_DATA;
  const [route, setRoute] = appUS({ name: 'home' });
  const [searchOpen, setSearchOpen] = appUS(false);
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  // apply theme
  appUE(() => {
    document.documentElement.setAttribute('data-theme', tweaks.theme === 'dark' ? 'dark' : 'light');
  }, [tweaks.theme]);

  // global cmd-k
  appUE(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        setSearchOpen(o => !o);
      } else if (e.key === '/' && document.activeElement === document.body) {
        e.preventDefault();
        setSearchOpen(true);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  // scroll to top on route change
  appUE(() => { window.scrollTo({ top: 0, behavior: 'instant' }); }, [route]);

  const onNavigate = (r) => setRoute(r);

  // resolve route → view + needed data
  const renderView = () => {
    if (route.name === 'home') return <Landing onNavigate={onNavigate} data={data} />;
    if (route.name === 'tools') return <ToolsHub data={data} onNavigate={onNavigate} />;
    if (route.name === 'profile') return <ProfilePage data={data} onNavigate={onNavigate} />;
    // Rapids family
    if (route.name === 'rapids') return <RapidsHub data={data} onNavigate={onNavigate} />;
    if (route.name === 'rapids-filter') return <RapidsFilter data={data} poolId={route.poolId} onNavigate={onNavigate} />;
    if (route.name === 'rapids-quiz') return <RapidsQuiz data={data} poolId={route.poolId} config={route.config} onNavigate={onNavigate} />;
    // Library + its sub-tabs (step / progress) all render through LibraryHub
    if (route.name === 'library' || route.name === 'progress' || route.name === 'step') {
      return <LibraryHub data={data} route={route} onNavigate={onNavigate} />;
    }
    const stepMap = { step2: data.STEP2, bugs: data.BUGS, drugs: data.DRUGS };
    const step = stepMap[route.stepId] || data.STEP2;
    const subject = step.subjects.find(s => s.id === route.subjectId);
    if (!subject) return <LibraryHub data={data} route={{ name: 'step', stepId: route.stepId || 'step2' }} onNavigate={onNavigate} />;
    if (route.name === 'subject') return <SubjectPage step={step} subject={subject} onNavigate={onNavigate} />;
    const topic = subject.topics.find(t => t.id === route.topicId);
    if (!topic) return <SubjectPage step={step} subject={subject} onNavigate={onNavigate} />;
    if (route.name === 'topic') return <TopicPage step={step} subject={subject} topic={topic} onNavigate={onNavigate} />;
    const subtopic = (topic.subtopics || []).find(s => s.id === route.subtopicId);
    if (!subtopic) return <TopicPage step={step} subject={subject} topic={topic} onNavigate={onNavigate} />;
    if (route.name === 'lesson') return <LessonPage step={step} subject={subject} topic={topic} subtopic={subtopic} onNavigate={onNavigate} />;
    return <Landing onNavigate={onNavigate} data={data} />;
  };

  return (
    <div className="shell">
      <Header route={route} onNavigate={onNavigate} onOpenSearch={() => setSearchOpen(true)} />
      {renderView()}
      <Footer />
      <SearchOverlay open={searchOpen} onClose={() => setSearchOpen(false)} onNavigate={onNavigate} index={data.SEARCH_INDEX} />

      <window.TweaksPanel title="Tweaks">
        <window.TweakSection title="Appearance">
          <window.TweakRadio label="Theme"
            value={tweaks.theme}
            onChange={v => setTweak('theme', v)}
            options={[{ value: 'light', label: 'Light' }, { value: 'dark', label: 'Dark' }]}
          />
        </window.TweakSection>
        <window.TweakSection title="About">
          <div style={{ fontSize: 12, color: 'var(--muted)', lineHeight: 1.5 }}>
            Mayday Medical is a prototype. Tweaks lets you switch between light & dark.
            Press <kbd style={{ fontSize: 10.5, padding: '1px 5px', background:'var(--bg-2)', border:'1px solid var(--line)', borderRadius: 4, fontFamily:'JetBrains Mono, monospace' }}>⌘K</kbd> anywhere to search.
          </div>
        </window.TweakSection>
      </window.TweaksPanel>
    </div>
  );
}

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