/* Dump — app.jsx: shell, nav, routing, keyboard shortcuts */

const NAV = [
{ key: 'today', label: 'Today', icon: 'today' },
{ key: 'capture', label: 'Capture', icon: 'capture' },
{ key: 'tasks', label: 'Tasks', icon: 'tasks' },
{ key: 'groceries', label: 'Groceries', icon: 'cart' },
{ key: 'calendar', label: 'Calendar', icon: 'calendar' },
{ key: 'done', label: 'Done', icon: 'done' },
{ key: 'connect', label: 'Connect', icon: 'connect' }];


function App() {
  const state = useDumpStore();
  const { route, settingsOpen, tasks, suggestions, pomodoro, settings, scheduler } = state;
  const pomoModalOpen = pomodoro.status !== 'idle' && !((pomodoro.status === 'break' || pomodoro.status === 'longbreak') && pomodoro.pilled);

  // Apply the colour theme to the document root (covers body + fixed modals).
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', settings.theme === 'dark' ? 'dark' : 'light');
  }, [settings.theme]);

  // Every screen change starts at the top — otherwise a scrolled board position
  // carries over to Capture etc. and the new screen appears "half scrolled".
  useEffect(() => {
    try {
      window.scrollTo(0, 0);
      const m = document.querySelector('.main');
      if (m) m.scrollTop = 0;
    } catch (e) {}
  }, [route]);

  // Restore simulated connections from a previous session
  useEffect(() => {
    const sc = DumpStore.getState().savedConnections || {};
    if (!DumpAPI.simConnections()) return;
    const patch = {};
    if (sc.google) {
      patch.google = {
        connected: true, demo: true, token: null,
        email: DumpDemo.persona.email,
        events: DumpDemo.calendarEvents,
        eventsDate: DumpUtil.todayISO()
      };
    }
    if (sc.slack) {
      patch.slack = { connected: true, demo: true, workspace: DumpDemo.persona.workspace };
    }
    if (Object.keys(patch).length) DumpStore.set(patch);
  }, []);

  // Keyboard shortcuts (desktop)
  useEffect(() => {
    const onKey = (e) => {
      const tag = document.activeElement && document.activeElement.tagName || '';
      const typing = tag === 'INPUT' || tag === 'TEXTAREA' || document.activeElement && document.activeElement.isContentEditable;
      if (e.key === 'Escape') {
        if (DumpStore.getState().settingsOpen) {DumpStore.set({ settingsOpen: false });return;}
        if (typing) document.activeElement.blur();
        return;
      }
      if (typing || e.metaKey || e.ctrlKey || e.altKey) return;
      if (e.key === 'n' || e.key === 'N' || e.key === 'd' || e.key === 'D') {
        e.preventDefault();
        DumpStore.set({ route: 'capture' });
        setTimeout(() => {if (window.__focusDump) window.__focusDump();}, 80);
      }
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);

  const openCount = tasks.filter((t) => (window.isActiveTask ? isActiveTask(t) : !t.done) && !t.trackDaily && !(t.minutes && t.minutes <= 2)).length;
  const twoMinCount = tasks.filter((t) => (window.isActiveTask ? isActiveTask(t) : !t.done) && !t.trackDaily && t.minutes && t.minutes <= 2 && (!t.dueDate || t.dueDate === DumpUtil.todayISO())).length;
  const sugCount = suggestions.filter((s) => !s.dismissed).length;
  const inboxCount = tasks.filter((t) => (t.bucket === 'inbox' || t.needsSorting) && !t.done).length;
  const binCount = tasks.filter((t) => t.status === 'binned').length;
  const groceryCount = (state.groceries || []).filter((g) => !g.done).length;

  const Section = {
    today: TodaySection,
    capture: CaptureSection,
    clarify: ClarifySection,
    tasks: TasksSection,
    groceries: GroceriesSection,
    calendar: CalendarSection,
    anchors: AnchorsSection,
    done: DoneSection,
    bin: BinSection,
    connect: ConnectSection
  }[route] || CaptureSection;

  const navBtn = (item, cls) =>
  <button
    key={item.key}
    data-tour={'nav-' + item.key}
    className={cls + (route === item.key ? ' active' : '')}
    onClick={() => DumpStore.set({ route: item.key })}>
    
      {Icons[item.icon](cls === 'tab-item' ? 21 : 18)}
      <span>{item.label}</span>
      {cls === 'nav-item' && item.key === 'today' && twoMinCount > 0 ? <span className="nav-badge alt">{twoMinCount}</span> : null}
      {cls === 'nav-item' && item.key === 'tasks' && openCount > 0 ? <span className="nav-badge">{openCount}</span> : null}
      {cls === 'nav-item' && item.key === 'groceries' && groceryCount > 0 ? <span className="nav-badge muted">{groceryCount}</span> : null}
      {cls === 'nav-item' && item.key === 'connect' && sugCount > 0 ? <span className="nav-badge">{sugCount}</span> : null}
    </button>;


  return (
    <div className={'app' + (pomoModalOpen ? ' pomodoro-active' : '')}>
      <aside className="sidebar">
        <div className="brand">
          <span className="brand-mark"></span>
          <h1 className="brand-name" style={{ fontSize: "38px" }}>Enstow</h1>
        </div>
        <nav className="nav">
          {NAV.map((item) => (
            <React.Fragment key={item.key}>
              {navBtn(item, 'nav-item')}
              {item.key === 'capture' && inboxCount > 0 ? (
                <button className={'nav-item' + (route === 'clarify' ? ' active' : '')}
                  data-tour="nav-clarify"
                  onClick={() => DumpStore.set((s) => ({
                    tasks: s.tasks.map((t) => ((t.needsSorting && !t.done) ? { ...t, bucket: 'inbox', needsSorting: false, clarify: true, clarifyKind: t.clarifyKind || 'vague' } : t)),
                    route: 'clarify'
                  }))}
                  title="Quick questions about things you captured">
                  {Icons.chat(18)}
                  <span>Clarify</span>
                  <span className="nav-badge">{inboxCount}</span>
                </button>
              ) : null}
            </React.Fragment>
          ))}
        </nav>
        <div className="sidebar-foot">
          <button className={'nav-item' + (route === 'bin' ? ' active' : '')} onClick={() => DumpStore.set({ route: 'bin' })}>
            {Icons.trash(18)}
            <span>Bin</span>
            {binCount > 0 ? <span className="nav-badge muted">{binCount}</span> : null}
          </button>
          <button className="nav-item nav-sweep" data-tour="nav-sweep" onClick={() => window.startSweep && window.startSweep()} title="Run a weekly sweep">
            {Icons.sweep(18)}
            <span>Sweep</span>
          </button>
          <button className="nav-item" onClick={() => DumpStore.set({ settingsOpen: true })}>
            {Icons.gear(18)}
            <span>Settings</span>
          </button>
        </div>
      </aside>

      <main className="main">
        <Section />
      </main>

      <button className="icon-btn mobile-gear" onClick={() => DumpStore.set({ settingsOpen: true })} aria-label="Settings">
        {Icons.gear(20)}
      </button>
      <button className="icon-btn mobile-bin" onClick={() => DumpStore.set({ route: 'bin' })} aria-label="Bin">
        {Icons.trash(20)}
        {binCount > 0 ? <span className="mobile-bin-dot"></span> : null}
      </button>

      <nav className="tabbar">
        {NAV.map((item) => navBtn(item, 'tab-item'))}
      </nav>

      {settingsOpen ? <SettingsPanel /> : null}
      {scheduler && scheduler.open ? <Scheduler date={scheduler.date} onClose={() => DumpAPI.closeScheduler()} /> : null}
      <SweepModal />
      <PomodoroModal />
      <BreakPill />
      <AuthSimModal />
      <ToastStack />
    </div>);

}

function mountNudge() {
  if (window.__nudgeMounted) return;
  window.__nudgeMounted = true;
  const root = ReactDOM.createRoot(document.getElementById('root'));

  const onboarded = (() => { try { return localStorage.getItem('braindump.onboarded') === 'true'; } catch (e) { return false; } })();
  const hasTasks = (() => { try { return (DumpStore.getState().tasks || []).length > 0; } catch (e) { return false; } })();

  // Let anyone replay the first-run flow from the console during the beta.
  window.__resetOnboarding = function () {
    try { localStorage.removeItem('braindump.onboarded'); } catch (e) {}
    window.__nudgeMounted = false;
    location.reload();
  };

  // Preview onboarding as an overlay WITHOUT touching tasks or the flag —
  // handy for reviewing the flow on a populated demo board.
  window.__previewOnboarding = function () {
    var host = document.getElementById('onb-preview');
    if (host) { host.remove(); }
    host = document.createElement('div');
    host.id = 'onb-preview';
    document.body.appendChild(host);
    var r = ReactDOM.createRoot(host);
    r.render(<OnboardingFlow onComplete={() => { r.unmount(); host.remove(); }} />);
  };

  // First run: empty board and not yet onboarded → show onboarding instead of the app.
  // (Demo users who load prefilled data have tasks, so they skip straight in.)
  if (!onboarded && !hasTasks) {
    const finish = (route) => {
      try { localStorage.setItem('braindump.onboarded', 'true'); } catch (e) {}
      DumpStore.set({ route: route === 'tasks' ? 'tasks' : 'capture' });
      root.render(<App />);
    };
    root.render(<OnboardingFlow onComplete={finish} />);
    return;
  }

  root.render(<App />);
}
// No client-side gate — access is handled at the host (e.g. Cloudflare Access).
mountNudge();