// Shell.jsx — sidebar nav + main column scaffold for the portal.

const Shell = ({ activeRoute, onNavigate, children, sidebarStyle = 'dark', density = 'comfortable' }) => {
  const [searchOpen, setSearchOpen] = useState(false);
  const [notifOpen, setNotifOpen]   = useState(false);
  const [search, setSearch] = useState('');

  // Search corpus
  const corpus = [
    ...window.SAMPLE_PREP_ITEMS.map(i => ({ kind: 'Prep item',  label: i.name, route: 'prep' })),
    ...window.SAMPLE_STAFF.map(s => ({ kind: 'Staff',           label: s.name, route: 'staff' })),
    { kind: 'Page', label: 'Dashboard',         route: 'dashboard' },
    { kind: 'Page', label: 'Daily Prep',        route: 'prep' },
    { kind: 'Page', label: 'Prep Assignment',   route: 'prep' },
    { kind: 'Page', label: 'Prep Catalog',       route: 'prep-catalog' },
    { kind: 'Page', label: 'Broadcasts',        route: 'broadcasts' },
    { kind: 'Page', label: 'Staff & PINs',      route: 'staff' },
    { kind: 'Page', label: 'History',           route: 'history' },
    { kind: 'Page', label: 'Settings',          route: 'settings' },
  ];
  const results = !search ? [] : corpus.filter(r => r.label.toLowerCase().includes(search.toLowerCase())).slice(0, 8);

  const notifications = [
    { id: 1, title: 'Walk-in cooler temp ↑', sub: 'Now 41°F — over threshold', time: '12 min', route: 'broadcasts' },
    { id: 2, title: 'Prep deadline in 30 min', sub: '4 primary items still pending', time: '30 min', route: 'prep' },
    { id: 3, title: 'Mei acknowledged broadcast', sub: '"Walk-in cooler door"', time: '1 h', route: 'broadcasts' },
    { id: 4, title: 'Low stock alert', sub: 'Eggplant — 25% of par', route: 'dashboard', time: '3 h' },
  ];

  useEffect(() => {
    const handler = (e) => {
      if (e.key === 'Escape') { setSearchOpen(false); setNotifOpen(false); }
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); setSearchOpen(true); }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, []);

  const sections = [
    { label: 'Today', items: [
      { id: 'dashboard', icon: 'home', label: 'Dashboard' },
    ]},
    { label: 'Operation', items: [
      { id: 'prep',         icon: 'clipboard', label: 'Daily Prep',
        matchRoutes: ['prep', 'prep-catalog'] },
      { id: 'broadcasts',   icon: 'megaphone', label: 'Broadcasts' },
      { id: 'truckorder',   icon: 'truck', label: 'Truck Order' },
      { id: 'training',  icon: 'book',  label: 'Training' },
    ]},
    { label: 'People', items: [
      { id: 'staff',     icon: 'users', label: 'Staff & PINs' },
    ]},
    { label: 'Setup', items: [
      { id: 'inventory', icon: 'box',    label: 'Inventory' },
      { id: 'devices',   icon: 'tablet', label: 'Devices' },
    ]},
    { label: 'Records', items: [
      { id: 'history',   icon: 'history', label: 'History' },
    ]},
    { label: 'Settings', items: [
      { id: 'settings',  icon: 'settings', label: 'Settings' },
    ]},
  ];

  const owner = window.SAMPLE_STAFF[0];

  const breadcrumbMap = {
    dashboard: ['Dashboard'],
    prep:         ['Operation', 'Daily Prep', 'Assignment'],
    'prep-catalog':['Operation', 'Daily Prep', 'Catalog'],
    broadcasts:   ['Operation', 'Broadcasts'],
    truckorder:   ['Operation', 'Truck Order'],
    staff:     ['People', 'Staff & PINs'],
    training:  ['Operation', 'Training'],
    inventory: ['Setup', 'Inventory'],
    devices:   ['Setup', 'Devices'],
    history:   ['Records', 'History'],
    settings:  ['Settings'],
  };
  const crumbs = breadcrumbMap[activeRoute] || [];

  return (
    <div className={`portal-shell sidebar-${sidebarStyle} ${density === 'dense' ? 'dense' : ''}`}>
      <aside className="portal-sidebar">
        <div className="portal-sidebar-brand">
          <div className="portal-sidebar-brand-mark">S</div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: '-0.01em' }}>Snap Operation</div>
            <div style={{ fontSize: 10.5, opacity: 0.5, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Owner Portal</div>
          </div>
        </div>

        <nav style={{ flex: 1, overflowY: 'auto' }} className="scroll-soft">
          {sections.map((section, si) => (
            <div key={si}>
              <div className="portal-sidebar-section-label">{section.label}</div>
              {section.items.map(item => {
                const matches = item.matchRoutes || [item.id];
                const active = matches.includes(activeRoute);
                return (
                  <button
                    key={item.id}
                    className={`portal-nav-item ${active ? 'is-active' : ''}`}
                    onClick={() => onNavigate(item.id)}
                  >
                    <PIcon name={item.icon} size={15} />
                    <span>{item.label}</span>
                    {item.badge && <span className="nav-badge">{item.badge}</span>}
                  </button>
                );
              })}
            </div>
          ))}
        </nav>

        <div className="portal-sidebar-footer">
          <div className="portal-user-chip">
            <PAvatar staff={owner} size={28} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500, letterSpacing: '-0.005em' }}>{owner.name}</div>
              <div style={{ fontSize: 10.5, opacity: 0.5, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Owner</div>
            </div>
            <PIcon name="chevronD" size={13} style={{ opacity: 0.6 }} />
          </div>
        </div>
      </aside>

      <main className="portal-main">
        <header className="portal-topbar">
          <div className="portal-breadcrumb">
            {crumbs.map((c, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span style={{ color: 'var(--fg-3)' }}>/</span>}
                <span className={i === crumbs.length - 1 ? 'crumb-current' : ''}>{c}</span>
              </React.Fragment>
            ))}
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <button title="Search (⌘K)" onClick={() => setSearchOpen(true)} style={{
              width: 32, height: 32, borderRadius: 8,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--fg-2)',
            }}><PIcon name="search" size={15} /></button>
            <div style={{ position: 'relative' }}>
              <button title="Notifications" onClick={() => setNotifOpen(o => !o)} style={{
                width: 32, height: 32, borderRadius: 8,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                color: 'var(--fg-2)', position: 'relative',
                background: notifOpen ? 'var(--bg-sunken)' : 'transparent',
              }}>
                <PIcon name="bell" size={15} />
                <span style={{ position: 'absolute', top: 6, right: 7, width: 6, height: 6, background: '#8B2A1A', borderRadius: 999 }} />
              </button>
              {notifOpen && (
                <>
                  <div onClick={() => setNotifOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 90 }} />
                  <div style={{
                    position: 'absolute', top: 'calc(100% + 6px)', right: 0,
                    width: 320, background: '#fff',
                    border: '1px solid var(--border-2)', borderRadius: 12,
                    boxShadow: '0 12px 40px rgba(0,0,0,0.15)', zIndex: 100,
                    overflow: 'hidden',
                  }}>
                    <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--border-2)', fontSize: 12.5, fontWeight: 600, display: 'flex', justifyContent: 'space-between' }}>
                      <span>Notifications</span>
                      <button style={{ fontSize: 11, color: 'var(--fg-3)' }} onClick={() => setNotifOpen(false)}>Mark all read</button>
                    </div>
                    {notifications.map(n => (
                      <button key={n.id} onClick={() => { onNavigate(n.route); setNotifOpen(false); }} style={{
                        display: 'block', width: '100%', textAlign: 'left',
                        padding: '10px 14px', borderBottom: '1px solid var(--border-2)',
                      }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                          <span style={{ fontSize: 12.5, fontWeight: 500 }}>{n.title}</span>
                          <span style={{ fontSize: 10.5, color: 'var(--fg-3)' }}>{n.time}</span>
                        </div>
                        <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 2 }}>{n.sub}</div>
                      </button>
                    ))}
                  </div>
                </>
              )}
            </div>
            <div style={{ width: 1, height: 18, background: 'var(--border-1)', margin: '0 4px' }} />
            <a href="https://ops.snap-a-box.com/" target="_blank" rel="noopener" style={{
              fontSize: 12.5, color: 'var(--fg-2)',
              textDecoration: 'none',
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '6px 10px', borderRadius: 7,
              border: '1px solid var(--border-1)',
              background: 'var(--bg-surface)',
            }}>
              <PIcon name="arrowR" size={13} />
              Open iPad app
            </a>
            <button onClick={() => window.portalSignOut && window.portalSignOut()} style={{
              fontSize: 12.5, color: 'var(--fg-2)',
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '6px 10px', borderRadius: 7,
              border: '1px solid var(--border-1)',
              background: 'var(--bg-surface)',
              cursor: 'pointer',
            }} title="Sign out">
              <PIcon name="ri-logout-box-r-line" size={13} />
              Sign out
            </button>
          </div>
        </header>

        <div style={{ flex: 1, minHeight: 0 }}>
          {children}
        </div>
      </main>

      {searchOpen && (
        <div onClick={() => setSearchOpen(false)} style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.30)',
          display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
          zIndex: 1000, padding: '14vh 24px 24px',
        }}>
          <div onClick={e => e.stopPropagation()} style={{
            width: 560, maxWidth: '100%',
            background: '#fff', borderRadius: 14,
            boxShadow: '0 20px 60px rgba(0,0,0,0.22)',
            overflow: 'hidden',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 18px', borderBottom: '1px solid var(--border-2)' }}>
              <PIcon name="search" size={16} color="var(--fg-3)" />
              <input
                autoFocus
                value={search}
                onChange={e => setSearch(e.target.value)}
                placeholder="Search prep items, staff, tasks, pages…"
                style={{ flex: 1, fontSize: 14, border: 'none', outline: 'none', background: 'transparent' }}
              />
              <span className="kbd">esc</span>
            </div>
            <div style={{ maxHeight: '50vh', overflowY: 'auto' }}>
              {results.length === 0 && search && (
                <div style={{ padding: 24, textAlign: 'center', fontSize: 12.5, color: 'var(--fg-3)' }}>No matches.</div>
              )}
              {results.length === 0 && !search && (
                <div style={{ padding: 24, textAlign: 'center', fontSize: 12.5, color: 'var(--fg-3)' }}>Start typing to search.</div>
              )}
              {results.map((r, i) => (
                <button key={i} onClick={() => { onNavigate(r.route); setSearchOpen(false); setSearch(''); }} style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  width: '100%', padding: '10px 18px',
                  borderBottom: '1px solid var(--border-2)', textAlign: 'left',
                }}>
                  <span style={{ fontSize: 13, fontWeight: 500 }}>{r.label}</span>
                  <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>{r.kind}</span>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

window.Shell = Shell;
