// assets/app.jsx — top-level app shell, sidebar nav, routing, tweaks wiring
// Routes use hash-based routing (#/sessions, #/sessions/[id], etc).

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "posthog",
  "density": "compact",
  "traceLayout": "timeline",
  "iconStyle": "emoji",
  "sidebarMode": "expanded",
  "dashboardCharts": "default"
}/*EDITMODE-END*/;

// Map "dark/light" toggle to a palette in the same family.
function isDarkPalette(p) { return p !== 'stripe'; }

// ─── Router ────────────────────────────────────────────────────────────────
function useHashRoute() {
  const [route, setRoute] = React.useState(() => window.location.hash.slice(1) || '/');
  React.useEffect(() => {
    const h = () => setRoute(window.location.hash.slice(1) || '/');
    window.addEventListener('hashchange', h);
    return () => window.removeEventListener('hashchange', h);
  }, []);
  return [route, (path) => { window.location.hash = path; }];
}

function matchRoute(route, pattern) {
  // pattern: /sessions or /sessions/:id
  const r = route.split('/').filter(Boolean);
  const p = pattern.split('/').filter(Boolean);
  if (r.length !== p.length) return null;
  const params = {};
  for (let i = 0; i < p.length; i++) {
    if (p[i].startsWith(':')) params[p[i].slice(1)] = r[i];
    else if (p[i] !== r[i]) return null;
  }
  return params;
}

// ─── Sidebar ───────────────────────────────────────────────────────────────
const NAV_ITEMS = [
  { type: 'label', label: 'Observability' },
  { icon: 'dashboard', label: 'AI dashboard', path: '/' },
  { icon: 'sessions',  label: 'Sessions',     path: '/sessions', badge: '247' },
  { icon: 'hook',      label: 'Hook events',  path: '/hooks',    badge: '3', badgeKind: 'alert' },
  { icon: 'deploy',    label: 'Deployments',  path: '/deployments' },
  { icon: 'cost',      label: 'AI cost',      path: '/cost' },
  { type: 'sep' },
  { type: 'label', label: 'Commerce' },
  { icon: 'trend',     label: 'Overview',     path: '/commerce' },
  { icon: 'package',   label: 'Stores',       path: '/stores' },
  { icon: 'user',      label: 'Users',        path: '/users' },
  { type: 'sep' },
  { type: 'label', label: 'AI ops' },
  { icon: 'fileText',  label: 'Prompts',      path: '/prompts' },
  { icon: 'alert',     label: 'Alerts',       path: '/alerts' },
  { icon: 'bell',      label: 'Notifications',path: '/notifications' },
  { icon: 'health',    label: 'System health',path: '/health' },
  { icon: 'tools',     label: 'Dev tools',    path: '/devtools' },
];

function Sidebar({ route, go, mode, onToggleMode, tweaks, setTweak }) {
  return (
    <aside className="sidebar">
      <div className="sidebar-head">
        <div className="sidebar-logo">SQ</div>
        <div className="sidebar-brand">ShopQuantum <span className="env">admin · prod</span></div>
      </div>
      <nav className="nav">
        {NAV_ITEMS.map((it, i) => {
          if (it.type === 'sep')   return <div key={i} style={{ height: 1, margin: '8px 6px', background: 'var(--border-subtle)' }} />;
          if (it.type === 'label') return <div key={i} className="nav-section-label">{it.label}</div>;
          const active = route === it.path || (it.path !== '/' && route.startsWith(it.path));
          return (
            <div key={i} className={`nav-item ${active ? 'active' : ''}`} onClick={() => go(it.path)} title={it.label}>
              <Icon name={it.icon} size={15} className="nav-icon" />
              <span className="nav-label">{it.label}</span>
              {it.badge && <span className={`nav-badge ${it.badgeKind || ''}`}>{it.badge}</span>}
            </div>
          );
        })}
      </nav>
      <div className="sidebar-foot">
        <div className="avatar">HV</div>
        <div className="sidebar-foot-text" style={{ flex: 1, overflow: 'hidden' }}>
          <div className="email">huy@shopquantum.io</div>
          <div className="role">admin · oncall</div>
        </div>
        <button className="btn icon-only ghost" title={mode === 'dark' ? 'Switch to light' : 'Switch to dark'} onClick={onToggleMode}>
          <Icon name={mode === 'dark' ? 'sun' : 'moon'} size={14} />
        </button>
      </div>
    </aside>
  );
}

