import { useEffect, useRef, useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import UserMenu from './UserMenu'
import { useNotifications } from '../context/NotificationContext'
import useNotificationSettingsStore from '../store/notificationSettingsStore'
import useTableViewStore from '../store/tableViewStore'
import useChatStore from '../store/chatStore'
import useKdsReadyStore from '../store/kdsReadyStore'
import useOfflineQueueCount from '../hooks/useOfflineQueueCount'
import useFailedPrintCount from '../hooks/useFailedPrintCount'

// ─── Nav item registry ────────────────────────────────────────────────────────

const NAV_REGISTRY = {
  tables: {
    key: 'tables',
    label: 'Τραπέζια',
    shortLabel: 'Τραπέζια',
    href: '/tables?tab=tables',
    match: (loc) => loc.pathname === '/tables' && loc.search !== '?tab=orders',
    icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <rect x="3" y="3" width="7" height="7" rx="1.5" fill="currentColor"/>
        <rect x="14" y="3" width="7" height="7" rx="1.5" fill="currentColor"/>
        <rect x="3" y="14" width="7" height="7" rx="1.5" fill="currentColor"/>
        <rect x="14" y="14" width="7" height="7" rx="1.5" fill="currentColor"/>
      </svg>
    ),
  },
  orders: {
    key: 'orders',
    label: 'Ενεργές Παραγγελίες',
    shortLabel: 'Παραγγελίες',
    href: '/tables?tab=orders',
    match: (loc) => loc.pathname === '/tables' && loc.search === '?tab=orders',
    icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <path d="M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2M9 5a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2M9 5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
        <path d="M9 12h6M9 16h4" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
      </svg>
    ),
  },
  messages: {
    key: 'messages',
    label: 'Μηνύματα',
    shortLabel: 'Μηνύματα',
    href: '/messages',
    match: (loc) => loc.pathname === '/messages',
    icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    ),
  },
  standalone: {
    key: 'standalone',
    label: 'Takeaway',
    shortLabel: 'Takeaway',
    href: '/tables',
    match: () => false,
    icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <path d="M5 12H3l9-9 9 9h-2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M10 22v-6h4v6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    ),
  },
  'shift-overview': {
    key: 'shift-overview',
    label: 'Βάρδια',
    shortLabel: 'Βάρδια',
    href: '/shift-overview',
    match: (loc) => loc.pathname === '/shift-overview',
    icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2"/>
        <path d="M12 7v5l3 3" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
      </svg>
    ),
  },
  'order-log': {
    key: 'order-log',
    label: 'Αρχείο',
    shortLabel: 'Αρχείο',
    href: '/order-log',
    match: (loc) => loc.pathname === '/order-log',
    icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <path d="M6 9V2h12v7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <rect x="6" y="14" width="12" height="8" rx="1" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    ),
  },
}

const DRAWER_ITEMS = [
  { ...NAV_REGISTRY.tables },
  { ...NAV_REGISTRY.orders },
  { ...NAV_REGISTRY.messages },
]

// ─── Cache badge (cloud upload) ───────────────────────────────────────────────

