// Loop MVP — App shell, persona switcher, router, tweaks

const TWEAK_DEFAULS = /*EDITMODE-BEGIN*/{
  "persona": "principal",
  "darkStatus": false,
  "showOrbits": true
}/*EDITMODE-END*/;

const TABS = [
  { key: 'home', label: 'Home', icon: 'home' },
  { key: 'meetings', label: 'Meetings', icon: 'calendar' },
  { key: 'people', label: 'People', icon: 'users' },
  { key: 'agents', label: 'Agents', icon: 'sparkles' },
  { key: 'more', label: 'More', icon: 'grid' },
];

// Map every route key to its primary tab so the tab bar highlights correctly
const ROUTE_TO_TAB = {
  home: 'home',
  meetings: 'meetings', brief: 'meetings', live: 'meetings', recap: 'meetings',
  people: 'people', person: 'people',
  agents: 'agents', 'agent-chat': 'agents', 'agent-builder': 'agents',
  more: 'more',
  notifications: 'home', tasks: 'more', dataroom: 'more', skills: 'more',
  compare: 'more', settings: 'more',
};

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULS);
  const persona = t.persona;
  // On a real phone IOSDevice is frameless (no fake status bar), so the
  // shell shouldn't reserve the 62px the mockup status bar needs.
  const isPhone = useIsPhone();

  // Per-persona history so switching personas doesn't carry you mid-flow
  const [history, setHistory] = React.useState({ principal: [{ route: 'home' }], moderator: [{ route: 'home' }] });
  const stack = history[persona];
  const current = stack[stack.length - 1];

  const go = React.useCallback((route, params) => {
    setHistory(h => ({ ...h, [persona]: [...h[persona], { route, params }] }));
  }, [persona]);

  // Provide a back action by walking the stack
  const back = React.useCallback(() => {
    setHistory(h => {
      const s = h[persona];
      if (s.length <= 1) return h;
      return { ...h, [persona]: s.slice(0, -1) };
    });
  }, [persona]);

  const goTab = (tabKey) => {
    setHistory(h => ({ ...h, [persona]: [{ route: tabKey }] }));
  };

  const screen = renderScreen(current.route, { persona, go: (r, p) => r === 'back' ? back() : go(r, p), params: current.params });

  const tab = ROUTE_TO_TAB[current.route] || 'home';
  const hideTabBar = current.route === 'live' || current.route === 'agent-chat';

  return (
    <IOSDevice width={402} height={874} dark={t.darkStatus}>
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column',
        background: 'var(--canvas)', position: 'relative', overflow: 'hidden',
        // box-sizing keeps the column inside the 874px device height —
        // without it, paddingTop pushes the TabBar past the bottom and
        // it gets clipped by the frame's overflow:hidden.
        boxSizing: 'border-box',
        // framed mockup: reserve the 62px fake status-bar height so the
        // header sits flush below it. Frameless phone mode: the real OS
        // status bar / notch is handled by safe-area insets, so no offset.
        paddingTop: isPhone ? 0 : 62,
        // Phone: the TabBar is position:fixed (out of flow), so reserve
        // its height (~63px + home-bar inset) here so content scrolls
        // clear of it. When the TabBar is hidden, only reserve the inset.
        paddingBottom: isPhone
          ? (hideTabBar
              ? 'env(safe-area-inset-bottom, 0px)'
              : 'calc(63px + env(safe-area-inset-bottom, 0px))')
          : 0 }}>
        {screen}
        {!hideTabBar && <TabBar tabs={TABS} current={tab} onPick={goTab} />}
      </div>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Persona">
          <TweakRadio label="View as" value={t.persona}
            options={[
              { value: 'principal', label: 'Principal' },
              { value: 'moderator', label: 'Moderator' },
            ]}
            onChange={(v) => setTweak('persona', v)} />
          <div style={{ fontSize: 11, color: 'var(--slate)', marginTop: 8, lineHeight: 1.4, padding: '0 4px' }}>
            Two personas, one product — same core, persona-specific surface and rituals.
          </div>
        </TweakSection>

        <TweakSection label="Theme">
          <TweakToggle label="Dark status bar" value={t.darkStatus}
            onChange={(v) => setTweak('darkStatus', v)} />
          <TweakToggle label="Orbital arcs" value={t.showOrbits}
            onChange={(v) => setTweak('showOrbits', v)} />
        </TweakSection>

        <TweakSection label="Quick nav">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, padding: '4px' }}>
            {[
              ['home', 'Home'], ['meetings', 'Meetings'], ['brief', 'Brief'],
              ['live', 'Live'], ['recap', 'Recap'], ['people', 'People'],
              ['person', 'Person'], ['agents', 'Agents'], ['agent-chat', 'Agent chat'],
              ['agent-builder', 'Build agent'], ['more', 'More'], ['tasks', 'Tasks'],
              ['notifications', 'Alerts'], ['dataroom', 'Dataroom'],
              ['compare', 'Compare'], ['skills', 'Skills'], ['settings', 'Settings'],
            ].map(([r, l]) => (
              <button key={r} onClick={() => go(r)} style={{
                padding: '5px 9px', borderRadius: 999,
                border: '1px solid rgba(20,20,19,0.18)',
                background: current.route === r ? 'var(--ink)' : 'transparent',
                color: current.route === r ? 'var(--canvas)' : 'var(--ink)',
                fontSize: 10, fontWeight: 500, cursor: 'pointer',
              }}>{l}</button>
            ))}
          </div>
        </TweakSection>
      </TweaksPanel>
    </IOSDevice>
  );
}

function renderScreen(route, ctx) {
  switch (route) {
    case 'home': return <HomeScreen {...ctx} />;
    case 'meetings': return <MeetingsScreen {...ctx} />;
    case 'brief': return <BriefScreen {...ctx} />;
    case 'live': return <LiveMeetingScreen {...ctx} />;
    case 'recap': return <RecapScreen {...ctx} />;
    case 'people': return <PeopleScreen {...ctx} />;
    case 'person': return <PersonScreen {...ctx} />;
    case 'agents': return <AgentsScreen {...ctx} />;
    case 'agent-chat': return <AgentChatScreen {...ctx} />;
    case 'agent-builder': return <AgentBuilderScreen {...ctx} />;
    case 'more': return <MoreScreen {...ctx} />;
    case 'notifications': return <NotificationsScreen {...ctx} />;
    case 'tasks': return <TasksScreen {...ctx} />;
    case 'dataroom': return <DataroomScreen {...ctx} />;
    case 'skills': return <SkillsScreen {...ctx} />;
    case 'compare': return <CompareScreen {...ctx} />;
    case 'settings': return <SettingsScreen {...ctx} />;
    default: return <HomeScreen {...ctx} />;
  }
}

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