// ─── Topbar ────────────────────────────────────────────────────────────────
function Topbar({ crumbs, actions, onToggleSidebar }) {
  return (
    <header className="topbar">
      <button className="icon-btn" onClick={onToggleSidebar} title="Toggle sidebar">
        <Icon name="panelLeft" size={15} />
      </button>
      <div className="breadcrumbs">
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <Icon name="chevron" size={12} className="sep" />}
            {c.path ? <a href={`#${c.path}`} style={{ color: 'var(--text-secondary)' }}>{c.label}</a> :
              <span className={i === crumbs.length - 1 ? 'current' : ''}>{c.label}</span>}
          </React.Fragment>
        ))}
      </div>
      <div className="spacer" />
      <div className="global-search">
        <Icon name="search" size={13} />
        <span>Search sessions, projects, merchants…</span>
        <kbd>⌘K</kbd>
      </div>
      {actions}
      <button className="icon-btn" title="Notifications">
        <Icon name="bell" size={15} />
        <span className="dot" />
      </button>
      <button className="icon-btn" title="Settings">
        <Icon name="settings" size={15} />
      </button>
    </header>
  );
}

// ─── Main App ──────────────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, go] = useHashRoute();
  const [sidebarCollapsed, setSidebarCollapsed] = React.useState(t.sidebarMode === 'collapsed');

  // Apply palette + density via data-attrs on <html>
  React.useEffect(() => {
    document.documentElement.dataset.palette = t.palette;
    document.documentElement.dataset.density = t.density;
    document.documentElement.dataset.traceLayout = t.traceLayout;
    document.documentElement.dataset.traceIcons = t.iconStyle;
  }, [t.palette, t.density, t.traceLayout, t.iconStyle]);

  // Sidebar auto-collapse mode
  React.useEffect(() => {
    if (t.sidebarMode === 'collapsed') setSidebarCollapsed(true);
    else if (t.sidebarMode === 'expanded') setSidebarCollapsed(false);
    else if (t.sidebarMode === 'auto') setSidebarCollapsed(route.startsWith('/sessions/') && route.split('/').length > 2);
  }, [t.sidebarMode, route]);

  const onToggleMode = () => {
    setTweak('palette', isDarkPalette(t.palette) ? 'stripe' : 'posthog');
  };
  const mode = isDarkPalette(t.palette) ? 'dark' : 'light';

  // Route → screen
  const isLogin = route === '/login';
  if (isLogin) return <ScreenLogin onLogin={() => go('/')} />;

  let body, crumbs, actions = null;
  if (route === '/') {
    body = <ScreenDashboard t={t} setTweak={setTweak} />;
    crumbs = [{ label: 'Dashboard' }];
  } else if (route === '/sessions') {
    body = <ScreenSessions go={go} t={t} />;
    crumbs = [{ label: 'Sessions' }];
  } else if (matchRoute(route, '/sessions/:id')) {
    const { id } = matchRoute(route, '/sessions/:id');
    body = <ScreenSessionDetail id={id} go={go} t={t} setTweak={setTweak} />;
    crumbs = [{ label: 'Sessions', path: '/sessions' }, { label: shortId(id, 8) }];
  } else if (route === '/hooks') {
    body = <ScreenHooks go={go} t={t} />;
    crumbs = [{ label: 'Hook events' }];
  } else if (route === '/deployments') {
    body = <ScreenDeployments go={go} t={t} />;
    crumbs = [{ label: 'Deployments' }];
  } else if (matchRoute(route, '/deployments/:id')) {
    const { id } = matchRoute(route, '/deployments/:id');
    body = <ScreenDeploymentDetail id={id} go={go} />;
    crumbs = [{ label: 'Deployments', path: '/deployments' }, { label: shortId(id, 8) }];
  } else if (route === '/cost') {
    body = <ScreenCost go={go} t={t} />;
    crumbs = [{ label: 'Cost & usage' }];
  } else if (route === '/alerts') {
    body = <ScreenAlerts t={t} />;
    crumbs = [{ label: 'Alerts' }];
  } else if (route === '/notifications') {
    body = <ScreenNotifications t={t} />;
    crumbs = [{ label: 'Notifications' }];
  } else if (route === '/health') {
    body = <ScreenHealth t={t} />;
    crumbs = [{ label: 'System health' }];
  } else if (route === '/devtools') {
    body = <ScreenDevTools t={t} />;
    crumbs = [{ label: 'Dev tools' }];
  } else if (route === '/commerce') {
    body = <ScreenCommerceOverview go={go} />;
    crumbs = [{ label: 'Commerce' }, { label: 'Overview' }];
  } else if (route === '/stores') {
    body = <ScreenStores go={go} />;
    crumbs = [{ label: 'Commerce', path: '/commerce' }, { label: 'Stores' }];
  } else if (matchRoute(route, '/stores/:id')) {
    const { id } = matchRoute(route, '/stores/:id');
    body = <ScreenStoreDetail id={id} go={go} />;
    crumbs = [{ label: 'Commerce', path: '/commerce' }, { label: 'Stores', path: '/stores' }, { label: shortId(id, 8) }];
  } else if (route === '/users') {
    body = <ScreenUsers go={go} />;
    crumbs = [{ label: 'Commerce', path: '/commerce' }, { label: 'Users' }];
  } else if (matchRoute(route, '/users/:id')) {
    const { id } = matchRoute(route, '/users/:id');
    body = <ScreenUserDetail id={id} go={go} />;
    crumbs = [{ label: 'Commerce', path: '/commerce' }, { label: 'Users', path: '/users' }, { label: shortId(id, 8) }];
  } else if (route === '/prompts') {
    body = <ScreenPrompts t={t} />;
    crumbs = [{ label: 'AI ops' }, { label: 'Prompts' }];
  } else {
    body = <div className="page"><div className="empty-state">Route not found: <Mono>{route}</Mono><br/><br/><button className="btn primary" onClick={() => go('/')}>Go to dashboard</button></div></div>;
    crumbs = [{ label: '404' }];
  }

  return (
    <div className={`shell ${sidebarCollapsed ? 'sidebar-collapsed' : ''}`}>
      <Sidebar route={route} go={go} mode={mode} onToggleMode={onToggleMode} tweaks={t} setTweak={setTweak} />
      <div className="main">
        <Topbar crumbs={crumbs} actions={actions} onToggleSidebar={() => setSidebarCollapsed(c => !c)} />
        <div className="content">{body}</div>
      </div>
      <AdminTweaks t={t} setTweak={setTweak} />
    </div>
  );
}