function CacheButton({ count }) {
  if (!count) return null
  return (
    <div style={{
      position: 'relative',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      minWidth: 44, minHeight: 44, borderRadius: 8,
      color: '#f59e0b',
    }}>
      {/* Cloud upload icon */}
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <path d="M12 16V10M12 10L9 13M12 10L15 13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M6.5 18a4.5 4.5 0 0 1-.5-8.965A6 6 0 0 1 17.5 11h.5a3.5 3.5 0 0 1 .5 6.965" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
      <span style={{
        position: 'absolute', top: 6, right: 6,
        background: '#f59e0b', color: 'white', fontSize: 10, fontWeight: 700,
        borderRadius: '50%', width: 16, height: 16,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {count > 9 ? '9+' : count}
      </span>
    </div>
  )
}

// ─── Failed print badge ───────────────────────────────────────────────────────

function FailedPrintButton({ count, onClick }) {
  if (!count) return null
  return (
    <button
      onClick={onClick}
      style={{
        position: 'relative',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        minWidth: 44, minHeight: 44, borderRadius: 8,
        background: 'none', border: 'none', cursor: 'pointer',
        color: '#ef4444',
      }}
    >
      {/* Printer icon */}
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <path d="M6 9V2h12v7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <rect x="6" y="14" width="12" height="8" rx="1" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
      <span style={{
        position: 'absolute', top: 6, right: 6,
        background: '#ef4444', color: 'white', fontSize: 10, fontWeight: 700,
        borderRadius: '50%', width: 16, height: 16,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {count > 9 ? '9+' : count}
      </span>
    </button>
  )
}

// ─── Bell button ──────────────────────────────────────────────────────────────

function BellButton({ onClick, count }) {
  return (
    <button
      onClick={onClick}
      style={{
        position: 'relative', background: 'none', border: 'none',
        color: 'var(--text)', cursor: 'pointer',
        minWidth: 44, minHeight: 44, borderRadius: 8,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      }}
    >
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
        <path d="M19.3399 14.49L18.3399 12.83C18.1299 12.46 17.9399 11.76 17.9399 11.35V8.82C17.9399 6.47 16.5599 4.44 14.5699 3.49C14.0499 2.57 13.0899 2 11.9899 2C10.8999 2 9.91994 2.59 9.39994 3.52C7.44994 4.49 6.09994 6.5 6.09994 8.82V11.35C6.09994 11.76 5.90994 12.46 5.69994 12.82L4.68994 14.49C4.28994 15.16 4.19994 15.9 4.44994 16.58C4.68994 17.25 5.25994 17.77 5.99994 18.02C7.93994 18.68 9.97994 19 12.0199 19C14.0599 19 16.0999 18.68 18.0399 18.03C18.7399 17.8 19.2799 17.27 19.5399 16.58C19.7999 15.89 19.7299 15.13 19.3399 14.49Z" fill="currentColor"/>
        <path d="M14.8297 20.01C14.4097 21.17 13.2997 22 11.9997 22C11.2097 22 10.4297 21.68 9.87969 21.11C9.55969 20.81 9.31969 20.41 9.17969 20C9.30969 20.02 9.43969 20.03 9.57969 20.05C9.80969 20.08 10.0497 20.11 10.2897 20.13C10.8597 20.18 11.4397 20.21 12.0197 20.21C12.5897 20.21 13.1597 20.18 13.7197 20.13C13.9297 20.11 14.1397 20.1 14.3397 20.07C14.4997 20.05 14.6597 20.03 14.8297 20.01Z" fill="currentColor"/>
      </svg>
      {count > 0 && (
        <span style={{
          position: 'absolute', top: 6, right: 6,
          background: '#ef4444', color: 'white', fontSize: 10, fontWeight: 700,
          borderRadius: '50%', width: 16, height: 16,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {count > 9 ? '9+' : count}
        </span>
      )}
    </button>
  )
}

// ─── Notification drawer ──────────────────────────────────────────────────────

function NotificationDrawer({ messages, onClose }) {
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()} style={{ maxHeight: '80svh' }}>
        <div className="modal-handle" />
        <h2 className="modal-title" style={{ marginBottom: 8 }}>Ειδοποιήσεις</h2>
        {messages.length === 0 && (
          <p style={{ textAlign: 'center', color: 'var(--muted)', padding: '24px 0' }}>
            Δεν υπάρχουν ειδοποιήσεις
          </p>
        )}
        <div style={{ display: 'flex', flexDirection: 'column', overflowY: 'auto', flex: 1 }}>
          {messages.map(msg => {
            const tableIds = (() => { try { return JSON.parse(msg.table_ids || '[]') } catch { return [] } })()
            return (
              <div key={msg.id} style={{
                padding: '12px 4px', borderBottom: '1px solid var(--border)',
                display: 'flex', gap: 12, alignItems: 'flex-start',
              }}>
                <span style={{ fontSize: 20, flexShrink: 0 }}>📢</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  {msg.sender_name && (
                    <div style={{ fontSize: 11, fontWeight: 700, color: '#a5b4fc', marginBottom: 2 }}>{msg.sender_name}</div>
                  )}
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{msg.body}</div>
                  {tableIds.length > 0 && (
                    <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>Τραπέζι: {tableIds.join(', ')}</div>
                  )}
                  <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>
                    {new Date(msg.created_at).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })}
                  </div>
                </div>
              </div>
            )
          })}
        </div>
        <button className="btn btn--secondary" style={{ width: '100%', marginTop: 4 }} onClick={onClose}>Κλείσιμο</button>
      </div>
    </div>
  )
}

// ─── Side drawer ──────────────────────────────────────────────────────────────

const DRAWER_NAV_ITEMS = [
  { ...NAV_REGISTRY.tables },
  {
    key: 'standalone',
    label: 'Takeaway / Delivery',
    href: '/tables',
    match: () => false, // active state handled separately in SideDrawer
    icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <path d="M5 12H3l9-9 9 9h-2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M10 22v-6h4v6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    ),
  },
  { ...NAV_REGISTRY.orders },
  { ...NAV_REGISTRY.messages },
  {
    key: 'shift-overview',
    label: 'Σύνοψη Βάρδιας',
    href: '/shift-overview',
    match: (loc) => loc.pathname === '/shift-overview',
    icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2"/>
        <path d="M12 7v5l3 3" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
      </svg>
    ),
  },
  {
    key: 'order-log',
    label: 'Αρχείο Παραγγελιών',
    href: '/order-log',
    match: (loc) => loc.pathname === '/order-log',
    icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <path d="M6 9V2h12v7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <rect x="6" y="14" width="12" height="8" rx="1" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    ),
  },
]

const DRAWER_SETTINGS_ITEM = {
  key: 'settings',
  label: 'Settings',
  href: '/settings',
  match: (loc) => loc.pathname.startsWith('/settings'),
  icon: (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/>
      <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" stroke="currentColor" strokeWidth="2"/>
    </svg>
  ),
}

function DrawerButton({ item, location, onNavigate, active: activeProp, onClick }) {
  const active = activeProp ?? item.match(location)
  return (
    <button
      onClick={onClick ?? (() => onNavigate(item.href))}
      style={{
        display: 'flex', alignItems: 'center', gap: 14,
        padding: '12px 14px', borderRadius: 12, border: 'none',
        background: active ? 'var(--accent)18' : 'transparent',
        color: active ? 'var(--accent)' : 'var(--text)',
        fontSize: 15, fontWeight: active ? 700 : 500,
        cursor: 'pointer', textAlign: 'left', width: '100%',
        transition: 'background 0.12s, color 0.12s',
      }}
    >
      <span style={{ opacity: active ? 1 : 0.6, flexShrink: 0 }}>{item.icon}</span>
      {item.label}
      {active && (
        <div style={{ marginLeft: 'auto', width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }} />
      )}
    </button>
  )
}

function SideDrawer({ open, onClose }) {
  const navigate = useNavigate()
  const location = useLocation()
  const { activeZoneTab, setActiveZoneTab } = useTableViewStore()

  function go(href) {
    if (href.startsWith('/tables')) setActiveZoneTab('all')
    onClose()
    navigate(href, { replace: true })
  }

  function goStandalone() {
    setActiveZoneTab('standalone')
    onClose()
    navigate('/tables', { replace: true })
  }

  return (
    <>
      {/* Overlay */}
      <div
        onClick={onClose}
        style={{
          position: 'fixed', inset: 0, zIndex: 300,
          background: 'rgba(0,0,0,0.55)',
          opacity: open ? 1 : 0,
          pointerEvents: open ? 'all' : 'none',
          transition: 'opacity 0.22s ease',
        }}
      />
      {/* Drawer panel */}
      <div style={{
        position: 'fixed', top: 0, left: 0, bottom: 0,
        width: 260, zIndex: 301,
        background: 'var(--bg2)',
        borderRight: '1px solid var(--border)',
        display: 'flex', flexDirection: 'column',
        transform: open ? 'translateX(0)' : 'translateX(-100%)',
        transition: 'transform 0.22s ease',
        boxShadow: open ? '4px 0 24px rgba(0,0,0,0.4)' : 'none',
      }}>
        {/* Drawer header */}
        <div style={{ padding: '20px 20px 16px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--accent)', letterSpacing: -0.5 }}>Xenia</div>
          <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>POS System</div>
        </div>

        {/* Main nav items */}
        <div style={{ flex: 1, padding: '12px 10px', display: 'flex', flexDirection: 'column', gap: 4, overflowY: 'auto' }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1, padding: '4px 10px 8px' }}>
            Πλοήγηση
          </div>
          {DRAWER_NAV_ITEMS.map(item => {
            const isStandaloneActive = location.pathname === '/tables' && activeZoneTab === 'standalone'
            const active = item.key === 'standalone'
              ? isStandaloneActive
              : item.key === 'tables'
              ? item.match(location) && !isStandaloneActive
              : undefined
            return (
              <DrawerButton
                key={item.key}
                item={item}
                location={location}
                onNavigate={go}
                active={active}
                onClick={item.key === 'standalone' ? goStandalone : undefined}
              />
            )
          })}
        </div>

        {/* Settings at bottom */}
        <div style={{ padding: '8px 10px 16px', borderTop: '1px solid var(--border)' }}>
          <DrawerButton item={DRAWER_SETTINGS_ITEM} location={location} onNavigate={go} />
        </div>
      </div>
    </>
  )
}

