// ─────────────────────────────────────────────────────
// LAYOUT — Sidebar + Header + Mobile + Logo uploadable
// ─────────────────────────────────────────────────────

// Planning et Pointage fusionnés — un seul item de nav
const NAV_ITEMS = [
  { id:'dashboard',        label:'Tableau de bord',     icon:'◈', permKey:'dashboard' },
  { id:'planning',         label:'Planning & Pointage', icon:'▦', permKey:'planning' },
  { id:'cartes',           label:'Cartes & Recettes',   icon:'◉', permKey:'recettes' },
  { id:'inventaire',       label:'Inventaire',          icon:'▣', permKey:'inventaire' },
  { id:'pertes',           label:'Pertes',              icon:'◬', permKey:'pertes' },
  { id:'haccp',            label:'HACCP',               icon:'⊕', permKey:'haccp' },
  { id:'fiches_salle',     label:'Fiches salle',        icon:'◫', permKey:'fiches_salle' },
  { id:'documents',        label:'Documents',           icon:'▤', permKey:'documents' },
  { id:'consultant_tools', label:'Outils consultant',   icon:'✦', permKey:'consultant_tools' },
  { id:'roles',            label:'Rôles & Accès',       icon:'◎', permKey:'roles' },
  { id:'parametres',       label:'Établissements',      icon:'⬡', permKey:'parametres' },
];

