/* ============================================================
   APP SHELL — sidebar, header, notifications
   ============================================================ */

const NAV = [
  { id:'dashboard',    label:'Dashboard',          icon:'home',     roles:['commerciale','backoffice','admin'] },
  { id:'catalogo',     label:'Catalogo',           icon:'boxes',    roles:['commerciale','backoffice','admin'] },
  { id:'prenotazioni', label:'Prenotazioni',       icon:'calendar', roles:['commerciale','backoffice','admin'] },
  { id:'noleggi',      label:'Noleggi in corso',   icon:'clock',    roles:['commerciale','backoffice','admin'] },
  { id:'archivio',     label:'Archivio',           icon:'boxes',    roles:['commerciale','backoffice','admin'] },
  { id:'anagrafica',   label:'Anagrafica clienti', icon:'users',    roles:['commerciale','backoffice','admin'] },
  { id:'notifiche',    label:'Notifiche',          icon:'bell',     roles:['commerciale','backoffice','admin'] },
  { id:'attivita',     label:'Log attività',       icon:'log',      roles:['backoffice','admin'] },
  { id:'admin',        label:'Console Admin',      icon:'shield',   roles:['admin'] },
];

function Sidebar({ role, view, nav, dark, currentUser }) {
  const items = NAV.filter(n => n.roles.includes(role));
  const userName = currentUser?.nome || (role==='admin'?'Omar Menabue':role==='backoffice'?'Sara Ferrari':'Marco Bianchi');
  const C = {
    bg: dark ? 'var(--ad-surface)' : 'var(--surface)',
    line: dark ? 'var(--ad-line)' : 'var(--line)',
    txt: dark ? 'var(--ad-text)' : 'var(--ink)',
    txt2: dark ? 'var(--ad-text-2)' : 'var(--ink-3)',
    activeBg: dark ? 'rgba(255,64,90,.14)' : 'var(--red-tint)',
    activeTx: dark ? 'var(--ad-red)' : 'var(--red)',
    hover: dark ? 'rgba(255,255,255,.04)' : 'var(--line-2)',
  };
  return (
    <aside style={{ width:258, flexShrink:0, background:C.bg, borderRight:'1px solid '+C.line,
      display:'flex', flexDirection:'column', height:'100%' }}>
      <div style={{ padding:'20px 22px 18px', borderBottom:'1px solid '+C.line }}>
        <img src={dark ? 'assets/menabue-logo-white.png' : 'assets/menabue-logo.png'} alt="Menabue Carrelli Elevatori"
          style={{ height:38, width:'auto', display:'block', marginBottom:11 }} />
        <div style={{ display:'flex', alignItems:'center', gap:7 }}>
          <span style={{ width:6, height:6, borderRadius:99, background:'var(--red)' }} />
          <span style={{ fontSize:11, fontWeight:700, letterSpacing:'.08em', color:C.txt2, textTransform:'uppercase' }}>Smart Fleet</span>
        </div>
      </div>

      <nav className="scroll" style={{ flex:1, padding:'14px 14px', display:'flex', flexDirection:'column', gap:3, overflowY:'auto' }}>
        <div style={{ fontSize:10.5, fontWeight:800, letterSpacing:'.1em', color:C.txt2, padding:'6px 12px 8px', textTransform:'uppercase' }}>Menu</div>
        {items.map(it => {
          const active = view === it.id;
          return (
            <button key={it.id} onClick={()=>nav(it.id)} style={{ display:'flex', alignItems:'center', gap:12,
              padding:'10px 12px', borderRadius:'var(--r-md)', fontSize:14, fontWeight:active?700:600,
              color: active ? C.activeTx : (dark?C.txt:'var(--ink-2)'), background: active ? C.activeBg : 'transparent',
              position:'relative', transition:'background .14s, color .14s', textAlign:'left' }}
              onMouseEnter={e=>{ if(!active) e.currentTarget.style.background=C.hover; }}
              onMouseLeave={e=>{ if(!active) e.currentTarget.style.background='transparent'; }}>
              {active && <span style={{ position:'absolute', left:-14, top:9, bottom:9, width:3, borderRadius:'0 3px 3px 0', background:C.activeTx }} />}
              <Icon name={it.icon} size={19} stroke={active?2:1.7} />
              {it.label}
            </button>
          );
        })}
      </nav>

      <div style={{ padding:'14px', borderTop:'1px solid '+C.line }}>
        {dark && (
          <div style={{ display:'flex', alignItems:'center', gap:8, padding:'8px 12px', borderRadius:'var(--r-md)',
            background:'rgba(255,64,90,.1)', marginBottom:10 }}>
            <Icon name="shield" size={15} style={{ color:'var(--ad-red)' }} />
            <span style={{ fontSize:11.5, fontWeight:800, color:'var(--ad-red)', letterSpacing:'.06em' }}>MODALITÀ ADMIN</span>
          </div>
        )}
        <div style={{ display:'flex', alignItems:'center', gap:11, padding:'8px' }}>
          <Avatar name={userName} color={RUOLI[role].color} />
          <div style={{ minWidth:0, flex:1 }}>
            <div style={{ fontSize:13, fontWeight:700, color:C.txt, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
              {userName}
            </div>
            <div style={{ fontSize:11.5, color:C.txt2 }}>{RUOLI[role].label}</div>
          </div>
        </div>
      </div>
    </aside>
  );
}

const NOTIF_ICON = {
  'booking.created': 'calendar', 'booking.modified': 'edit', 'booking.confirmed': 'check',
  'booking.freed': 'unlock', 'booking.extended': 'refresh', 'booking.expiring_soon': 'clock',
  'booking.expired': 'alertCircle',
  'rental.return_in_7d': 'clock', 'rental.return_today': 'clock', 'rental.return_date_changed': 'edit',
  'product.created': 'sparkle', 'product.modified': 'edit', 'product.status_changed': 'refresh',
  'client.created': 'users', 'client.updated': 'edit', 'client.deleted': 'x',
};

function timeAgo(iso) {
  const d = new Date(iso);
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 60) return 'ora';
  if (diff < 3600) return Math.floor(diff/60) + ' min fa';
  if (diff < 86400) return Math.floor(diff/3600) + ' h fa';
  if (diff < 2*86400) return 'ieri';
  return d.toLocaleDateString('it-IT', { day:'2-digit', month:'short' });
}

function NotifPanel({ open, onClose, items, onMarkAllRead, onNavToPrefs }) {
  if(!open) return null;
  const unreadCount = items.filter(n => !n.read).length;
  return (
    <>
      <div onClick={onClose} style={{ position:'fixed', inset:0, zIndex:40 }} />
      <div style={{ position:'absolute', top:54, right:0, width:380, zIndex:50, borderRadius:'var(--r-lg)',
        background:'var(--surface)', boxShadow:'var(--sh-3)', border:'1px solid var(--line)', overflow:'hidden', animation:'scaleIn .16s ease' }}>
        <div style={{ padding:'14px 18px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <span style={{ fontWeight:800, fontSize:14.5 }}>Notifiche</span>
          {unreadCount > 0 ? (
            <span style={{ fontSize:12, fontWeight:700, color:'var(--red)', background:'var(--red-tint)', padding:'3px 9px', borderRadius:99 }}>
              {unreadCount} {unreadCount===1?'nuova':'nuove'}
            </span>
          ) : (
            <span style={{ fontSize:11.5, fontWeight:600, color:'var(--ink-4)' }}>Tutto letto</span>
          )}
        </div>
        <div className="scroll" style={{ maxHeight:420, overflowY:'auto' }}>
          {items.length === 0 ? (
            <div style={{ padding:'40px 16px', textAlign:'center' }}>
              <Icon name="bell" size={28} style={{ color:'var(--ink-4)', opacity:.5, marginBottom:8 }} />
              <div style={{ fontSize:13, color:'var(--ink-3)', fontWeight:600 }}>Nessuna notifica</div>
            </div>
          ) : items.map(n => (
            <div key={n.id} style={{ display:'flex', gap:12, padding:'13px 18px', borderBottom:'1px solid var(--line-2)',
              background: n.read?'var(--surface)':'var(--red-tint)', transition:'background .12s' }}>
              <span style={{ width:34, height:34, borderRadius:9, flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center',
                background: n.read?'var(--line-2)':'var(--surface)', color:'var(--red)' }}>
                <Icon name={NOTIF_ICON[n.event_type] || 'bell'} size={17} />
              </span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ display:'flex', justifyContent:'space-between', gap:8 }}>
                  <span style={{ fontSize:13.5, fontWeight:700 }}>{n.title}</span>
                  {!n.read && <span style={{ width:7, height:7, borderRadius:99, background:'var(--red)', flexShrink:0, marginTop:6 }} />}
                </div>
                {n.body && <div style={{ fontSize:12.5, color:'var(--ink-2)', marginTop:2 }}>{n.body}</div>}
                <div style={{ fontSize:11.5, color:'var(--ink-4)', marginTop:4 }}>{timeAgo(n.created_at)}</div>
              </div>
            </div>
          ))}
        </div>
        <div style={{ padding:'10px 14px', display:'flex', alignItems:'center', justifyContent:'space-between', borderTop:'1px solid var(--line)' }}>
          <button onClick={(e)=>{e.preventDefault(); onNavToPrefs();}}
            style={{ fontSize:12, fontWeight:600, color:'var(--ink-3)' }}>
            Impostazioni
          </button>
          {unreadCount > 0 && (
            <button onClick={onMarkAllRead}
              style={{ fontSize:12.5, fontWeight:700, color:'var(--red)' }}>
              Segna tutte come lette
            </button>
          )}
        </div>
      </div>
    </>
  );
}

function Header({ title, subtitle, role, onLogout, search, setSearch, theme, setTheme, currentUser, onNavToPrefs }) {
  const [notifOpen, setNotifOpen] = useState(false);
  const [notifs, setNotifs] = useState([]);
  const [unread, setUnread] = useState(0);
  const user = currentUser?.nome || (role==='admin'?'Omar Menabue':role==='backoffice'?'Sara Ferrari':'Marco Bianchi');
  const isDark = theme==='dark';

  // Carica notifiche al mount + ogni 30 sec
  useEffect(() => {
    let mounted = true;
    const load = async () => {
      if (!window.LogAPI) return;
      const items = await window.LogAPI.listNotifications({ limit: 20 });
      if (mounted) {
        setNotifs(items);
        setUnread(items.filter(n => !n.read).length);
      }
    };
    load();
    const iv = setInterval(load, 30000);
    return () => { mounted = false; clearInterval(iv); };
  }, []);

  // Quando si apre il panel, segna come "lette" quelle visualizzate (dopo 1.5s)
  useEffect(() => {
    if (!notifOpen || unread === 0) return;
    const t = setTimeout(async () => {
      await window.LogAPI.markAllAsRead();
      setNotifs(prev => prev.map(n => ({ ...n, read: true })));
      setUnread(0);
    }, 1500);
    return () => clearTimeout(t);
  }, [notifOpen]);

  const handleMarkAll = async () => {
    await window.LogAPI.markAllAsRead();
    setNotifs(prev => prev.map(n => ({ ...n, read: true })));
    setUnread(0);
  };

  const goPrefs = () => {
    setNotifOpen(false);
    onNavToPrefs && onNavToPrefs();
  };

  return (
    <header style={{ height:69, flexShrink:0, background:'var(--surface)', borderBottom:'1px solid var(--line)',
      display:'flex', alignItems:'center', gap:18, padding:'0 26px', position:'relative', zIndex:30 }}>
      <div style={{ flex:1, minWidth:0 }}>
        <h1 style={{ margin:0, fontFamily:'var(--font-display)', fontSize:20, fontWeight:800, letterSpacing:'-.01em', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{title}</h1>
        {subtitle && <div style={{ fontSize:12.5, color:'var(--ink-3)', marginTop:1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{subtitle}</div>}
      </div>

      {setSearch && (
        <div style={{ position:'relative', width:'clamp(180px, 24vw, 300px)', flexShrink:0 }}>
          <Icon name="search" size={18} style={{ position:'absolute', left:13, top:'50%', transform:'translateY(-50%)', color:'var(--ink-4)' }} />
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Cerca per codice, marca, modello…"
            style={{ width:'100%', padding:'10px 14px 10px 40px', fontSize:13.5, borderRadius:'var(--r-md)',
              border:'1.5px solid var(--line)', background:'var(--surface-2)', outline:'none' }}
            onFocus={e=>e.target.style.borderColor='var(--red)'} onBlur={e=>e.target.style.borderColor='var(--line)'} />
        </div>
      )}

      <div style={{ position:'relative' }}>
        <button onClick={()=>setNotifOpen(o=>!o)} style={{ width:42, height:42, borderRadius:'var(--r-md)',
          border:'1.5px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink-2)', position:'relative' }}>
          <Icon name="bell" size={20} />
          {unread > 0 && (
            <span style={{ position:'absolute', top:6, right:7, minWidth:18, height:18, padding:'0 5px', borderRadius:99,
              background:'var(--red)', color:'#fff', fontSize:10.5, fontWeight:800, display:'flex', alignItems:'center', justifyContent:'center',
              border:'2px solid var(--surface)' }}>{unread > 99 ? '99+' : unread}</span>
          )}
        </button>
        <NotifPanel open={notifOpen} onClose={()=>setNotifOpen(false)} items={notifs}
          onMarkAllRead={handleMarkAll} onNavToPrefs={goPrefs} />
      </div>

      {setTheme && (
        <button onClick={()=>setTheme(isDark?'light':'dark')} title={isDark?'Modalità chiara':'Modalità scura'}
          style={{ width:42, height:42, borderRadius:'var(--r-md)', border:'1.5px solid var(--line)',
            display:'flex', alignItems:'center', justifyContent:'center', color: isDark?'var(--red)':'var(--ink-2)',
            background: isDark?'var(--red-tint)':'transparent' }}>
          <Icon name={isDark?'sun':'moon'} size={19} />
        </button>
      )}

      <div style={{ width:1, height:30, background:'var(--line)' }} />

      <div style={{ display:'flex', alignItems:'center', gap:10 }}>
        <Avatar name={user} color={RUOLI[role].color} size={36} />
        <div style={{ lineHeight:1.25 }}>
          <div style={{ fontSize:13.5, fontWeight:700 }}>{user}</div>
          <RolePill ruolo={role} style={{ padding:'2px 8px 2px 6px', fontSize:11 }} />
        </div>
        <button onClick={onLogout} title="Esci" style={{ width:38, height:38, borderRadius:'var(--r-md)',
          border:'1.5px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink-3)', marginLeft:4 }}>
          <Icon name="logout" size={18} />
        </button>
      </div>
    </header>
  );
}

/* ============================================================
   MOBILE COMPONENTS — BottomNav, MobileHeader, MobileDrawer
   ============================================================ */

// Le 4 voci principali nella bottom bar; il resto va nel drawer
const BOTTOM_NAV_IDS = ['dashboard', 'catalogo', 'prenotazioni', 'noleggi'];

// Icona hamburger inline (Icon "menu" non è nel set standard)
function HamburgerIcon({ size=22, stroke=1.7 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round">
      <line x1="4" y1="6" x2="20" y2="6" />
      <line x1="4" y1="12" x2="20" y2="12" />
      <line x1="4" y1="18" x2="20" y2="18" />
    </svg>
  );
}

function BottomNav({ role, view, nav, onOpenDrawer }) {
  const items = NAV.filter(n => n.roles.includes(role) && BOTTOM_NAV_IDS.includes(n.id));
  // Ordina secondo BOTTOM_NAV_IDS
  items.sort((a,b) => BOTTOM_NAV_IDS.indexOf(a.id) - BOTTOM_NAV_IDS.indexOf(b.id));

  const drawerActive = !BOTTOM_NAV_IDS.includes(view);

  return (
    <nav className="bottom-nav">
      {items.map(it => {
        const active = view === it.id;
        return (
          <button key={it.id} onClick={()=>nav(it.id)} className={"bottom-nav-item" + (active?' active':'')}>
            <Icon name={it.icon} size={22} stroke={active?2.1:1.7} />
            <span>{it.label.split(' ')[0]}</span>
          </button>
        );
      })}
      <button onClick={onOpenDrawer} className={"bottom-nav-item" + (drawerActive?' active':'')}>
        <HamburgerIcon size={22} stroke={drawerActive?2.1:1.7} />
        <span>Menu</span>
      </button>
    </nav>
  );
}

function MobileDrawer({ open, onClose, role, view, nav, currentUser, onLogout, theme, setTheme }) {
  if (!open) return null;
  const items = NAV.filter(n => n.roles.includes(role) && !BOTTOM_NAV_IDS.includes(n.id));
  const userName = currentUser?.nome || (role==='admin'?'Omar Menabue':role==='backoffice'?'Sara Ferrari':'Marco Bianchi');
  const isDark = theme==='dark';

  const goTo = (v) => { nav(v); onClose(); };

  return (
    <>
      <div className="drawer-backdrop" onClick={onClose} />
      <aside className="drawer-panel">
        {/* Header con logo */}
        <div style={{ padding:'20px 22px 18px', borderBottom:'1px solid var(--line)' }}>
          <img src={isDark ? 'assets/menabue-logo-white.png' : 'assets/menabue-logo.png'} alt="Menabue" style={{ height:36, width:'auto', display:'block', marginBottom:10 }} />
          <div style={{ display:'flex', alignItems:'center', gap:7 }}>
            <span style={{ width:6, height:6, borderRadius:99, background:'var(--red)' }} />
            <span style={{ fontSize:11, fontWeight:700, letterSpacing:'.08em', color:'var(--ink-3)', textTransform:'uppercase' }}>Smart Fleet</span>
          </div>
        </div>

        {/* Voci menu */}
        <nav className="scroll" style={{ flex:1, padding:'14px 12px', display:'flex', flexDirection:'column', gap:3, overflowY:'auto' }}>
          <div style={{ fontSize:10.5, fontWeight:800, letterSpacing:'.1em', color:'var(--ink-3)', padding:'6px 12px 8px', textTransform:'uppercase' }}>
            Altre sezioni
          </div>
          {items.map(it => {
            const active = view === it.id;
            return (
              <button key={it.id} onClick={()=>goTo(it.id)} style={{ display:'flex', alignItems:'center', gap:12,
                padding:'12px 14px', borderRadius:'var(--r-md)', fontSize:14, fontWeight:active?700:600,
                color: active ? 'var(--red)' : 'var(--ink-2)',
                background: active ? 'var(--red-tint)' : 'transparent',
                textAlign:'left', transition:'background .14s, color .14s' }}>
                <Icon name={it.icon} size={19} stroke={active?2:1.7} />
                {it.label}
              </button>
            );
          })}

          {/* Dark mode toggle: visibile solo per admin */}
          {setTheme && (
            <button onClick={()=>setTheme(isDark?'light':'dark')} style={{ display:'flex', alignItems:'center', gap:12,
              padding:'12px 14px', borderRadius:'var(--r-md)', fontSize:14, fontWeight:600,
              color: 'var(--ink-2)', background:'transparent', marginTop:8,
              textAlign:'left', borderTop:'1px solid var(--line-2)' }}>
              <Icon name={isDark?'sun':'moon'} size={19} stroke={1.7} />
              {isDark?'Modalità chiara':'Modalità scura'}
            </button>
          )}
        </nav>

        {/* Footer utente + logout */}
        <div style={{ padding:'14px', borderTop:'1px solid var(--line)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:11, padding:'8px' }}>
            <Avatar name={userName} color={RUOLI[role].color} />
            <div style={{ minWidth:0, flex:1 }}>
              <div style={{ fontSize:13, fontWeight:700, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
                {userName}
              </div>
              <div style={{ fontSize:11.5, color:'var(--ink-3)' }}>{RUOLI[role].label}</div>
            </div>
            <button onClick={()=>{ onClose(); onLogout(); }} title="Esci"
              style={{ width:40, height:40, borderRadius:'var(--r-md)',
              border:'1.5px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--red)' }}>
              <Icon name="logout" size={18} />
            </button>
          </div>
        </div>
      </aside>
    </>
  );
}

function MobileHeader({ title, subtitle, onOpenDrawer, search, setSearch, currentUser, onNavToPrefs }) {
  const [searchOpen, setSearchOpen] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);
  const [notifs, setNotifs] = useState([]);
  const [unread, setUnread] = useState(0);
  const searchInputRef = React.useRef(null);

  // Carica notifiche
  useEffect(() => {
    let mounted = true;
    const load = async () => {
      if (!window.LogAPI) return;
      const items = await window.LogAPI.listNotifications({ limit: 20 });
      if (mounted) {
        setNotifs(items);
        setUnread(items.filter(n => !n.read).length);
      }
    };
    load();
    const iv = setInterval(load, 30000);
    return () => { mounted = false; clearInterval(iv); };
  }, []);

  useEffect(() => {
    if (!notifOpen || unread === 0) return;
    const t = setTimeout(async () => {
      await window.LogAPI.markAllAsRead();
      setNotifs(prev => prev.map(n => ({ ...n, read: true })));
      setUnread(0);
    }, 1500);
    return () => clearTimeout(t);
  }, [notifOpen]);

  // Focus input search quando si apre
  useEffect(() => {
    if (searchOpen && searchInputRef.current) {
      searchInputRef.current.focus();
    }
  }, [searchOpen]);

  const handleMarkAll = async () => {
    await window.LogAPI.markAllAsRead();
    setNotifs(prev => prev.map(n => ({ ...n, read: true })));
    setUnread(0);
  };

  const goPrefs = () => {
    setNotifOpen(false);
    onNavToPrefs && onNavToPrefs();
  };

  return (
    <>
      <header className="mobile-header">
        <button className="mobile-icon-btn" onClick={onOpenDrawer} title="Menu">
          <HamburgerIcon size={20} />
        </button>

        <div className="mobile-header-title">
          {searchOpen && setSearch ? (
            <input ref={searchInputRef} value={search||''} onChange={e=>setSearch(e.target.value)}
              placeholder="Cerca…"
              style={{ width:'100%', padding:'8px 12px', fontSize:14, fontWeight:500,
                borderRadius:'var(--r-md)', border:'1.5px solid var(--red)', background:'var(--surface-2)', outline:'none' }} />
          ) : (
            <>
              <div>{title}</div>
              {subtitle && <div style={{ fontSize:11.5, fontWeight:500, color:'var(--ink-3)', marginTop:-1 }}>{subtitle}</div>}
            </>
          )}
        </div>

        {setSearch && (
          <button className="mobile-icon-btn" onClick={()=>{
            if (searchOpen) { setSearch(''); setSearchOpen(false); }
            else setSearchOpen(true);
          }} title="Cerca">
            <Icon name={searchOpen ? 'x' : 'search'} size={19} />
          </button>
        )}

        <div style={{ position:'relative' }}>
          <button className="mobile-icon-btn" onClick={()=>setNotifOpen(o=>!o)} title="Notifiche" style={{ position:'relative' }}>
            <Icon name="bell" size={19} />
            {unread > 0 && (
              <span style={{ position:'absolute', top:5, right:5, minWidth:16, height:16, padding:'0 4px', borderRadius:99,
                background:'var(--red)', color:'#fff', fontSize:9.5, fontWeight:800, display:'flex', alignItems:'center', justifyContent:'center',
                border:'2px solid var(--surface)' }}>{unread > 9 ? '9+' : unread}</span>
            )}
          </button>
        </div>
      </header>

      {/* Notifiche panel su mobile: sheet full-width sotto l'header */}
      {notifOpen && (
        <>
          <div onClick={()=>setNotifOpen(false)} style={{ position:'fixed', inset:0, zIndex:40, background:'rgba(15,17,21,.35)' }} />
          <div style={{ position:'fixed', top:50, left:8, right:8, zIndex:50, borderRadius:'var(--r-lg)',
            background:'var(--surface)', boxShadow:'var(--sh-3)', border:'1px solid var(--line)', overflow:'hidden', animation:'scaleIn .16s ease' }}>
            <div style={{ padding:'12px 16px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
              <span style={{ fontWeight:800, fontSize:14 }}>Notifiche</span>
              {unread > 0 ? (
                <span style={{ fontSize:11.5, fontWeight:700, color:'var(--red)', background:'var(--red-tint)', padding:'2px 8px', borderRadius:99 }}>
                  {unread} {unread===1?'nuova':'nuove'}
                </span>
              ) : (
                <span style={{ fontSize:11, fontWeight:600, color:'var(--ink-4)' }}>Tutto letto</span>
              )}
            </div>
            <div className="scroll" style={{ maxHeight:'60vh', overflowY:'auto' }}>
              {notifs.length === 0 ? (
                <div style={{ padding:'36px 16px', textAlign:'center' }}>
                  <Icon name="bell" size={26} style={{ color:'var(--ink-4)', opacity:.5, marginBottom:8 }} />
                  <div style={{ fontSize:13, color:'var(--ink-3)', fontWeight:600 }}>Nessuna notifica</div>
                </div>
              ) : notifs.map(n => (
                <div key={n.id} style={{ display:'flex', gap:11, padding:'12px 16px', borderBottom:'1px solid var(--line-2)',
                  background: n.read?'var(--surface)':'var(--red-tint)' }}>
                  <span style={{ width:32, height:32, borderRadius:9, flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center',
                    background: n.read?'var(--line-2)':'var(--surface)', color:'var(--red)' }}>
                    <Icon name={NOTIF_ICON[n.event_type] || 'bell'} size={16} />
                  </span>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ display:'flex', justifyContent:'space-between', gap:8 }}>
                      <span style={{ fontSize:13, fontWeight:700 }}>{n.title}</span>
                      {!n.read && <span style={{ width:7, height:7, borderRadius:99, background:'var(--red)', flexShrink:0, marginTop:6 }} />}
                    </div>
                    {n.body && <div style={{ fontSize:12, color:'var(--ink-2)', marginTop:2 }}>{n.body}</div>}
                    <div style={{ fontSize:11, color:'var(--ink-4)', marginTop:3 }}>{timeAgo(n.created_at)}</div>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ padding:'10px 14px', display:'flex', alignItems:'center', justifyContent:'space-between', borderTop:'1px solid var(--line)' }}>
              <button onClick={goPrefs} style={{ fontSize:12, fontWeight:600, color:'var(--ink-3)' }}>Impostazioni</button>
              {unread > 0 && (
                <button onClick={handleMarkAll} style={{ fontSize:12.5, fontWeight:700, color:'var(--red)' }}>Segna tutte come lette</button>
              )}
            </div>
          </div>
        </>
      )}
    </>
  );
}

Object.assign(window, { Sidebar, Header, NotifPanel, NAV, BottomNav, MobileHeader, MobileDrawer, BOTTOM_NAV_IDS });