// ─── Triple pill footer ───────────────────────────────────────────────────────

function PillBadge({ count, color = '#ef4444' }) {
  if (!count) return null
  return (
    <span style={{
      background: color, color: 'white', fontSize: 12, fontWeight: 800,
      borderRadius: 11, minWidth: 22, height: 22,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      padding: '0 6px', lineHeight: 1, flexShrink: 0,
    }}>
      {count > 9 ? '9+' : count}
    </span>
  )
}

function TripleFooter({ location, navigate, chatUnread, kdsReady, tripleItems }) {
  const { activeZoneTab, setActiveZoneTab } = useTableViewStore()
  const items = (tripleItems || ['tables', 'orders', 'messages']).map(k => NAV_REGISTRY[k]).filter(Boolean)

  function handleNavClick(item) {
    if (item.key === 'standalone') { setActiveZoneTab('standalone'); navigate('/tables', { replace: true }); return }
    if (item.key === 'tables' || item.key === 'orders') setActiveZoneTab('all')
    navigate(item.href, { replace: true })
  }

  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '10px 10px',
      background: 'var(--bg2)',
      borderTop: '1px solid var(--border)',
      flexShrink: 0,
    }}>
      <div style={{ display: 'flex', gap: 4, background: 'var(--bg3)', borderRadius: 28, padding: 4, width: '100%' }}>
        {items.map(item => {
          const isStandaloneActive = location.pathname === '/tables' && activeZoneTab === 'standalone'
          const active = item.key === 'standalone'
            ? isStandaloneActive
            : item.key === 'tables'
            ? item.match(location) && !isStandaloneActive
            : item.match(location)
          const badge = item.key === 'messages' && chatUnread > 0
            ? { count: chatUnread, color: '#ef4444' }
            : item.key === 'orders' && kdsReady > 0
            ? { count: kdsReady, color: '#22c55e' }
            : null
          return (
            <button
              key={item.key}
              onClick={() => handleNavClick(item)}
              style={{
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                flex: 1,
                padding: '9px 8px', borderRadius: 22,
                border: '2px solid transparent',
                background: active ? 'var(--accent)' : 'transparent',
                color: active ? 'var(--accent-fg)' : 'var(--muted)',
                fontSize: 14, fontWeight: 700, cursor: 'pointer', lineHeight: 1,
                transition: 'background 0.15s, color 0.15s',
                whiteSpace: 'nowrap',
              }}
            >
              <span style={{ display: 'inline-flex', alignItems: 'center', flexShrink: 0 }}>
                {item.key === 'tables' && <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><rect x="3" y="3" width="7" height="7" rx="1.5" fill="currentColor"/><rect x="14" y="3" width="7" height="7" rx="1.5" fill="currentColor"/><rect x="3" y="14" width="7" height="7" rx="1.5" fill="currentColor"/><rect x="14" y="14" width="7" height="7" rx="1.5" fill="currentColor"/></svg>}
                {item.key === 'orders' && <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2M9 5a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2M9 5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/><path d="M9 12h6M9 16h4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>}
                {item.key === 'messages' && <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>}
              </span>
              {item.shortLabel ?? item.label}
              {badge && <PillBadge count={badge.count} color={badge.color} />}
            </button>
          )
        })}
      </div>
    </div>
  )
}

