import { Fragment, useState } from 'react';
import { View, Text, Pressable, StyleSheet, Modal, Platform } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Ionicons from '@expo/vector-icons/Ionicons';
import { useQuery } from '@tanstack/react-query';
import { colors, spacing, radii, typography } from '../theme';
import { PRIMARY_ITEMS, SECONDARY_ITEMS, TABBAR_PRIMARY_ITEMS, TABBAR_SECONDARY_ITEMS } from '../navigation/navItems';
import { ClemIcon } from './ClemIcon';
import { fetchDieticianUnreadCount } from '../api/dieticianReport';

// Rose de la pastille "messages non lus" (maquette Claude Design "ClemIA Chatbot") —
// couleur locale à ce composant, pas ajoutée au thème global (même précédent que les
// dégradés scoped par écran).
const UNREAD_COLOR = '#E11D6B';
const UNREAD_BG = '#ffe9f1';

function useDieticianUnreadCount() {
  const { data } = useQuery({
    queryKey: ['dieticianUnreadCount'],
    queryFn: fetchDieticianUnreadCount,
    refetchInterval: 3 * 60 * 1000,
  });
  return data?.count ?? 0;
}

type Props = {
  activeScreen: string;
  orientation: 'rail' | 'tabbar' | 'burger';
  onNavigate: (screen: string) => void;
  onLogout: () => void;
  // Bouton "+" central de la barre du bas format téléphone (mockup Claude Design "Mon
  // suivi" 1b/2a) — n'a de sens qu'en orientation "tabbar", ignoré ailleurs.
  onQuickAdd?: () => void;
};

const isWeb = Platform.OS === 'web';

