// shell-v2.jsx
// ─────────────────────────────────────────────────────────────────────────────
// New shell (dark sidebar + top bar) matching the PerduraCEO design reference.
// Registers window.ShellV2. Built ALONGSIDE the existing src/shell.jsx Sidebar —
// nothing is deleted. Not active until app.jsx opts in.
//
// IMPORTANT: nav `key`s below are the app's REAL page keys (the ones app.jsx
// switches on — mostly underscore_case, with `audit-log` hyphenated to match
// app.jsx). Using the wrong key renders a blank page, so these are mapped
// against the verified list in app.jsx. setPage(key) is the single source of
// truth for navigation; app.jsx already syncs the URL on page change, so we do
// NOT call PerduraRouter.set (its setPath() takes a route object, not a key).
// ─────────────────────────────────────────────────────────────────────────────
(function () {
  const h = React.createElement;
  const { useState } = React;

  // label/icon are presentation; `key` MUST be a real app.jsx page key.
  const NAV_GROUPS = [
    { label: 'OVERVIEW', items: [
      { key: 'overview',            label: 'Dashboard',        icon: '◉' },
      { key: 'board_reports',       label: 'Board Report',     icon: '▣' },
    ]},
    { label: 'GENERAL LEDGER', items: [
      { key: 'income_statement',    label: 'Income Statement', icon: '▤' },
      { key: 'balance_sheet',       label: 'Balance Sheet',    icon: '▦' },
      { key: 'trial_balance',       label: 'Trial Balance',    icon: '▥' },
      { key: 'cash_flow_statement', label: 'Cash Flow',        icon: '◇' },
    ]},
    { label: 'ANALYTICS', items: [
      { key: 'revenue_intelligence', label: 'Revenue',         icon: '↗' },
      { key: 'expenses',            label: 'Expenses',         icon: '↘' },
      { key: 'working_capital',     label: 'Working Capital',  icon: '⟳' },
      { key: 'arap',                label: 'AR / AP',          icon: '⌗' },
      { key: 'kpi_scorecard',       label: 'KPI Scorecard',    icon: '◎' },
      { key: 'margin',              label: 'Margin Analysis',  icon: '◐' },
      { key: 'inventory',           label: 'Inventory',        icon: '▢' },
    ]},
    { label: 'INTELLIGENCE', items: [
      { key: 'opportunities',       label: 'Savings',          icon: '✦' },
      { key: 'exceptions',          label: 'Exceptions',       icon: '!' },
      { key: 'cfo_briefings',       label: 'Briefing',         icon: '✎' },
      { key: 'decisions',           label: 'Initiatives',      icon: '◆' },
    ]},
    { label: 'PLANNING', items: [
      { key: 'budget',              label: 'Budget vs Actual', icon: '▤' },
      { key: 'cash_forecast',       label: '13-Week Forecast', icon: '◷' },
    ]},
    { label: 'OPERATIONS', items: [
      { key: 'payroll',             label: 'Payroll',          icon: '☷' },
      { key: 'capex',               label: 'CAPEX Register',   icon: '⌂' },
    ]},
    { label: 'ADMIN', items: [
      { key: 'audit-log',           label: 'Audit Log',        icon: '▤' },   // hyphenated in app.jsx
      { key: 'category_mapping',    label: 'Category Mapping', icon: '☰' },
      { key: 'settings_profile',    label: 'Settings',         icon: '⚙' },
    ]},
  ];

  function ShellV2({ page, setPage, companyName, companyProfile, periodSelector, onAIAnalyse, children }) {
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [collapsedGroups, setCollapsedGroups] = useState({});

    const toggleGroup = (label) => setCollapsedGroups(g => ({ ...g, [label]: !g[label] }));

    const navigate = (key) => {
      if (typeof setPage === 'function') setPage(key);
      else if (typeof window.__perduraSetPage === 'function') window.__perduraSetPage(key);
      setSidebarOpen(false);
      // URL sync is handled by app.jsx's page-change effect — do not call
      // PerduraRouter.set here (it expects a route object, not a page key).
    };

    const runAI = () => {
      if (typeof onAIAnalyse === 'function') return onAIAnalyse();
      if (typeof window.openAIAnalyse === 'function') return window.openAIAnalyse({ page });
      if (typeof window.__perduraSetPage === 'function') return window.__perduraSetPage('cfo_briefings');
    };

    const sidebarStyle = {
      width: '220px', minHeight: '100vh', background: '#0f1923',
      display: 'flex', flexDirection: 'column', flexShrink: 0,
      position: 'fixed', top: 0, left: 0, bottom: 0,
      overflowY: 'auto', zIndex: 100, transition: 'transform .25s ease',
    };

    return h('div', { style: { display: 'flex', minHeight: '100vh', fontFamily: 'Inter, sans-serif', background: '#f8f9fa' } },

      // Mobile overlay
      sidebarOpen && h('div', {
        onClick: () => setSidebarOpen(false),
        style: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,.4)', zIndex: 99 },
      }),

      // Sidebar
      h('div', { style: { ...sidebarStyle, transform: sidebarOpen ? 'translateX(0)' : undefined } },

        // Logo
        h('div', { style: { padding: '18px 16px', borderBottom: '1px solid rgba(255,255,255,.08)', flexShrink: 0 } },
          h('div', { style: { color: '#00b894', fontWeight: '800', fontSize: '15px', letterSpacing: '-.01em' } }, 'Perdura Capital'),
          h('div', { style: { color: 'rgba(255,255,255,.35)', fontSize: '10px', marginTop: '2px', letterSpacing: '.08em', textTransform: 'uppercase' } }, 'CFO Dashboard'),
        ),

        // Company badge
        companyName && h('div', { style: { padding: '10px 16px', background: 'rgba(0,184,148,.08)', borderBottom: '1px solid rgba(0,184,148,.15)', flexShrink: 0 } },
          h('div', { style: { color: 'rgba(255,255,255,.4)', fontSize: '9px', fontWeight: '700', textTransform: 'uppercase', letterSpacing: '.1em' } }, 'Viewing'),
          h('div', { style: { color: '#00b894', fontSize: '11px', fontWeight: '700', marginTop: '2px' } }, companyName),
        ),

        // Nav groups
        h('nav', { style: { flex: 1, padding: '8px 0', overflowY: 'auto' } },
          NAV_GROUPS.map(group =>
            h('div', { key: group.label },
              h('div', {
                onClick: () => toggleGroup(group.label),
                style: { padding: '10px 16px 4px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer' },
              },
                h('div', { style: { color: 'rgba(255,255,255,.25)', fontSize: '9px', fontWeight: '700', letterSpacing: '.12em', textTransform: 'uppercase' } }, group.label),
                h('div', { style: { color: 'rgba(255,255,255,.25)', fontSize: '9px' } }, collapsedGroups[group.label] ? '▶' : '▼'),
              ),
              !collapsedGroups[group.label] && group.items.map(item => {
                const active = page === item.key;
                return h('div', {
                  key: item.key,
                  onClick: () => navigate(item.key),
                  style: {
                    display: 'flex', alignItems: 'center', gap: '10px', padding: '7px 16px',
                    background: active ? 'rgba(0,184,148,.12)' : 'transparent',
                    borderLeft: `3px solid ${active ? '#00b894' : 'transparent'}`,
                    color: active ? '#00b894' : 'rgba(255,255,255,.55)',
                    fontSize: '12px', fontWeight: active ? '600' : '400',
                    cursor: 'pointer', transition: 'all .12s',
                  },
                  onMouseEnter: e => { if (!active) { e.currentTarget.style.color = 'rgba(255,255,255,.85)'; e.currentTarget.style.background = 'rgba(255,255,255,.04)'; } },
                  onMouseLeave: e => { if (!active) { e.currentTarget.style.color = 'rgba(255,255,255,.55)'; e.currentTarget.style.background = 'transparent'; } },
                },
                  h('span', { style: { fontSize: '12px', width: '16px', textAlign: 'center' } }, item.icon),
                  item.label,
                );
              }),
            )
          )
        ),

        // Bottom links
        h('div', { style: { padding: '8px 0', borderTop: '1px solid rgba(255,255,255,.08)', flexShrink: 0 } },
          h('div', {
            onClick: () => navigate('settings_profile'),
            style: { padding: '8px 16px', color: 'rgba(255,255,255,.3)', fontSize: '11px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px' },
          }, '⚙', ' Settings'),
          h('div', {
            onClick: () => window.location.replace('/admin'),
            style: { padding: '8px 16px', color: 'rgba(255,255,255,.3)', fontSize: '11px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px' },
          }, '🔧', ' Admin Portal'),
          h('div', {
            onClick: () => window.supabaseClient?.auth.signOut().then(() => window.location.href = '/login'),
            style: { padding: '8px 16px', color: '#e74c3c', fontSize: '11px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px' },
          }, '⏻', ' Log Out'),
        )
      ),

      // Main content area
      h('div', { style: { marginLeft: '220px', flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 } },

        // Top bar
        h('div', { style: { background: 'white', borderBottom: '1px solid #e9ecef', padding: '0 24px', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'sticky', top: 0, zIndex: 50, flexShrink: 0 } },

          h('div', { style: { display: 'flex', alignItems: 'center', gap: '16px' } },
            // Hamburger (mobile) — shown <768px via .pa-hamburger media rule if present
            h('button', {
              onClick: () => setSidebarOpen(o => !o),
              className: 'pa-hamburger',
              style: { background: 'none', border: 'none', cursor: 'pointer', padding: '4px', display: 'none' },
            },
              h('div', { style: { width: '20px', height: '2px', background: '#0d2040', marginBottom: '4px', borderRadius: '1px' } }),
              h('div', { style: { width: '20px', height: '2px', background: '#0d2040', marginBottom: '4px', borderRadius: '1px' } }),
              h('div', { style: { width: '20px', height: '2px', background: '#0d2040', borderRadius: '1px' } }),
            ),
            // Period selector — app.jsx passes the live <GlobalPeriodSelector/> element.
            periodSelector || null,
          ),

          // AI Analyse button
          h('button', {
            onClick: runAI,
            style: { background: '#00b894', color: 'white', border: 'none', borderRadius: '7px', padding: '7px 16px', fontSize: '11px', fontWeight: '700', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '6px', letterSpacing: '.02em' },
          }, '✦ AI Analyse'),
        ),

        // Page content
        h('div', { style: { flex: 1, overflow: 'auto' } }, children)
      )
    );
  }

  window.ShellV2 = ShellV2;
})();