// ─── Icon navbar footer ───────────────────────────────────────────────────────

function IconNavbar({ navItems, location, navigate, chatUnread, kdsReady }) {
  const { activeZoneTab, setActiveZoneTab } = useTableViewStore()
  const items = navItems
    .map(key => NAV_REGISTRY[key])
    .filter(Boolean)

  function handleNavClick(item) {
    if (item.key === 'standalone') { setActiveZoneTab('standalone'); navigate('/tables', { replace: true }); return }
    if (item.key === 'tables' || item.key === 'orders') setActiveZoneTab('all')
    navigate(item.href, { replace: true })
  }

  return (
    <div style={{
      display: 'flex', alignItems: 'stretch',
      padding: '0 8px',
      paddingBottom: 'env(safe-area-inset-bottom, 0px)',
      background: 'var(--bg2)',
      borderTop: '1px solid var(--border)',
      flexShrink: 0,
      minHeight: 60,
    }}>
      {items.map(item => {
        const isStandaloneActive = location.pathname === '/tables' && activeZoneTab === 'standalone'
        const active = item.key === 'standalone'
          ? isStandaloneActive
          : item.key === 'tables'
          ? item.match(location) && !isStandaloneActive
          : item.match(location)
        const badge = item.key === 'messages' && chatUnread > 0
          ? { count: chatUnread, color: '#ef4444' }
          : item.key === 'orders' && kdsReady > 0
          ? { count: kdsReady, color: '#22c55e' }
          : null
        return (
          <button
            key={item.key}
            onClick={() => handleNavClick(item)}
            style={{
              flex: 1, display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center', gap: 4,
              border: 'none', background: 'none', cursor: 'pointer',
              color: active ? 'var(--accent)' : 'var(--muted)',
              padding: '10px 4px',
              position: 'relative',
              transition: 'color 0.15s',
            }}
          >
            {active && (
              <div style={{
                position: 'absolute', top: 0, left: '25%', right: '25%',
                height: 2, borderRadius: '0 0 2px 2px',
                background: 'var(--accent)',
              }} />
            )}
            <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
              {item.icon}
              {badge && (
                <span style={{
                  position: 'absolute', top: -4, right: -6,
                  background: badge.color, color: 'white', fontSize: 9, fontWeight: 800,
                  borderRadius: '50%', minWidth: 14, height: 14,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  padding: '0 2px',
                }}>
                  {badge.count > 9 ? '9+' : badge.count}
                </span>
              )}
            </span>
            <span style={{ fontSize: 10, fontWeight: active ? 700 : 500, letterSpacing: 0.2 }}>
              {item.shortLabel ?? item.label}
            </span>
          </button>
        )
      })}
    </div>
  )
}