export function AppNavBar({ activeScreen, orientation, onNavigate, onLogout, onQuickAdd }: Props) {
  const [moreOpen, setMoreOpen] = useState(false);
  const insets = useSafeAreaInsets();
  const isBurger = orientation === 'burger';
  const isWide = orientation === 'rail';
  // Format téléphone (barre du bas + "+"), seul cas restant une fois `isBurger`
  // écarté ci-dessus et `isWide` (rail) écarté par le rendu ci-dessous.
  const isTabbarPhone = !isBurger && !isWide;
  // Rail large écran web (desktop mobile-web) : sidebar plus large, lignes
  // horizontales icône+libellé, calquée sur la maquette Claude Design "Mes
  // Repas" (logo "CLEM AI" en tête de colonne) — le rail natif (tablette)
  // garde sa mise en page verticale compacte historique, inchangée.
  const isRailWeb = isWide && isWeb;
  // Format téléphone : le bouton/panneau "Compte" de cette barre n'existe plus (déplacé
  // dans `TopMenuBar` ci-dessous, barre du haut) — cette liste ne sert donc plus qu'au
  // rail (tablette native/desktop web).
  const secondaryItems = SECONDARY_ITEMS.filter((item) => !('webOnly' in item) || Platform.OS === 'web');

  function go(screen: string) {
    setMoreOpen(false);
    onNavigate(screen);
  }

  const moreActive = secondaryItems.some((item) => item.screen === activeScreen);

  // Mode burger : plus invoqué par aucun appelant depuis le 2026-08-11 (revert vers la
  // barre du bas + "+", voir .wolf/cerebrum.md Decision Log) — code gardé tel quel
  // (même précédent que l'ex-dead-code 'tabbar' avant le burger du 2026-08-01), au cas
  // où ce mode serait redemandé un jour.
  if (isBurger) {
    const drawerItems = [...PRIMARY_ITEMS, ...secondaryItems];
    return (
      <>
        <View
          style={[styles.burgerBar, { paddingTop: insets.top + spacing.sm }]}
          nativeID={isWeb ? 'app-burger-bar' : undefined}
        >
          <Pressable style={styles.burgerButton} onPress={() => setMoreOpen(true)} hitSlop={8}>
            <Ionicons name="menu-outline" size={26} color={colors.text} />
          </Pressable>
          <Text style={styles.wordmark}>
            CLEM <Text style={styles.wordmarkAccent}>AI</Text>
          </Text>
          <View style={styles.burgerButton} />
        </View>

        <Modal visible={moreOpen} transparent animationType="fade" onRequestClose={() => setMoreOpen(false)}>
          <Pressable style={styles.drawerOverlay} onPress={() => setMoreOpen(false)}>
            <View style={[styles.drawerPanel, { paddingTop: insets.top + spacing.lg }]}>
              {drawerItems.map((item) => {
                const active = item.screen === activeScreen;
                return (
                  <Pressable
                    key={item.screen}
                    style={[styles.drawerItem, active && styles.drawerItemActive]}
                    onPress={() => go(item.screen)}
                  >
                    {'icon' in item && (
                      <Ionicons
                        name={item.icon as any}
                        size={19}
                        color={active ? colors.primary : colors.textMuted}
                        style={styles.drawerItemIcon}
                      />
                    )}
                    <Text style={[styles.drawerItemText, active && styles.drawerItemTextActive]}>{item.label}</Text>
                  </Pressable>
                );
              })}
              <Pressable
                style={[styles.drawerItem, styles.drawerLastItem]}
                onPress={() => {
                  setMoreOpen(false);
                  onLogout();
                }}
              >
                <Text style={[styles.drawerItemText, styles.logoutText]}>Déconnexion</Text>
              </Pressable>
            </View>
          </Pressable>
        </Modal>
      </>
    );
  }

  const primaryItems = isTabbarPhone ? TABBAR_PRIMARY_ITEMS : PRIMARY_ITEMS;
  // Coupure façon mockup ("Suivi Repas [+] Jeûne Profil") : un espace vide réserve la
  // place du "+" flottant sans chevaucher un libellé, aussi proche que possible du
  // milieu réel des onglets rendus (arrondi au-dessus : penche légèrement à gauche si
  // le compte est impair, comme avec les 3 onglets actuels de TABBAR_PRIMARY_ITEMS).
  const tabbarGapIndex = Math.ceil(primaryItems.length / 2);

  return (
    <>
      <View style={styles.tabbarWrap}>
        <View
          style={
            isRailWeb
              ? styles.railWeb
              : isWide
                ? styles.rail
                : [styles.tabbar, { paddingBottom: 6 + insets.bottom }]
          }
        >
          {/* Icône produit retirée d'ici (demande explicite utilisateur, 2026-08-21) —
              elle ne vit plus que sur le bouton du menu burger (TopMenuBar ci-dessous),
              ce rail garde seulement le mot-symbole texte. */}
          {isRailWeb && (
            <View style={styles.brand}>
              <Text style={styles.wordmark}>
                CLEM <Text style={styles.wordmarkAccent}>AI</Text>
              </Text>
            </View>
          )}
          {/* Rail (tablette native / desktop web) : le "+" flottant n'existe que sur la
              barre du bas format téléphone — sans ce bouton, aucun moyen d'ouvrir le
              dialogue d'ajout en vue large (régression repérée par l'utilisateur). Même
              câblage `onQuickAdd` que le "+" de la barre du bas (navigation cross-écran
              vers "Mon suivi" + ouverture du dialogue, voir RootNavigator.tsx/App.web.tsx). */}
          {isWide && onQuickAdd && (
            <Pressable
              style={isRailWeb ? styles.railWebAddButton : styles.railAddButton}
              onPress={onQuickAdd}
              accessibilityLabel="Ajouter un aliment"
            >
              <Ionicons name="add" size={isRailWeb ? 18 : 22} color="#fff" />
              {isRailWeb && <Text style={styles.railWebAddButtonText}>Ajouter</Text>}
            </Pressable>
          )}
          {primaryItems.map((item, idx) => (
            <Fragment key={item.screen}>
              {isTabbarPhone && idx === tabbarGapIndex && <View style={styles.tabbarGap} />}
              <NavButton
                icon={item.icon}
                label={item.label}
                active={item.screen === activeScreen}
                vertical={isWide}
                railWeb={isRailWeb}
                onPress={() => go(item.screen)}
              />
            </Fragment>
          ))}
          {/* Onglet "ClemIA" (maquette Claude Design "ClemIA Chatbot") : pas un item de
              `primaryItems` (icône dynamique violet/rose + pastille selon les messages non
              lus, pas une icône Ionicons statique) — ajouté à la main ici, même patron que
              le bouton "Compte" du rail natif ci-dessous. */}
          <ClemIANavButton
            active={activeScreen === 'ClemIA'}
            vertical={isWide}
            railWeb={isRailWeb}
            onPress={() => go('ClemIA')}
          />
          {/* Rail large écran web : la place ne manque pas, donc les entrées secondaires
              (Profil/Compte/Préférences/Jeûne/Poids) restent visibles en permanence plutôt
              que cachées derrière le bouton "Compte" — réservé au rail natif compact
              (tablette) et à la barre du bas téléphone, où la place manque. */}
          {isRailWeb && (
            <>
              <View style={styles.railDividerWeb} />
              {secondaryItems.map((item) => (
                <NavButton
                  key={item.screen}
                  icon={item.icon}
                  label={item.label}
                  active={item.screen === activeScreen}
                  vertical={isWide}
                  railWeb={isRailWeb}
                  onPress={() => go(item.screen)}
                />
              ))}
            </>
          )}
          <View style={isRailWeb ? styles.railSpacerWeb : isWide ? styles.railSpacer : styles.tabbarSpacer} />
          {isRailWeb ? (
            <Pressable style={styles.railWebLogout} onPress={onLogout}>
              <Ionicons name="log-out-outline" size={19} color={colors.danger} />
              <Text style={styles.railWebLogoutText}>Déconnexion</Text>
            </Pressable>
          ) : (
            // Rail natif (tablette) uniquement — format téléphone : le "Compte" est
            // maintenant le bouton burger de `TopMenuBar` (barre du haut), pas un onglet
            // de cette barre du bas.
            isWide && (
              <NavButton
                icon="person-circle-outline"
                label="Compte"
                active={moreActive}
                vertical={isWide}
                railWeb={isRailWeb}
                onPress={() => setMoreOpen(true)}
              />
            )
          )}
        </View>

        {/* Bouton "+" central débordant au-dessus de la barre (mockup 1b/2a) — ouvre le
            dialogue d'ajout d'aliment de l'écran "Mon suivi" depuis n'importe quel écran
            (voir RootNavigator.tsx/App.web.tsx pour le câblage de `onQuickAdd`). */}
        {isTabbarPhone && onQuickAdd && (
          <Pressable
            style={[styles.tabbarFab, { bottom: 42 + insets.bottom }]}
            onPress={onQuickAdd}
            hitSlop={4}
            accessibilityLabel="Ajouter un aliment"
          >
            <Ionicons name="add" size={30} color="#fff" />
          </Pressable>
        )}
      </View>

      <Modal visible={moreOpen} transparent animationType="fade" onRequestClose={() => setMoreOpen(false)}>
        <Pressable style={styles.overlay} onPress={() => setMoreOpen(false)}>
          <View style={styles.panel}>
            {secondaryItems.map((item) => (
              <Pressable key={item.screen} style={styles.panelItem} onPress={() => go(item.screen)}>
                {'icon' in item && (
                  <Ionicons name={item.icon as any} size={18} color={colors.textMuted} style={styles.panelItemIcon} />
                )}
                <Text style={styles.panelItemText}>{item.label}</Text>
              </Pressable>
            ))}
            <Pressable
              style={[styles.panelItem, styles.panelLastItem]}
              onPress={() => {
                setMoreOpen(false);
                onLogout();
              }}
            >
              <Text style={[styles.panelItemText, styles.logoutText]}>Déconnexion</Text>
            </Pressable>
          </View>
        </Pressable>
      </Modal>
    </>
  );
}

