/* GarageWiz — app shell: top bar, nav, user menu, admin sidebar */
(function () {
  const e = React.createElement;
  const { useState, useRef } = React;
  const Icon = window.Icon, Wordmark = window.Wordmark, Btn = window.Btn;

  const HOME = { id: 'dashboard', label: 'Home', icon: 'home', route: '#/dashboard' };
  const PRICING_NAV = [
    { id: 'doors', label: 'Doors', icon: 'door', route: '#/doors' },
    { id: 'openers', label: 'Openers', icon: 'opener', route: '#/openers' },
    { id: 'parts', label: 'Parts', icon: 'parts', route: '#/parts' },
  ];
  const PRICING_SECTIONS = { tools: 1, doors: 1, openers: 1, parts: 1, quote: 1, estimate: 1, estimates: 1, pricingadmin: 1 };

  function TopBar() {
    const app = window.useApp();
    const [menuOpen, setMenuOpen] = useState(false);
    const clickRef = useRef({ n: 0, t: 0 });
    const active = app.route.section;
    const inPricing = !!PRICING_SECTIONS[active];
    // Home + (pricing module nav only while inside the pricing tool)
    const MODULES = [HOME].concat(inPricing ? PRICING_NAV : []);

    function logoClick() {
      const now = Date.now();
      const c = clickRef.current;
      if (now - c.t < 650) c.n += 1; else c.n = 1;
      c.t = now;
      if (c.n >= 3) { c.n = 0; app.openDealer(); }
    }

    const navItem = (m) => e('button', {
      key: m.id, onClick: () => app.go(m.route),
      title: m.label,
      style: {
        display: 'flex', alignItems: 'center', gap: 9, border: 'none', cursor: 'pointer',
        background: active === m.id ? 'rgba(245,224,65,.16)' : 'transparent',
        color: active === m.id ? 'var(--yellow)' : 'rgba(255,255,255,.82)',
        padding: '10px 16px', borderRadius: 999, fontFamily: 'var(--display)', fontWeight: 600, fontSize: 15.5,
        transition: 'background .15s, color .15s', whiteSpace: 'nowrap',
      },
    },
      e(Icon, { name: m.icon, size: 19 }),
      e('span', { className: 'nav-label' }, m.label),
    );

    return e('header', {
      style: {
        background: 'linear-gradient(180deg, var(--teal) 0%, var(--teal-700) 100%)',
        color: '#fff', borderBottom: '3px solid var(--navy)', position: 'sticky', top: 0, zIndex: 90,
        boxShadow: '0 2px 14px rgba(1,30,40,.18)',
      },
    },
      e('div', { style: { display: 'flex', alignItems: 'center', gap: 18, padding: '0 22px', height: 70, maxWidth: 1480, margin: '0 auto' } },
        // Logo (triple-click → dealer)
        e('button', {
          onClick: logoClick, title: 'GarageWiz',
          style: { background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, display: 'flex', alignItems: 'center', flexShrink: 0 },
        }, e(Wordmark, { height: 42 })),

        e('nav', { className: 'topnav', style: { display: 'flex', alignItems: 'center', gap: 4, marginLeft: 8 } }, MODULES.map(navItem)),

        e('div', { className: 'grow' }),

        // Estimate (cart) — shows only when items have been added
        (app.estimate && app.estimate.items && app.estimate.items.length)
          ? e('button', {
            onClick: () => app.go('#/estimate'), title: 'Estimate',
            style: {
              display: 'flex', alignItems: 'center', gap: 8, border: '1.5px solid var(--yellow)',
              background: active === 'estimate' ? 'var(--yellow)' : 'rgba(245,224,65,.12)', color: active === 'estimate' ? 'var(--ink)' : '#fff',
              padding: '9px 14px', borderRadius: 999, fontFamily: 'var(--display)', fontWeight: 700, fontSize: 14.5, cursor: 'pointer',
            },
          }, e(Icon, { name: 'tag', size: 18 }), e('span', null, 'Estimate'),
            e('span', { style: { background: active === 'estimate' ? 'var(--ink)' : 'var(--yellow)', color: active === 'estimate' ? 'var(--yellow)' : 'var(--ink)', borderRadius: 999, minWidth: 20, height: 20, padding: '0 6px', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 800 } }, app.estimate.items.length))
          : null,

        // Admin entry — context-aware: pricing-tool admin while in the tool,
        // otherwise the system admin.
        app.user && app.user.role === 'admin'
          ? (function () {
            const adminRoute = inPricing ? '#/pricingadmin/settings' : '#/admin/users';
            const adminLabel = inPricing ? 'Tool Admin' : 'System Admin';
            const adminActive = active === 'admin' || active === 'pricingadmin';
            return e('button', {
              onClick: () => app.go(adminRoute),
              title: adminLabel,
              style: {
                display: 'flex', alignItems: 'center', gap: 8, border: '1.5px solid rgba(255,255,255,.28)',
                background: adminActive ? 'rgba(255,255,255,.16)' : 'transparent', color: '#fff',
                padding: '9px 14px', borderRadius: 999, fontFamily: 'var(--display)', fontWeight: 600, fontSize: 14.5, cursor: 'pointer',
              },
            }, e(Icon, { name: 'settings', size: 18 }), e('span', { className: 'nav-label' }, adminLabel));
          })()
          : null,

        // User chip
        e('div', { style: { position: 'relative' } },
          e('button', {
            onClick: () => setMenuOpen(o => !o),
            style: { display: 'flex', alignItems: 'center', gap: 10, background: 'rgba(255,255,255,.1)', border: 'none', color: '#fff', padding: '7px 9px 7px 7px', borderRadius: 999, cursor: 'pointer' },
          },
            e('span', { style: { width: 34, height: 34, borderRadius: 999, background: 'var(--yellow)', color: 'var(--ink)', display: 'grid', placeItems: 'center', fontFamily: 'var(--display)', fontWeight: 600, fontSize: 15 } }, (app.user ? app.user.name : 'G').slice(0, 1)),
            e('span', { className: 'nav-label', style: { display: 'flex', flexDirection: 'column', lineHeight: 1.15, alignItems: 'flex-start', maxWidth: 130 } },
              e('span', { style: { fontWeight: 600, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 120 } }, app.user ? app.user.name.split(' ')[0] : ''),
              e('span', { style: { fontSize: 11, color: 'rgba(255,255,255,.7)', fontWeight: 600 } }, app.user && app.user.role === 'admin' ? 'Admin' : 'Sales Rep'),
            ),
            e(Icon, { name: 'chevD', size: 16 }),
          ),
          menuOpen ? e('div', {
            style: { position: 'absolute', right: 0, top: 'calc(100% + 8px)', background: '#fff', color: 'var(--ink)', borderRadius: 14, boxShadow: 'var(--sh-3)', minWidth: 200, overflow: 'hidden', zIndex: 95 },
            onMouseLeave: () => setMenuOpen(false),
          },
            e('div', { style: { padding: '14px 16px', borderBottom: '1px solid var(--line)' } },
              e('div', { style: { fontWeight: 700 } }, app.user ? app.user.name : ''),
              e('div', { className: 'muted', style: { fontSize: 13 } }, app.user ? app.user.email : ''),
              e('div', { style: { marginTop: 6 } }, e('span', { className: 'badge ' + (app.user && app.user.role === 'admin' ? 'badge-prem' : 'badge-start') }, app.user && app.user.role === 'admin' ? 'Admin' : 'Sales Rep')),
            ),
            (app.user && app.user.role === 'admin') ? e('button', { onClick: () => { setMenuOpen(false); app.openDealer(); }, className: 'menu-row' }, e(Icon, { name: 'lock', size: 17 }), 'Dealer view') : null,
            e('button', { onClick: () => app.logout(), className: 'menu-row' }, e(Icon, { name: 'logout', size: 17 }), 'Sign out'),
          ) : null,
        ),
      ),
      // mobile nav row
      e('nav', { className: 'topnav-mobile', style: { display: 'none', gap: 4, padding: '0 14px 10px', overflowX: 'auto' } }, MODULES.map(navItem)),
    );
  }
  window.TopBar = TopBar;

  /* ---------- Admin layouts (two tiers) ---------- */
  // Pricing-tool admin — lives INSIDE the pricing tool (#/pricingadmin/...)
  const PRICING_ADMIN_NAV = [
    { id: 'settings', label: 'Business Settings', icon: 'settings', route: '#/pricingadmin/settings' },
    { id: 'doors', label: 'Door Pricing', icon: 'door', route: '#/pricingadmin/doors' },
    { id: 'openers', label: 'Openers', icon: 'opener', route: '#/pricingadmin/openers' },
    { id: 'manufacturers', label: 'Manufacturers', icon: 'manufacturers', route: '#/pricingadmin/manufacturers' },
    { id: 'suppliers', label: 'Suppliers', icon: 'suppliers', route: '#/pricingadmin/suppliers' },
    { id: 'parts', label: 'Parts', icon: 'parts', route: '#/pricingadmin/parts' },
    { id: 'upgrades', label: 'Upgrades', icon: 'spark', route: '#/pricingadmin/upgrades' },
    { id: 'bundles', label: 'Bundles', icon: 'bundle', route: '#/pricingadmin/bundles' },
    { id: 'coupons', label: 'Coupons', icon: 'tag', route: '#/pricingadmin/coupons' },
    { id: 'reviews', label: 'Review Requests', icon: 'mail', route: '#/pricingadmin/reviews' },
  ];
  // System admin — the whole app suite (#/admin/...)
  const SYSTEM_ADMIN_NAV = [
    { id: 'users', label: 'Users', icon: 'users', route: '#/admin/users' },
    { id: 'permissions', label: 'Permissions', icon: 'lock', route: '#/admin/permissions' },
    { id: 'tools', label: 'Tools', icon: 'briefcase', route: '#/admin/tools' },
    { id: 'backend', label: 'Backend', icon: 'settings', route: '#/admin/backend' },
    { id: 'activity', label: 'Activity', icon: 'activity', route: '#/admin/activity' },
  ];

  function AdminLayout({ children }) {
    const app = window.useApp();
    const isPricing = app.route.section === 'pricingadmin';
    const nav = isPricing ? PRICING_ADMIN_NAV : SYSTEM_ADMIN_NAV;
    const sub = app.route.sub || nav[0].id;
    const eyebrow = isPricing ? 'Pricing Tool · Admin' : 'System Admin';
    const note = isPricing ? 'Changes here update pricing & options across the Pricing Configurator instantly.' : 'Manage users, tool access and the app suite.';
    return e('div', { className: 'admin-wrap', style: { display: 'flex', maxWidth: 1480, margin: '0 auto', minHeight: 'calc(100vh - 70px)' } },
      e('aside', {
        className: 'admin-side',
        style: { width: 256, flexShrink: 0, background: 'var(--navy)', padding: '22px 16px', position: 'sticky', top: 70, alignSelf: 'flex-start', height: 'calc(100vh - 70px)', overflowY: 'auto' },
      },
        isPricing ? e('button', { onClick: () => app.go('#/tools/pricing'), style: { display: 'flex', alignItems: 'center', gap: 8, background: 'transparent', border: 'none', color: 'rgba(255,255,255,.7)', fontWeight: 600, fontFamily: 'var(--display)', fontSize: 13.5, cursor: 'pointer', marginBottom: 14, padding: '0 12px' } }, e(Icon, { name: 'arrowL', size: 16 }), 'Back to Pricing tool') : null,
        e('div', { className: 'eyebrow', style: { color: 'var(--yellow)', padding: '0 12px 14px' } }, eyebrow),
        e('div', { style: { display: 'flex', flexDirection: 'column', gap: 3 } },
          nav.map(n => e('button', {
            key: n.id, onClick: () => app.go(n.route),
            style: {
              display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left', border: 'none', cursor: 'pointer',
              background: sub === n.id ? 'rgba(0,177,237,.18)' : 'transparent',
              color: sub === n.id ? '#fff' : 'rgba(255,255,255,.7)',
              padding: '11px 13px', borderRadius: 11, fontFamily: 'var(--display)', fontWeight: 600, fontSize: 14.5,
              boxShadow: sub === n.id ? 'inset 3px 0 0 var(--yellow)' : 'none', transition: 'background .15s, color .15s',
            },
          }, e(Icon, { name: n.icon, size: 19 }), n.label)),
        ),
        e('div', { style: { marginTop: 22, padding: '14px', background: 'rgba(255,255,255,.05)', borderRadius: 12 } },
          e('div', { style: { fontSize: 12.5, color: 'rgba(255,255,255,.6)', lineHeight: 1.5 } }, note),
        ),
      ),
      e('main', { className: 'admin-main', style: { flex: 1, minWidth: 0, padding: '34px 40px 80px' } }, children),
    );
  }
  window.AdminLayout = AdminLayout;
})();