// ─── AppShell ─────────────────────────────────────────────────────────────────

export default function AppShell({ children, title, rightActions }) {
  const navigate = useNavigate()
  const location = useLocation()
  const [drawerOpen, setDrawerOpen] = useState(false)
  const [showNotifs, setShowNotifs] = useState(false)

  const { unreadCount, recentMessages, fetchRecent, ackAll } = useNotifications() || {}
  const { popupMode } = useNotificationSettingsStore()
  const { navStyle, navItems, tripleItems } = useTableViewStore()
  const { totalUnread: chatUnread } = useChatStore()
  const { readyCount } = useKdsReadyStore()
  const offlineCacheCount = useOfflineQueueCount()
  const failedPrintCount = useFailedPrintCount()

  function openNotifs() {
    setShowNotifs(true)
    fetchRecent?.()
    if (popupMode === 'never') ackAll?.()
  }

  return (
    <div className="page">
      {/* ── Header ────────────────────────────────────────────── */}
      <header className="top-bar">
        {/* Hamburger menu */}
        <button
          onClick={() => setDrawerOpen(true)}
          style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            background: 'none', border: 'none', cursor: 'pointer',
            color: 'var(--text)', minWidth: 44, minHeight: 44, borderRadius: 8,
          }}
        >
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
            <line x1="3" y1="6" x2="21" y2="6"/>
            <line x1="3" y1="12" x2="21" y2="12"/>
            <line x1="3" y1="18" x2="21" y2="18"/>
          </svg>
        </button>

        {/* Title / right-actions area */}
        {title && (
          <span className="top-bar__title">{title}</span>
        )}
        {!title && <div style={{ flex: 1 }} />}

        {/* Custom right actions (per-page) */}
        {rightActions}

        {/* Offline cache badge — visible only when ops are pending */}
        <CacheButton count={offlineCacheCount} />

        {/* Failed print badge — navigates to order log */}
        <FailedPrintButton count={failedPrintCount} onClick={() => navigate('/order-log?filter=failed')} />

        {/* Bell */}
        <BellButton onClick={openNotifs} count={unreadCount || 0} />

        {/* Username chip */}
        <UserMenu />
      </header>

      {/* ── Side drawer ───────────────────────────────────────── */}
      <SideDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} />

      {/* ── Page content ──────────────────────────────────────── */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden' }}>
        {children}
      </div>

      {/* ── Footer nav ────────────────────────────────────────── */}
      {navStyle === 'icon_navbar' ? (
        <IconNavbar
          navItems={navItems}
          location={location}
          navigate={navigate}
          chatUnread={chatUnread}
          kdsReady={readyCount}
        />
      ) : (
        <TripleFooter
          location={location}
          navigate={navigate}
          chatUnread={chatUnread}
          kdsReady={readyCount}
          tripleItems={tripleItems}
        />
      )}

      {/* ── Notification drawer ───────────────────────────────── */}
      {showNotifs && (
        <NotificationDrawer
          messages={recentMessages || []}
          onClose={() => setShowNotifs(false)}
        />
      )}
    </div>
  )
}