type TopMenuBarProps = {
  activeScreen: string;
  onNavigate: (screen: string) => void;
  onLogout: () => void;
};

// Barre du haut format téléphone : bouton burger (convention la plus courante : icône
// ☰ en haut à gauche, cf. demande explicite utilisateur 2026-08-11) ouvrant les
// destinations occasionnelles (Recettes, Produits, Profil, Compte, Préférences,
// Jeûne, Poids, Bilan) — les destinations principales vivent dans la barre du bas
// (`AppNavBar` orientation="tabbar") avec le "+", juste au-dessus. Composant à part
// (pas une variante de plus dans `AppNavBar`) car mêmes contraintes de montage que le
// "+" : sur natif, la barre du haut (`header`) et la barre du bas (`tabBar`) sont deux
// render props DISTINCTS de `Tab.Navigator` (RootNavigator.tsx) — deux instances
// séparées ne pourraient pas partager un état `moreOpen` local à `AppNavBar`. Ce
// composant reste donc autonome (son propre state), monté une fois par plateforme.
export function TopMenuBar({ activeScreen, onNavigate, onLogout }: TopMenuBarProps) {
  const [open, setOpen] = useState(false);
  const insets = useSafeAreaInsets();
  const items = TABBAR_SECONDARY_ITEMS.filter((item) => !('webOnly' in item) || Platform.OS === 'web');

  function go(screen: string) {
    setOpen(false);
    onNavigate(screen);
  }

  return (
    <>
      <View
        style={[styles.burgerBar, { paddingTop: insets.top + spacing.sm }]}
        nativeID={isWeb ? 'app-burger-bar' : undefined}
      >
        <Pressable style={styles.burgerButton} onPress={() => setOpen(true)} hitSlop={8}>
          <Ionicons name="menu-outline" size={26} color={colors.text} />
        </Pressable>
        <Text style={styles.wordmark}>
          CLEM <Text style={styles.wordmarkAccent}>AI</Text>
        </Text>
        <View style={styles.burgerButton} />
      </View>

      <Modal visible={open} transparent animationType="fade" onRequestClose={() => setOpen(false)}>
        <Pressable style={styles.drawerOverlay} onPress={() => setOpen(false)}>
          <View style={[styles.drawerPanel, { paddingTop: insets.top + spacing.lg }]}>
            {/* Icône produit (ClemIcon) : le bouton d'ouverture du menu garde son glyphe ☰
                inchangé (demande explicite utilisateur, 2026-08-21) — la marque s'affiche
                ici, en tête du tiroir, comme un en-tête cliquable (retour à "Mon suivi"). */}
            <Pressable style={styles.drawerBrand} onPress={() => go('Tracking')}>
              <View style={styles.burgerLogo}>
                <ClemIcon size={16} />
              </View>
              <Text style={styles.drawerBrandText}>
                CLEM <Text style={styles.wordmarkAccent}>AI</Text>
              </Text>
            </Pressable>
            {items.map((item) => {
              const active = item.screen === activeScreen;
              return (
                <Pressable
                  key={item.screen}
                  style={[styles.drawerItem, active && styles.drawerItemActive]}
                  onPress={() => go(item.screen)}
                >
                  <Ionicons
                    name={item.icon as any}
                    size={19}
                    color={active ? colors.primary : colors.textMuted}
                    style={styles.drawerItemIcon}
                  />
                  <Text style={[styles.drawerItemText, active && styles.drawerItemTextActive]}>{item.label}</Text>
                </Pressable>
              );
            })}
            <Pressable
              style={[styles.drawerItem, styles.drawerLastItem]}
              onPress={() => {
                setOpen(false);
                onLogout();
              }}
            >
              <Text style={[styles.drawerItemText, styles.logoutText]}>Déconnexion</Text>
            </Pressable>
          </View>
        </Pressable>
      </Modal>
    </>
  );
}