const useIsMobile = () => {
  const [mobile, setMobile] = React.useState(typeof window !== 'undefined' && window.innerWidth < 768);
  React.useEffect(() => {
    const handler = () => setMobile(window.innerWidth < 768);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);
  return mobile;
};

const Layout = ({ user, currentPage, setPage, onLogout, children, etablissement, setEtablissement }) => {
  const isMobile = useIsMobile();
  const [sidebarOpen, setSidebarOpen] = React.useState(!isMobile);
  const [notifOpen, setNotifOpen] = React.useState(false);
  const [logoMenuOpen, setLogoMenuOpen] = React.useState(false);
  const [showMore, setShowMore] = React.useState(false);
  const [logoHover, setLogoHover] = React.useState(false);

  // Logo uploadable — stocké en localStorage
  const [appLogo, setAppLogo] = React.useState(() => scRead('sc_app_logo', null));
  const fileInputRef = React.useRef(null);

  // Permissions dynamiques (relues à chaque render depuis DEMO_DATA, hydraté depuis localStorage)
  const perms = DEMO_DATA.permissions[user.role] || {};
  const roleInfo = DEMO_DATA.roles[user.role];

  // Établissements accessibles à l'utilisateur
  const etabs = DEMO_DATA.etablissements.filter(e => user.etablissementIds.includes(e.id));

  // Persister l'établissement courant (pour que les autres modules et le PDF puissent y accéder)
  React.useEffect(() => {
    if (etablissement?.id) scWrite('sc_current_etab', etablissement.id);
  }, [etablissement]);

  // Nav filtrée : on cache TOUT module dont la permission est false
  const visibleNav = NAV_ITEMS.filter(item => {
    const permVal = perms[item.permKey];
    return permVal !== false && permVal !== undefined;
  });

  // ═══ ALERTES DYNAMIQUES : Pointages manquants + HACCP en retard ═══
  const alertes = React.useMemo(() => {
    const result = [];
    const today = new Date().toISOString().slice(0, 10);
    const etabId = etablissement?.id || 'etab-1';

    // 1. Pointages manquants : shifts d'aujourd'hui où l'employé devait être là mais n'a pas pointé l'arrivée
    try {
      const planning = scRead('sc_planning', DEMO_DATA.planning);
      const now = new Date();
      const nowTime = String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0');
      const todayShifts = planning.filter(s => s.date === today && (s.etablissementId || 'etab-1') === etabId);
      todayShifts.forEach(shift => {
        if (!shift.pointageDebut && shift.debut && shift.debut <= nowTime) {
          const emp = DEMO_DATA.utilisateurs.find(u => u.id === shift.userId);
          if (emp) {
            result.push({
              txt: `Pointage manquant — ${emp.prenom} ${emp.nom} (${shift.debut})`,
              type: 'warn',
              category: 'pointage',
            });
          }
        }
      });
    } catch (e) { /* silencieux */ }

    // 2. Relevés HACCP en retard : tâches/contrôles non effectués à date
    try {
      const releves = scRead('sc_haccp_releves', []);
      const controls = scRead('sc_haccp_controls', []);
      // Compter les contrôles de ce jour non effectués
      const todayControls = (Array.isArray(controls) ? controls : []).filter(c => c.date === today && (c.etablissementId || 'etab-1') === etabId && !c.effectue);
      todayControls.forEach(c => {
        result.push({
          txt: `HACCP en retard — ${c.nom || c.type || 'contrôle'} (aujourd'hui)`,
          type: 'warn',
          category: 'haccp',
        });
      });
      // Relevés de température hors plage sur les 2 derniers jours
      const d2 = new Date(); d2.setDate(d2.getDate() - 2);
      const d2str = d2.toISOString().slice(0, 10);
      const relevesRecent = (Array.isArray(releves) ? releves : []).filter(r => r.date >= d2str && (r.etablissementId || 'etab-1') === etabId);
      relevesRecent.forEach(r => {
        if (r.horsPlage || r.alerte) {
          result.push({
            txt: `⚠ HACCP — ${r.zone || r.equipement || 'relevé'} hors plage (${r.valeur || '?'}°C le ${r.date})`,
            type: 'warn',
            category: 'haccp',
          });
        }
      });
    } catch (e) { /* silencieux */ }

    return result.slice(0, 10); // max 10 alertes affichées
  }, [currentPage, etablissement]);

  React.useEffect(() => { if (isMobile) setSidebarOpen(false); }, [currentPage, isMobile]);

  const handleSetPage = (p) => { setPage(p); if (isMobile) setSidebarOpen(false); };

  const currentItem = NAV_ITEMS.find(n => n.id === currentPage);

  // ── Logo upload (consultant uniquement)
  const canEditLogo = user.role === 'consultant';

  const handleLogoUpload = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) {
      alert('Veuillez sélectionner une image (PNG, JPG, SVG).');
      return;
    }
    if (file.size > 500 * 1024) {
      alert('Image trop lourde (max 500 Ko). Merci d\'en choisir une plus petite.');
      return;
    }
    const reader = new FileReader();
    reader.onload = ev => {
      const dataUrl = ev.target.result;
      setAppLogo(dataUrl);
      scWrite('sc_app_logo', dataUrl);
      setLogoMenuOpen(false);
    };
    reader.readAsDataURL(file);
    e.target.value = '';
  };

  const handleLogoRemove = () => {
    if (!window.confirm('Revenir au logo par défaut "SC" ?')) return;
    setAppLogo(null);
    localStorage.removeItem('sc_app_logo');
    setLogoMenuOpen(false);
  };

  const LogoMark = ({ size = 34, fontSize = 12 }) => (
    <div style={{
      width: size, height: size, borderRadius: 8,
      background: appLogo ? 'transparent' : 'var(--accent)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontWeight: 700, fontSize, color: '#fff',
      fontFamily: 'var(--font-serif)', letterSpacing: 1, flexShrink: 0,
      overflow: 'hidden', position: 'relative',
      cursor: canEditLogo ? 'pointer' : 'default',
      border: canEditLogo && logoHover ? '2px dashed var(--accent)' : '2px solid transparent',
      transition: 'border 0.15s',
    }}
    onMouseEnter={() => canEditLogo && setLogoHover(true)}
    onMouseLeave={() => setLogoHover(false)}
    onClick={canEditLogo ? (e) => { e.stopPropagation(); setLogoMenuOpen(!logoMenuOpen); } : undefined}
    title={canEditLogo ? 'Cliquer pour changer le logo' : ''}>
      {appLogo
        ? <img src={appLogo} alt="logo" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        : 'SC'}
      {canEditLogo && logoHover && (
        <div style={{
          position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: size > 30 ? 14 : 10, color: '#fff',
        }}>
          ✎
        </div>
      )}
    </div>
  );

  const LogoMenu = () => (
    logoMenuOpen && canEditLogo && (
      <div style={ls.logoMenu} onClick={e => e.stopPropagation()}>
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          style={{ display: 'none' }}
          onChange={handleLogoUpload}
        />
        <button style={ls.logoMenuBtn} onClick={() => fileInputRef.current?.click()}>
          📁 Changer le logo
        </button>
        {appLogo && (
          <button style={{ ...ls.logoMenuBtn, color: '#dc2626' }} onClick={handleLogoRemove}>
            🗑 Retirer le logo
          </button>
        )}
        <div style={{ fontSize: 10, color: 'var(--text2)', padding: '8px 12px 4px', borderTop: '1px solid var(--border)' }}>
          Max 500 Ko. PNG, JPG ou SVG.
        </div>
      </div>
    )
  );

  // ════════════════════════════════
  // MOBILE BOTTOM NAV
  // ════════════════════════════════
  if (isMobile) {
    const topNav = visibleNav.slice(0, 4);
    const moreNav = visibleNav.slice(4);

    return (
      <div style={ls.mobileRoot}>
        <header style={ls.mobileTopbar}>
          <div style={{ position: 'relative' }}>
            <LogoMark size={32} fontSize={11} />
            <LogoMenu />
          </div>
          <div style={ls.mobileTitle}>{currentItem?.label || 'Tableau de bord'}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {etabs.length > 1 && (
              <select style={ls.mobileEtabSelect} value={etablissement?.id || etabs[0].id}
                      onChange={e => setEtablissement(etabs.find(et => et.id === e.target.value))}>
                {etabs.map(et => <option key={et.id} value={et.id}>{et.nom}</option>)}
              </select>
            )}
            <div style={{ position: 'relative' }}>
              <button style={ls.iconBtn} onClick={() => setNotifOpen(!notifOpen)}>
                <span style={{ fontSize: 18 }}>🔔</span>
                {alertes.length > 0 && <div style={ls.notifDot}>{alertes.length}</div>}
              </button>
              {notifOpen && (
                <div style={{ ...ls.notifPanel, right: 0, top: 40 }}>
                  <div style={ls.notifHeader}>Alertes ({alertes.length})</div>
                  {alertes.length === 0 && <div style={{ ...ls.notifItem, color: 'var(--text2)', fontStyle: 'italic', borderLeft: '3px solid #16a34a' }}>✓ Aucune alerte — tout est à jour</div>}
                  {alertes.map((a, i) => (
                    <div key={i} style={{ ...ls.notifItem, borderLeft: `3px solid ${a.type === 'warn' ? '#f59e0b' : '#3b82f6'}` }}>{a.txt}</div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </header>

        <main style={ls.mobileContent} onClick={() => { notifOpen && setNotifOpen(false); showMore && setShowMore(false); logoMenuOpen && setLogoMenuOpen(false); }}>
          {children}
        </main>

        <nav style={ls.mobileNav}>
          {topNav.map(item => {
            const active = currentPage === item.id;
            return (
              <button key={item.id} style={{ ...ls.mobileNavBtn, ...(active ? ls.mobileNavActive : {}) }} onClick={() => handleSetPage(item.id)}>
                <span style={{ fontSize: 19, lineHeight: 1 }}>{item.icon}</span>
                <span style={{ fontSize: 9, marginTop: 3, fontWeight: active ? 700 : 500, maxWidth: 62, textAlign: 'center', lineHeight: 1.1 }}>{item.label}</span>
              </button>
            );
          })}
          {moreNav.length > 0 && (
            <button style={{ ...ls.mobileNavBtn, ...(showMore ? ls.mobileNavActive : {}) }} onClick={() => setShowMore(!showMore)}>
              <span style={{ fontSize: 19, lineHeight: 1 }}>⋯</span>
              <span style={{ fontSize: 9, marginTop: 3, fontWeight: 500 }}>Plus</span>
            </button>
          )}
          {showMore && (
            <div style={ls.moreDrawer}>
              {moreNav.map(item => {
                const active = currentPage === item.id;
                return (
                  <button key={item.id} style={{ ...ls.moreItem, ...(active ? { background: 'var(--accent-light)', color: 'var(--accent)' } : {}) }} onClick={() => handleSetPage(item.id)}>
                    <span style={{ fontSize: 20 }}>{item.icon}</span>
                    <span style={{ flex: 1, textAlign: 'left', fontSize: 14, fontWeight: 600 }}>{item.label}</span>
                    {active && <span style={{ fontSize: 14, color: 'var(--accent)' }}>●</span>}
                  </button>
                );
              })}
              <div style={{ borderTop: '1px solid var(--border)', margin: '8px 0' }} />
              <div style={{ padding: '8px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ ...ls.mobileAvatar, background: roleInfo.couleur }}>{user.avatar}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>{user.prenom} {user.nom}</div>
                  <div style={{ fontSize: 11, color: 'var(--text2)' }}>{roleInfo.label}</div>
                </div>
                <button style={{ background: 'none', border: '1px solid var(--border)', padding: '6px 12px', borderRadius: 6, fontSize: 12, color: 'var(--text2)', cursor: 'pointer', fontFamily: 'var(--font)' }} onClick={onLogout}>Déco.</button>
              </div>
            </div>
          )}
        </nav>
      </div>
    );
  }

  // ════════════════════════════════
  // DESKTOP
  // ════════════════════════════════
  return (
    <div style={ls.root} onClick={() => { notifOpen && setNotifOpen(false); logoMenuOpen && setLogoMenuOpen(false); }}>
      <aside style={{ ...ls.sidebar, width: sidebarOpen ? 234 : 58 }}>
        <div style={ls.sidebarTop}>
          <div style={ls.logoWrap}>
            <div style={{ position: 'relative' }}>
              <LogoMark size={34} fontSize={12} />
              <LogoMenu />
            </div>
            {sidebarOpen && (
              <div style={ls.logoText}>
                <div style={ls.logoName}>Samper Consulting</div>
                <div style={ls.logoSub}>Gestion culinaire</div>
              </div>
            )}
          </div>
          <button style={ls.toggleBtn} onClick={() => setSidebarOpen(!sidebarOpen)}>
            {sidebarOpen ? '◂' : '▸'}
          </button>
        </div>

        {sidebarOpen && etabs.length > 0 && (
          <div style={ls.etabWrap}>
            <div style={ls.etabLabel}>Établissement</div>
            <select style={ls.etabSelect} value={etablissement?.id || etabs[0].id} onChange={e => setEtablissement(etabs.find(et => et.id === e.target.value))}>
              {etabs.map(et => <option key={et.id} value={et.id}>{et.nom}</option>)}
            </select>
          </div>
        )}

        <nav style={ls.nav}>
          {visibleNav.map(item => {
            const active = currentPage === item.id;
            return (
              <button key={item.id}
                style={{ ...ls.navItem, ...(active ? ls.navActive : {}), justifyContent: sidebarOpen ? 'flex-start' : 'center' }}
                onClick={() => handleSetPage(item.id)} title={!sidebarOpen ? item.label : ''}>
                <span style={{ ...ls.navIcon, ...(item.id === 'consultant_tools' ? { color: 'var(--accent)' } : {}) }}>{item.icon}</span>
                {sidebarOpen && <span style={ls.navLabel}>{item.label}</span>}
                {active && <div style={ls.navActiveLine} />}
              </button>
            );
          })}
        </nav>

        <div style={{ ...ls.userArea, padding: sidebarOpen ? '14px 16px' : '14px 0', justifyContent: sidebarOpen ? 'flex-start' : 'center' }}>
          <div style={{ ...ls.avatar, background: roleInfo.couleur }}>{user.avatar}</div>
          {sidebarOpen && (
            <div style={ls.userInfo}>
              <div style={ls.userName}>{user.prenom} {user.nom}</div>
              <div style={{ ...ls.userRole, color: roleInfo.couleur }}>{roleInfo.label}</div>
            </div>
          )}
        </div>
      </aside>

      <div style={ls.main}>
        <header style={ls.topbar}>
          <div style={ls.topbarLeft}>
            <div style={ls.pageTitle}>{currentItem?.label || 'Tableau de bord'}</div>
            {etablissement && <div style={ls.etabBadge}>{etablissement.nom}</div>}
          </div>
          <div style={ls.topbarRight}>
            <div style={{ position: 'relative' }}>
              <button style={ls.iconBtn} onClick={(e) => { e.stopPropagation(); setNotifOpen(!notifOpen); }}>
                <span>🔔</span>
                {alertes.length > 0 && <div style={ls.notifDot}>{alertes.length}</div>}
              </button>
              {notifOpen && (
                <div style={ls.notifPanel}>
                  <div style={ls.notifHeader}>Alertes ({alertes.length})</div>
                  {alertes.length === 0 && <div style={{ ...ls.notifItem, color: 'var(--text2)', fontStyle: 'italic', borderLeft: '3px solid #16a34a' }}>✓ Aucune alerte — tout est à jour</div>}
                  {alertes.map((a, i) => (
                    <div key={i} style={{ ...ls.notifItem, borderLeft: `3px solid ${a.type === 'warn' ? '#f59e0b' : '#3b82f6'}` }}>{a.txt}</div>
                  ))}
                </div>
              )}
            </div>
            <div style={ls.topbarDivider} />
            <button style={ls.logoutBtn} onClick={onLogout}>Déconnexion</button>
          </div>
        </header>

        <main style={ls.content}>{children}</main>
      </div>
    </div>
  );
};

const ls = {
  // Desktop
  root: { display: 'flex', height: '100vh', fontFamily: 'var(--font)', background: 'var(--bg)', overflow: 'hidden' },
  sidebar: { background: 'var(--nav)', display: 'flex', flexDirection: 'column', flexShrink: 0, overflow: 'visible', borderRight: '1px solid rgba(255,255,255,0.05)', transition: 'width .18s' },
  sidebarTop: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 14px 12px', borderBottom: '1px solid rgba(255,255,255,0.06)', flexShrink: 0 },
  logoWrap: { display: 'flex', alignItems: 'center', gap: 10, overflow: 'visible' },
  logoText: { overflow: 'hidden' },
  logoName: { color: '#fff', fontWeight: 700, fontSize: 14, lineHeight: 1.2, whiteSpace: 'nowrap' },
  logoSub: { color: 'rgba(255,255,255,0.4)', fontSize: 10, whiteSpace: 'nowrap' },
  logoMenu: { position: 'absolute', top: '100%', left: 0, marginTop: 6, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 10, boxShadow: '0 6px 24px rgba(0,0,0,0.12)', width: 200, zIndex: 300, overflow: 'hidden' },
  logoMenuBtn: { width: '100%', display: 'block', textAlign: 'left', padding: '10px 14px', background: 'none', border: 'none', fontSize: 13, color: 'var(--text)', cursor: 'pointer', fontFamily: 'var(--font)' },
  toggleBtn: { background: 'none', border: 'none', color: 'rgba(255,255,255,0.35)', cursor: 'pointer', fontSize: 14, padding: 4, flexShrink: 0 },
  etabWrap: { padding: '12px 14px', borderBottom: '1px solid rgba(255,255,255,0.06)', flexShrink: 0 },
  etabLabel: { color: 'rgba(255,255,255,0.3)', fontSize: 10, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6 },
  etabSelect: { width: '100%', background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.1)', color: 'rgba(255,255,255,0.8)', borderRadius: 6, padding: '6px 8px', fontSize: 12, cursor: 'pointer', fontFamily: 'var(--font)' },
  nav: { flex: 1, display: 'flex', flexDirection: 'column', gap: 2, padding: '12px 8px', overflowY: 'auto' },
  navItem: { display: 'flex', alignItems: 'center', gap: 10, padding: '9px 10px', borderRadius: 8, border: 'none', background: 'none', color: 'rgba(255,255,255,0.5)', cursor: 'pointer', fontSize: 13, fontWeight: 500, position: 'relative', transition: 'background .15s,color .15s', fontFamily: 'var(--font)', width: '100%', textAlign: 'left' },
  navActive: { background: 'rgba(255,255,255,0.1)', color: '#fff' },
  navActiveLine: { position: 'absolute', right: 0, top: '50%', transform: 'translateY(-50%)', width: 3, height: 18, background: 'var(--accent)', borderRadius: 2 },
  navIcon: { fontSize: 14, flexShrink: 0, width: 18, textAlign: 'center' },
  navLabel: { whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
  userArea: { display: 'flex', alignItems: 'center', gap: 10, borderTop: '1px solid rgba(255,255,255,0.06)', flexShrink: 0, boxSizing: 'border-box' },
  avatar: { width: 34, height: 34, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: 12, flexShrink: 0 },
  userInfo: { overflow: 'hidden' },
  userName: { color: '#fff', fontWeight: 600, fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
  userRole: { fontSize: 11, fontWeight: 500, whiteSpace: 'nowrap' },
  main: { flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' },
  topbar: { height: 56, background: 'var(--surface)', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 24px', flexShrink: 0 },
  topbarLeft: { display: 'flex', alignItems: 'center', gap: 12 },
  pageTitle: { fontSize: 16, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-serif)' },
  etabBadge: { background: 'var(--accent-light)', color: 'var(--accent)', fontSize: 11, fontWeight: 600, padding: '3px 9px', borderRadius: 20 },
  topbarRight: { display: 'flex', alignItems: 'center', gap: 12 },
  iconBtn: { background: 'none', border: 'none', cursor: 'pointer', fontSize: 16, position: 'relative', padding: 4 },
  notifDot: { position: 'absolute', top: 0, right: 0, background: '#ef4444', color: '#fff', fontSize: 9, fontWeight: 700, width: 16, height: 16, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center' },
  notifPanel: { position: 'absolute', right: 0, top: 40, width: 300, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.1)', zIndex: 200 },
  notifHeader: { padding: '12px 16px', borderBottom: '1px solid var(--border)', fontSize: 12, fontWeight: 700, color: 'var(--text2)', textTransform: 'uppercase', letterSpacing: 0.5 },
  notifItem: { padding: '10px 14px', fontSize: 13, color: 'var(--text)', borderBottom: '1px solid var(--border)', lineHeight: 1.4 },
  topbarDivider: { width: 1, height: 20, background: 'var(--border)' },
  logoutBtn: { background: 'none', border: '1px solid var(--border)', color: 'var(--text2)', padding: '6px 14px', borderRadius: 6, fontSize: 12, cursor: 'pointer', fontFamily: 'var(--font)' },
  content: { flex: 1, overflowY: 'auto', padding: '24px' },

  // Mobile
  mobileRoot: { display: 'flex', flexDirection: 'column', height: '100vh', fontFamily: 'var(--font)', background: 'var(--bg)' },
  mobileTopbar: { height: 54, background: 'var(--nav)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 14px', flexShrink: 0, gap: 10 },
  mobileTitle: { flex: 1, color: '#fff', fontWeight: 700, fontSize: 14, fontFamily: 'var(--font-serif)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
  mobileEtabSelect: { background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.1)', color: 'rgba(255,255,255,0.9)', borderRadius: 5, padding: '4px 6px', fontSize: 11, maxWidth: 100, fontFamily: 'var(--font)' },
  mobileContent: { flex: 1, overflowY: 'auto', padding: '12px', WebkitOverflowScrolling: 'touch' },
  mobileNav: { display: 'flex', background: 'var(--surface)', borderTop: '1px solid var(--border)', flexShrink: 0, position: 'relative', zIndex: 50, paddingBottom: 'env(safe-area-inset-bottom)' },
  mobileNavBtn: { flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '8px 4px 10px', background: 'none', border: 'none', color: 'var(--text2)', cursor: 'pointer', fontFamily: 'var(--font)', gap: 2, minHeight: 58 },
  mobileNavActive: { color: 'var(--accent)' },
  mobileAvatar: { width: 34, height: 34, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: 12, flexShrink: 0 },
  moreDrawer: { position: 'absolute', bottom: '100%', left: 0, right: 0, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: '12px 12px 0 0', boxShadow: '0 -8px 32px rgba(0,0,0,0.12)', padding: '8px 0', maxHeight: '70vh', overflowY: 'auto' },
  moreItem: { display: 'flex', alignItems: 'center', gap: 14, padding: '13px 20px', background: 'none', border: 'none', width: '100%', cursor: 'pointer', fontFamily: 'var(--font)', color: 'var(--text)', transition: 'background .1s' },
};

Object.assign(window, { Layout });
