// Strategies top-level — switches between list and detail views.
// State-routed within the tab (no URL router); URL hash mirrors view
// for shareability ('' = list, '#strategy/<id>' = detail).

window.Strategies = function Strategies({ goto, session, isElevated }) {
  const { useState, useEffect } = React;
  const [view, setView] = useState(() => _readHash());
  const [newModalOpen, setNewModalOpen] = useState(false);

  const list = window.useApi(() => window.EQ_API.getStrategies(true), []);

  // Sync state ↔ URL hash
  useEffect(() => {
    const onHashChange = () => setView(_readHash());
    window.addEventListener('hashchange', onHashChange);
    return () => window.removeEventListener('hashchange', onHashChange);
  }, []);
  useEffect(() => {
    const hash = view.type === 'detail' ? `#strategy/${view.id}` : '';
    if (window.location.hash !== hash) window.history.replaceState(null, '', hash || window.location.pathname);
  }, [view]);

  // Frontend-only guard (server still enforces require_elevated). Non-admins
  // see a denial banner instead of the page contents.
  const canSee = isElevated === true
    ? true
    : (window.EQ_IS_AUTHORIZED ? window.EQ_IS_AUTHORIZED(session) : false);
  if (!canSee) {
    return (
      <div>
        <window.TopBar title="Strategies"/>
        <div style={{ padding: 32 }}>
          <window.ErrorBanner error={{ message: 'Strategies is admin-only. Contact your administrator for access.' }}/>
        </div>
      </div>
    );
  }

  return (
    <>
      {view.type === 'list' && (
        <window.StrategiesList
          list={list}
          onOpen={(id) => setView({ type: 'detail', id })}
          onNew={() => setNewModalOpen(true)}
        />
      )}
      {view.type === 'detail' && (
        <window.StrategyDetail
          strategyId={view.id}
          onBack={() => { setView({ type: 'list' }); list.reload(); }}
          onEdited={() => list.reload()}
          onDeleted={() => { setView({ type: 'list' }); list.reload(); }}
        />
      )}
      {newModalOpen && (
        <window.StrategyEditModal
          existing={null}
          onClose={() => setNewModalOpen(false)}
          onSaved={(saved) => { setNewModalOpen(false); list.reload(); setView({ type: 'detail', id: saved.id }); }}
        />
      )}
    </>
  );
};

function _readHash() {
  const m = window.location.hash.match(/^#strategy\/([a-zA-Z0-9-]+)$/);
  return m ? { type: 'detail', id: m[1] } : { type: 'list' };
}