function ClemIANavButton({
  active,
  vertical,
  railWeb,
  onPress,
}: {
  active: boolean;
  vertical: boolean;
  railWeb: boolean;
  onPress: () => void;
}) {
  const unreadCount = useDieticianUnreadCount();
  const hasUnread = unreadCount > 0;
  const badgeLabel = unreadCount > 9 ? '9+' : String(unreadCount);
  const iconColor = hasUnread ? UNREAD_COLOR : colors.primary;

  const icon = (
    <View style={styles.clemiaIconWrap}>
      <ClemIcon size={railWeb ? 19 : vertical ? 21 : 22} color={iconColor} />
      {hasUnread && (
        <View style={styles.clemiaBadge}>
          <Text style={styles.clemiaBadgeText}>{badgeLabel}</Text>
        </View>
      )}
    </View>
  );

  if (railWeb) {
    return (
      <Pressable
        style={[styles.railWebItem, active && styles.railWebItemActive, hasUnread && styles.clemiaItemUnreadBg]}
        onPress={onPress}
      >
        {icon}
        <Text style={[styles.railWebLabel, active && styles.railWebLabelActive, hasUnread && { color: UNREAD_COLOR }]} numberOfLines={1}>
          ClemIA
        </Text>
      </Pressable>
    );
  }

  return (
    <Pressable
      style={[vertical ? styles.railItem : styles.tabItem, active && styles.itemActive, hasUnread && styles.clemiaItemUnreadBg]}
      onPress={onPress}
    >
      {icon}
      <Text style={[styles.itemLabel, active && styles.itemLabelActive, hasUnread && { color: UNREAD_COLOR }]} numberOfLines={1}>
        ClemIA
      </Text>
    </Pressable>
  );
}

