// Bellia — Shell : Sidebar + Header globaux

const MODULES = [
  { id: 'dashboard', label: 'Tableau de bord', icon: 'dashboard' },
  { id: 'ventes',    label: 'Ventes',          icon: 'bag' },
  { id: 'depenses',  label: 'Dépenses',        icon: 'receipt' },
  { id: 'rh',        label: 'Ressources humaines', icon: 'users' },
  { id: 'achats',    label: 'Achats',          icon: 'package' },
  { id: 'ref',       label: 'Référentiel',     icon: 'book' },
  { id: 'analyse',   label: 'Analyse',         icon: 'chart' },
  { id: 'admin',     label: 'Administration',  icon: 'shield' },
  { id: 'automation',label: 'Automatisation',  icon: 'zap' },
  { id: 'simulateur',label: 'Simulateur',      icon: 'calc' },
];

const RESTAURANTS = [
  { id: 'rep', name: 'Cantine Corner — République', initials: 'CR', city: 'Paris 11e' },
  { id: 'bat', name: 'Cantine Corner — Bastille',   initials: 'CB', city: 'Paris 12e' },
  { id: 'mtg', name: 'Cantine Corner — Montrouge',  initials: 'CM', city: 'Hauts-de-Seine' },
];

const RestoSwitcher = ({ onOpenSettings }) => {
  const [open, setOpen] = React.useState(false);
  const [sel, setSel] = React.useState(() => {
    try { const s = JSON.parse(localStorage.getItem('bellia-restos') || 'null'); return s || ['rep']; } catch { return ['rep']; }
  });
  const ref = React.useRef(null);
  React.useEffect(() => {
    try { localStorage.setItem('bellia-restos', JSON.stringify(sel)); } catch {}
  }, [sel]);
  React.useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);

  const toggle = (id) => setSel(s => s.includes(id) ? (s.length > 1 ? s.filter(x => x !== id) : s) : [...s, id]);
  const all = () => setSel(RESTAURANTS.map(r => r.id));

  const label = sel.length === RESTAURANTS.length ? 'Tous les restaurants' :
                sel.length === 1 ? RESTAURANTS.find(r => r.id === sel[0])?.name.replace('Cantine Corner — ', '') :
                `${sel.length} restaurants sélectionnés`;
  const initials = sel.length === RESTAURANTS.length ? 'CC' : sel.length === 1 ? RESTAURANTS.find(r => r.id === sel[0]).initials : `${sel.length}`;

  return (
    <div ref={ref} style={{ position: 'relative', marginBottom: 14 }}>
      <button onClick={() => setOpen(o => !o)} style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 14,
        background: open ? C.orangeWh : C.card, border: `1px solid ${open ? C.orangeSft : C.line}`, cursor: 'pointer', width: '100%', textAlign: 'left',
        fontFamily: 'inherit',
      }}>
        <Avatar initials={initials} size={28} c={sel.length === RESTAURANTS.length ? C.orange : C.orangeDp} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: C.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</div>
          <div style={{ fontSize: 10, color: C.mute }}>{sel.length === RESTAURANTS.length ? 'consolidé' : `sur ${RESTAURANTS.length} restaurants`}</div>
        </div>
        <Icon name="chevDown" size={14} color={C.mute} style={{ transition: 'transform .15s ease', transform: open ? 'rotate(180deg)' : 'none' }} />
      </button>

      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 6px)', left: 0, right: 0, zIndex: 60,
          background: C.card, border: `1px solid ${C.line}`, borderRadius: 18,
          boxShadow: '0 18px 36px -20px rgba(36,27,18,0.28)', overflow: 'hidden',
          minWidth: 280,
        }}>
          <div style={{ padding: '12px 14px', borderBottom: `1px solid ${C.lineSoft}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 10, color: C.mute, fontWeight: 700, letterSpacing: 0.6 }}>SÉLECTION MULTI</span>
            <button onClick={all} style={{ background: 'transparent', border: 'none', color: C.orangeDp, fontWeight: 600, fontSize: 11, cursor: 'pointer', fontFamily: 'inherit', padding: 0 }}>Tout sélectionner</button>
          </div>
          <div style={{ padding: 6 }}>
            {RESTAURANTS.map(r => {
              const checked = sel.includes(r.id);
              return (
                <button key={r.id} onClick={() => toggle(r.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 11,
                  background: checked ? C.cardWash : 'transparent', border: 'none', cursor: 'pointer',
                  fontFamily: 'inherit', textAlign: 'left', width: '100%',
                }}>
                  <span style={{
                    width: 18, height: 18, borderRadius: 6, border: `1.5px solid ${checked ? C.orange : C.line}`,
                    background: checked ? C.orange : C.card, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>{checked && <Icon name="check" size={11} color="#fff" stroke={3} />}</span>
                  <Avatar initials={r.initials} size={24} c={C.orangeDp} style={{ fontSize: 10 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, color: C.ink, fontWeight: 600 }}>{r.name.replace('Cantine Corner — ', '')}</div>
                    <div style={{ fontSize: 10, color: C.mute }}>{r.city}</div>
                  </div>
                </button>
              );
            })}
          </div>
          <div style={{ padding: 8, borderTop: `1px solid ${C.lineSoft}`, background: C.cardWash }}>
            <button onClick={() => { onOpenSettings?.(); setOpen(false); }} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 10,
              background: 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
              width: '100%', textAlign: 'left', fontSize: 12, color: C.ink2, fontWeight: 600,
            }}>
              <Icon name="settings" size={14} color={C.mute} />
              <span style={{ flex: 1 }}>Gérer les restaurants</span>
              <Icon name="arrowR" size={12} color={C.mute} />
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

const Sidebar = ({ current, onNav }) => (
  <aside style={{ width: 232, padding: 20, display: 'flex', flexDirection: 'column', gap: 4, flexShrink: 0 }}>
    <div style={{ padding: '4px 10px 22px' }}><Logo size={28} /></div>

    <RestoSwitcher onOpenSettings={() => onNav('restaurants')} />

    {MODULES.map(m => {
      const active = current === m.id;
      return (
        <button key={m.id} onClick={() => onNav(m.id)} style={{
          display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 12,
          background: active ? C.orangeWh : 'transparent', color: active ? C.orangeDp : C.ink2,
          border: 'none', cursor: 'pointer', fontFamily: 'inherit', width: '100%', textAlign: 'left',
          fontSize: 13, fontWeight: active ? 600 : 500, letterSpacing: -0.1,
          transition: 'background .12s ease',
        }}
        onMouseEnter={e => !active && (e.currentTarget.style.background = C.cardWash)}
        onMouseLeave={e => !active && (e.currentTarget.style.background = 'transparent')}
        >
          <Icon name={m.icon} size={17} color={active ? C.orangeDp : C.mute} stroke={1.8} />
          <span>{m.label}</span>
        </button>
      );
    })}

    <div style={{ marginTop: 'auto', paddingTop: 12, borderTop: `1px solid ${C.line}` }}>
      <button onClick={() => onNav('restaurants')} style={{
        display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 12,
        background: current === 'restaurants' ? C.orangeWh : 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
        width: '100%', textAlign: 'left', fontSize: 13, fontWeight: current === 'restaurants' ? 600 : 500, color: current === 'restaurants' ? C.orangeDp : C.ink2,
      }}>
        <Icon name="settings" size={17} color={current === 'restaurants' ? C.orangeDp : C.mute} />
        <span>Paramètres</span>
      </button>
    </div>
  </aside>
);

const Header = ({ title, subtitle, right }) => {
  const [narrow, setNarrow] = React.useState(false);
  React.useEffect(() => {
    const check = () => setNarrow(window.innerWidth < 1180);
    check();
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);
  return (
    <header style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 18, flex: '1 1 320px', minWidth: 0 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: C.ink, margin: 0, letterSpacing: -0.6, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</h1>
          {subtitle && <div style={{ fontSize: 12, color: C.mute, marginTop: 4, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{subtitle}</div>}
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
        {narrow ? (
          <button aria-label="Rechercher" style={{
            width: 38, height: 38, borderRadius: 999, background: C.card, border: `1px solid ${C.line}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}>
            <Icon name="search" size={15} color={C.ink2} />
          </button>
        ) : (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8, padding: '0 14px', height: 38,
            background: C.card, border: `1px solid ${C.line}`, borderRadius: 999, width: 200,
          }}>
            <Icon name="search" size={15} color={C.mute} />
            <input placeholder="Rechercher…" style={{
              background: 'transparent', border: 'none', outline: 'none', fontSize: 12, color: C.ink,
              fontFamily: 'inherit', flex: 1, padding: 0, minWidth: 0,
            }} />
            <kbd style={{ fontSize: 10, color: C.mute, background: C.cardSoft, padding: '2px 6px', borderRadius: 6, fontFamily: 'inherit' }}>⌘K</kbd>
          </div>
        )}
        {right}
        <button aria-label="Notifications" style={{
          position: 'relative', width: 38, height: 38, borderRadius: 999, background: C.card, border: `1px solid ${C.line}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}>
          <Icon name="bell" size={16} color={C.ink2} />
          <span style={{ position: 'absolute', top: 8, right: 9, width: 8, height: 8, borderRadius: 999, background: C.orange, border: `2px solid ${C.card}` }} />
        </button>
        <Avatar initials="YB" size={38} />
      </div>
    </header>
  );
};

const PeriodPicker = ({ value = 'mois', onChange = () => {} }) => {
  const items = [{ id: 'jour', l: 'Jour' }, { id: 'sem', l: 'Semaine' }, { id: 'mois', l: 'Mois' }, { id: 'an', l: 'Année' }];
  return (
    <div style={{ display: 'inline-flex', padding: 4, background: C.card, border: `1px solid ${C.line}`, borderRadius: 999, gap: 2 }}>
      {items.map(i => {
        const active = value === i.id;
        return (
          <button key={i.id} onClick={() => onChange(i.id)} style={{
            padding: '7px 14px', borderRadius: 999, background: active ? C.orange : 'transparent',
            color: active ? '#fff' : C.ink2, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
            fontSize: 12, fontWeight: 600,
          }}>{i.l}</button>
        );
      })}
      <button style={{
        padding: '7px 14px', borderRadius: 999, background: 'transparent', color: C.mute,
        border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 600,
        display: 'inline-flex', alignItems: 'center', gap: 4,
      }}>
        <Icon name="cal" size={13} /> Personnalisé
      </button>
    </div>
  );
};

const PageShell = ({ current, onNav, children }) => (
  <div style={{ minHeight: '100vh', background: C.bg, display: 'flex', fontFamily: 'Inter, sans-serif' }}>
    <Sidebar current={current} onNav={onNav} />
    <main style={{ flex: 1, padding: '20px 24px 24px 4px', minWidth: 0 }}>
      <div style={{ background: C.card, border: `1px solid ${C.line}`, borderRadius: 28, padding: 28, minHeight: 'calc(100vh - 40px)' }}>
        {children}
      </div>
    </main>
  </div>
);

Object.assign(window, { Sidebar, Header, PeriodPicker, PageShell, MODULES, RESTAURANTS });