// ─── Tweaks panel ──────────────────────────────────────────────────────────
function AdminTweaks({ t, setTweak }) {
  const PALETTE_PREVIEWS = {
    posthog: ['#000000', '#0a0a0a', '#f5bd02', '#fafafa'],
    grafana: ['#0b0c14', '#181b22', '#f55f00', '#ecedee'],
    sentry:  ['#181225', '#29213f', '#7553ff', '#f5f0ff'],
    stripe:  ['#f6f9fc', '#ffffff', '#635bff', '#0a2540'],
  };
  return (
    <TweaksPanel>
      <TweakSection label="Palette / Theme" />
      <TweakColor label="Palette" value={PALETTE_PREVIEWS[t.palette]}
        options={Object.values(PALETTE_PREVIEWS)}
        onChange={(v) => {
          const found = Object.entries(PALETTE_PREVIEWS).find(([, arr]) => arr.join() === v.join());
          if (found) setTweak('palette', found[0]);
        }} />
      <TweakRadio label="Palette name" value={t.palette}
        options={['posthog', 'grafana', 'sentry', 'stripe']}
        onChange={(v) => setTweak('palette', v)} />

      <TweakSection label="Information density" />
      <TweakRadio label="Table density" value={t.density}
        options={['compact', 'comfortable', 'spacious']}
        onChange={(v) => setTweak('density', v)} />

      <TweakSection label="Trace viewer" />
      <TweakRadio label="Layout" value={t.traceLayout}
        options={['timeline', 'log', 'chat']}
        onChange={(v) => setTweak('traceLayout', v)} />
      <TweakRadio label="Event icons" value={t.iconStyle}
        options={['emoji', 'lucide', 'border']}
        onChange={(v) => setTweak('iconStyle', v)} />

      <TweakSection label="Dashboard" />
      <TweakRadio label="Charts" value={t.dashboardCharts}
        options={['default', 'sparkline', 'minimal']}
        onChange={(v) => setTweak('dashboardCharts', v)} />

      <TweakSection label="Sidebar" />
      <TweakRadio label="Mode" value={t.sidebarMode}
        options={['expanded', 'collapsed', 'auto']}
        onChange={(v) => setTweak('sidebarMode', v)} />
    </TweaksPanel>
  );
}

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