function NavButton({
  icon,
  label,
  active,
  vertical,
  railWeb,
  onPress,
}: {
  icon: string;
  label: string;
  active: boolean;
  vertical: boolean;
  railWeb: boolean;
  onPress: () => void;
}) {
  if (railWeb) {
    return (
      <Pressable style={[styles.railWebItem, active && styles.railWebItemActive]} onPress={onPress}>
        <Ionicons name={icon as any} size={19} color={active ? colors.primary : colors.textMuted} />
        <Text style={[styles.railWebLabel, active && styles.railWebLabelActive]} numberOfLines={1}>
          {label}
        </Text>
      </Pressable>
    );
  }

  return (
    <Pressable style={[vertical ? styles.railItem : styles.tabItem, active && styles.itemActive]} onPress={onPress}>
      <Ionicons name={icon as any} size={vertical ? 21 : 22} color={active ? colors.primary : colors.textMuted} />
      <Text style={[styles.itemLabel, active && styles.itemLabelActive]} numberOfLines={1}>
        {label}
      </Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  rail: {
    width: 84,
    flexShrink: 0,
    borderRightWidth: 1,
    borderRightColor: colors.border,
    alignItems: 'center',
    paddingVertical: spacing.lg,
    gap: 4,
  },
  railWeb: {
    width: 224,
    flexShrink: 0,
    paddingVertical: spacing.lg,
    paddingHorizontal: spacing.sm + 4,
    gap: 2,
    // Ces pages défilent via la fenêtre (pas un ScrollView interne, voir
    // MealPlanningScreen.tsx) — sans ceci, ce rail (simple sibling flex) défile
    // avec le reste dès que le contenu dépasse un écran (liste "Idées repas" à
    // scroll infini), et menu/logo disparaissent en scrollant. `position`
    // sticky/`vh` absents du type RN ViewStyle, d'où le cast, comme pour
    // `tabbar` ci-dessous.
    ...(isWeb ? ({ position: 'sticky', top: 0, alignSelf: 'flex-start', maxHeight: '100vh', overflowY: 'auto' } as object) : {}),
  },
  railSpacerWeb: { flex: 1 },
  brand: { flexDirection: 'row', alignItems: 'center', gap: 10, paddingHorizontal: 8, paddingTop: 4, paddingBottom: 20 },
  wordmark: { fontSize: 17, fontWeight: '800', color: colors.text },
  wordmarkAccent: { color: colors.primary },
  railWebItem: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 10, paddingHorizontal: 12, borderRadius: 10 },
  railWebItemActive: { backgroundColor: '#eef0fe' },
  railWebLabel: { fontSize: 14.5, fontWeight: '500', color: colors.textMuted },
  railWebLabelActive: { fontWeight: '700', color: colors.primary },
  railDividerWeb: { height: 1, backgroundColor: colors.border, marginVertical: spacing.sm },
  railWebLogout: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 10, paddingHorizontal: 12, borderRadius: 10 },
  railWebLogoutText: { fontSize: 14.5, fontWeight: '600', color: colors.danger },
  railWebAddButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
    backgroundColor: colors.primary,
    borderRadius: 10,
    paddingVertical: 11,
    marginBottom: spacing.md,
  },
  railWebAddButtonText: { fontSize: 14.5, fontWeight: '700', color: '#fff' },
  railAddButton: {
    width: 44,
    height: 44,
    borderRadius: radii.pill,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: spacing.sm,
  },
  railSpacer: { flex: 1 },
  railItem: {
    width: 64,
    alignItems: 'center',
    gap: 4,
    paddingVertical: 10,
    borderRadius: radii.md,
  },
  tabbar: {
    flexDirection: 'row',
    borderTopWidth: 1,
    borderTopColor: colors.border,
    backgroundColor: colors.card,
    paddingHorizontal: 4,
    paddingTop: 6,
    paddingBottom: 6,
    // Sur mobile-web (App.web.tsx), la page HTML défile normalement (pas une
    // vraie fenêtre d'appli à hauteur fixe comme en natif) : sans ceci, cette
    // barre — dernier élément du flex column — se retrouve au bas de tout le
    // contenu au lieu de rester collée au bas du viewport. En natif, le
    // Tab.Navigator gère déjà lui-même le positionnement fixe de sa tabBar,
    // donc ce correctif ne doit s'appliquer qu'au web. `position:'fixed'` est
    // supporté par react-native-web mais absent du type RN `ViewStyle`, d'où
    // le cast.
    ...(Platform.OS === 'web'
      ? ({ position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 50 } as object)
      : {}),
  },
  tabbarSpacer: { width: 0 },
  // Simple conteneur pour ancrer le "+" (position:'absolute') au-dessus de la barre —
  // pas de style propre nécessaire pour rail/railWeb, qui n'affichent pas de "+".
  tabbarWrap: {},
  // Écarte les deux moitiés de la barre (2 onglets + Compte à droite) pour laisser la
  // place au "+" sans chevaucher un libellé — largeur identique au mockup 1b/2a.
  tabbarGap: { width: 64 },
  tabbarFab: {
    // Même correctif fixed/absolute que `tabbar` ci-dessus (mobile-web défile via le
    // document, pas une fenêtre d'appli à hauteur fixe) — voir aussi le même patron
    // déjà posé sur le FAB de TrackingScreen.tsx avant qu'il ne migre ici.
    ...(Platform.OS === 'web' ? ({ position: 'fixed' } as object) : { position: 'absolute' }),
    left: '50%',
    marginLeft: -31,
    width: 62,
    height: 62,
    borderRadius: 31,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    shadowColor: colors.primary,
    shadowOffset: { width: 0, height: 10 },
    shadowOpacity: 0.4,
    shadowRadius: 24,
    elevation: 8,
    zIndex: 60,
  },
  tabItem: {
    flex: 1,
    alignItems: 'center',
    gap: 3,
    paddingVertical: 6,
    borderRadius: radii.md,
  },
  itemActive: { backgroundColor: '#eef0fe' },
  itemLabel: { fontSize: 10.5, fontWeight: '700', color: colors.textMuted },
  itemLabelActive: { color: colors.primary },
  // Fond rose de l'onglet "ClemIA" quand il y a des messages non lus (maquette Claude
  // Design) — remplace `itemActive`/`railWebItemActive` (violet) le temps qu'il y a du
  // nouveau à voir, indépendamment de l'onglet actif.
  clemiaItemUnreadBg: { backgroundColor: UNREAD_BG },
  clemiaIconWrap: { width: 22, height: 22, alignItems: 'center', justifyContent: 'center' },
  clemiaBadge: {
    position: 'absolute',
    top: -6,
    right: -10,
    minWidth: 16,
    height: 16,
    paddingHorizontal: 3,
    borderRadius: radii.pill,
    backgroundColor: UNREAD_COLOR,
    borderWidth: 2,
    borderColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  clemiaBadgeText: { fontSize: 9, fontWeight: '700', color: '#fff' },
  overlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.3)', justifyContent: 'flex-end', alignItems: 'flex-end' },
  panel: {
    margin: spacing.lg,
    marginBottom: 96,
    backgroundColor: colors.card,
    borderRadius: radii.lg,
    overflow: 'hidden',
    minWidth: 240,
  },
  panelItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  panelLastItem: { borderBottomWidth: 0 },
  panelItemIcon: { width: 18 },
  panelItemText: { ...typography.body, color: colors.text },
  logoutText: { color: colors.danger },
  burgerBar: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: spacing.sm,
    paddingBottom: spacing.sm,
    backgroundColor: colors.card,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
    // Même patron que railWeb/AppHeader.tsx : sur mobile-web (App.web.tsx), la page
    // défile via la fenêtre (pas de ScrollView interne bornée) — sans ce `sticky`, ce
    // bandeau défilerait avec le reste. `as object` pour contourner le typage RN
    // ViewStyle (n'admet pas 'sticky', propre à react-native-web).
    ...(isWeb ? ({ position: 'sticky', top: 0, zIndex: 40 } as object) : {}),
  },
  burgerButton: { width: 36, height: 36, alignItems: 'center', justifyContent: 'center' },
  burgerLogo: { width: 28, height: 28, borderRadius: radii.sm, backgroundColor: colors.primary, alignItems: 'center', justifyContent: 'center' },
  drawerOverlay: { flex: 1, flexDirection: 'row', backgroundColor: 'rgba(0,0,0,0.3)' },
  drawerPanel: {
    width: 272,
    maxWidth: '80%',
    backgroundColor: colors.card,
    paddingHorizontal: spacing.sm,
    paddingBottom: spacing.lg,
  },
  // En-tête de marque en tête du tiroir (icône produit ClemIcon), au-dessus des
  // destinations occasionnelles — bordure plus marquée que `drawerItem` pour le
  // distinguer visuellement du reste de la liste.
  drawerBrand: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  drawerBrandText: { fontSize: 16, fontWeight: '800', color: colors.text },
  drawerItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
    borderRadius: radii.md,
  },
  drawerItemActive: { backgroundColor: '#eef0fe' },
  drawerItemIcon: { width: 20 },
  drawerLastItem: { borderBottomWidth: 0 },
  drawerItemText: { ...typography.body, color: colors.text },
  drawerItemTextActive: { color: colors.primary, fontWeight: '700' },
});
