// 7play — top-level app: provider, router, cmd+k shortcut, tweaks

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "stepperStyle": "numbered"
}/*EDITMODE-END*/;

function App() {
  return (
    <StoreProvider>
      <AppInner />
    </StoreProvider>
  );
}

function AppInner() {
  const { state, actions } = useStore();
  const [tweaksOpen, setTweaksOpen] = React.useState(false);

  // Tweaks protocol
  React.useEffect(() => {
    const onMessage = (e) => {
      const d = e.data;
      if (!d || typeof d !== 'object') return;
      if (d.type === '__activate_edit_mode') setTweaksOpen(true);
      if (d.type === '__deactivate_edit_mode') setTweaksOpen(false);
      if (d.type === '__toggle_edit_mode') setTweaksOpen(o => !o);
    };
    window.addEventListener('message', onMessage);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMessage);
  }, []);

  // Global keyboard shortcuts
  React.useEffect(() => {
    const onKey = (e) => {
      // ignore when typing
      const inField = ['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement?.tagName);
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        actions.openModal({ kind: 'cmdk' });
        return;
      }
      if (inField) return;
      if (state.route.kind === 'session') {
        if (e.key === 'ArrowLeft') { window.dispatchEvent(new CustomEvent('7play:prev-stage')); }
        if (e.key === 'ArrowRight') { window.dispatchEvent(new CustomEvent('7play:next-stage')); }
        if (e.key === 'a' && e.shiftKey) { window.dispatchEvent(new CustomEvent('7play:approve')); }
        if (e.key === 'r' && e.shiftKey) { window.dispatchEvent(new CustomEvent('7play:reject')); }
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [state.route, actions]);

  const setStepperAndPersist = (val) => {
    actions.setStepperStyle(val);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { stepperStyle: val } }, '*');
  };

  const route = state.route;
  const session = route.kind === 'session' ? state.sessions[route.sessionId] : null;
  const game = session ? window.GAMES.find(g => g.id === session.gameId) : null;
  const isWorkspace = route.kind === 'session' && session && game;

  // Re-render when the workspace reports a stage change so the no-chat
  // class can be recomputed.
  const [, forceStageRender] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    const h = () => forceStageRender();
    window.addEventListener('7play:stage-changed', h);
    return () => window.removeEventListener('7play:stage-changed', h);
  }, []);

  // Chat rail only renders on Build (stage 2) and now docks on the LEFT
  // next to the icon rail so it doesn't push main content.
  const currentStage = window.__currentStage ?? 0;
  const chatVisible = isWorkspace && currentStage === 2;

  const appCls = [
    'app',
    route.kind === 'home' ? 'has-sidebar' : 'no-sidebar',
    !chatVisible && 'no-chat',
    chatVisible && 'chat-left',
    chatVisible && state.chatCollapsed && 'chat-collapsed',
  ].filter(Boolean).join(' ');

  return (
    <div className={appCls} data-screen-label={routeLabel(route, session, game)}>
      {route.kind === 'home' && <Sidebar onNav={(k, id) => actions.nav(k, id)} activeSessionId={session?.id} />}

      {route.kind === 'home' && <div className="main"><SessionsList /></div>}
      {route.kind === 'new' && <div className="main"><NewSessionWizard /></div>}
      {isWorkspace && <SessionWorkspace session={session} game={game} stepperVariant={state.stepperStyle} />}

      <ModalHost />
      <ToastHost />

      {tweaksOpen && (
        <TweaksPanel
          stepperStyle={state.stepperStyle}
          setStepperStyle={setStepperAndPersist}
          onClose={() => setTweaksOpen(false)}
        />
      )}
    </div>
  );
}

function routeLabel(route, session, game) {
  if (route.kind === 'home') return 'Sessions list';
  if (route.kind === 'new') return 'New Session wizard';
  if (route.kind === 'session' && game) return `Workspace · ${game.name} · stage ${session.stage + 1}`;
  return '7play';
}

function TweaksPanel({ stepperStyle, setStepperStyle, onClose }) {
  return (
    <div className="tweaks-panel">
      <div className="tweaks-head">
        <Icon name="sparkle" size={14} />
        <div className="t-title">Tweaks</div>
        <div className="close" onClick={onClose}>×</div>
      </div>
      <div className="tweak-group">
        <div className="tweak-label">Stage stepper style</div>
        <div className="tweak-options">
          {[['numbered', 'Segments'], ['pills', 'Pills'], ['dots', 'Dots']].map(([val, label]) => (
            <div key={val} className={`tweak-opt ${stepperStyle === val ? 'active' : ''}`} onClick={() => setStepperStyle(val)}>{label}</div>
          ))}
        </div>
      </div>
      <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--line)', fontSize: 11, color: 'var(--ink-faint)' }}>
        Open a session workspace to preview. Try ⌘K for command palette.
      </div>
    </div>
  );
}

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