/* ============================================================
   APP · raíz (público + admin) y navegación
   ============================================================ */

function TopBar({ brand, cartas, activeCarta, onCarta, onHome, onInfo, onReserve }) {
  const [open, setOpen] = useState(false);
  const pick = (fn) => { fn(); setOpen(false); window.scrollTo({top:0}); };
  return (
    <header className="topbar" style={accentVars(activeCarta||'restaurante')}>
      <div className="topbar-inner">
        <div className="brandmark" onClick={onHome}>
          <Seal brand={brand} />
          <div><div className="bn">{brand.name}</div><div className="bt">{brand.tagline}</div></div>
        </div>
        <nav className="tabs">
          {cartas.map(c => (
            <button key={c.id} className={'tab'+(activeCarta===c.id?' active':'')} onClick={()=>onCarta(c.id)} style={activeCarta===c.id?accentVars(c.id):null}>
              <span className="dot" style={{background:activeCarta===c.id?'rgba(255,255,255,.7)':themeFor(c.id).accent}}/>{c.name}
            </button>
          ))}
        </nav>
        <div className="spacer" />
        <div className="topbar-actions">
          <button className="btn ghost sm" onClick={onInfo}><Icon name="info" size={16}/><span className="lbl">Info</span></button>
          {brand.reservationsOn && <button className="btn sm" onClick={onReserve}><Icon name="calendar" size={16}/><span className="lbl">Reservar</span></button>}
        </div>
        <button className="menu-btn" aria-label="Menú" onClick={()=>setOpen(o=>!o)}><Icon name={open?'x':'menu'} size={22}/></button>
      </div>

      {open && (
        <>
          <div className="drawer-scrim" onClick={()=>setOpen(false)} />
          <div className="mobile-drawer" style={accentVars(activeCarta||'restaurante')}>
            <div className="md-label">Cartas</div>
            <button className={'md-item'+(activeCarta===null?' active':'')} onClick={()=>pick(onHome)}><Icon name="home" size={18}/> Inicio</button>
            {cartas.map(c => (
              <button key={c.id} className={'md-item'+(activeCarta===c.id?' active':'')} onClick={()=>pick(()=>onCarta(c.id))}>
                <Icon name={themeFor(c.id).icon} size={18}/> {c.name}
              </button>
            ))}
            <div className="md-sep" />
            <button className="md-item" onClick={()=>pick(onInfo)}><Icon name="info" size={18}/> Información & contacto</button>
            {brand.reservationsOn && <button className="md-item cta" onClick={()=>pick(onReserve)}><Icon name="calendar" size={18}/> Reservar mesa</button>}
          </div>
        </>
      )}
    </header>
  );
}

function PublicShell({ onAdmin }) {
  const { data } = useStore();
  const { brand, cartas } = data;
  const [cartaId, setCartaId] = useState(null); // null = portada
  const [info, setInfo] = useState(false);
  const [reserva, setReserva] = useState(false);
  const [legal, setLegal] = useState(null);
  const carta = cartas.find(c => c.id === cartaId);

  return (
    <div>
      <TopBar brand={brand} cartas={cartas} activeCarta={cartaId}
        onCarta={(id)=>{setCartaId(id);window.scrollTo({top:0});}}
        onHome={()=>{setCartaId(null);window.scrollTo({top:0});}}
        onInfo={()=>setInfo(true)} onReserve={()=>setReserva(true)} />

      {carta ? <CartaView carta={carta} /> : <Portada brand={brand} cartas={cartas} onOpen={(id)=>{setCartaId(id);window.scrollTo({top:0});}} />}

      <footer style={{borderTop:'1px solid var(--line)',marginTop:carta?0:0,padding:'26px 22px 60px',textAlign:'center'}}>
        <div style={{display:'flex',gap:'10px 22px',justifyContent:'center',flexWrap:'wrap',marginBottom:14}}>
          <button onClick={()=>setLegal('privacidad')} style={{fontSize:13,color:'var(--ink-soft)',fontWeight:500}}>Política de Privacidad</button>
          <button onClick={()=>setLegal('terminos')} style={{fontSize:13,color:'var(--ink-soft)',fontWeight:500}}>Términos y Condiciones</button>
          <button onClick={()=>setLegal('ley17336')} style={{fontSize:13,color:'var(--ink-soft)',fontWeight:500}}>Protección Ley 17.336</button>
        </div>
        <div style={{color:'var(--ink-faint)',fontSize:12.5}}>{brand.website} · 2007 - 2026 · 19 años en Chile</div>
      </footer>

      {info && <InfoModal brand={brand} onClose={()=>setInfo(false)} onReserve={()=>{setInfo(false);setReserva(true);}} />}
      {reserva && <ReservaModal brand={brand} cartas={cartas} onClose={()=>setReserva(false)} />}
      {legal && <LegalModal docKey={legal} brand={brand} onClose={()=>setLegal(null)} />}

      <button className="fab-admin" title="Administración" onClick={onAdmin}><Icon name="lock" size={18}/></button>
    </div>
  );
}

function AdminShell({ onExit }) {
  const store = useStore();
  const newRsv = (store.data.reservations||[]).filter(r=>r.status==='nueva').length;
  const ALLNAV = [
    {k:'contenido', l:'Contenido', icon:'book'},
    {k:'reservas', l:'Reservas', icon:'calendar', badge:newRsv},
    {k:'dashboard', l:'Dashboard', icon:'chart'},
    {k:'usuarios', l:'Usuarios', icon:'users'},
    {k:'restaurante', l:'Restaurante', icon:'gear'},
  ];
  const NAV = ALLNAV.filter(n => store.can(n.k));
  const [view, setView] = useState(NAV[0]?.k || 'contenido');
  const roleLabel = store.currentUser ? (store.ROLES[store.currentUser.role]||{}).label : '';
  return (
    <div className="admin">
      <div className="admin-top">
        <div className="admin-top-inner">
          <div className="at-brand"><Seal brand={store.data.brand} size={30}/> <span className="at-name">{store.data.brand.name}</span> <span className="pill">Admin</span></div>
          <nav className="admin-nav">
            {NAV.map(n=>(
              <button key={n.k} className={view===n.k?'active':''} onClick={()=>setView(n.k)}>
                <Icon name={n.icon} size={16}/><span className="lbl">{n.l}</span>
                {n.badge>0 && <span className="navbadge">{n.badge}</span>}
              </button>
            ))}
          </nav>
          <div className="spacer" style={{flex:1}}/>
          <div className="at-meta">
            <span className="at-sync" title={store.online===true?'Conectado al servidor':'Modo local'}>
              {store.syncing ? <><Icon name="reset" size={13}/> Guardando…</> : (store.online===true ? '● En línea' : '○ Local')}
            </span>
            <span className="at-user"><b>{store.currentUser?.name}</b><span>{roleLabel}</span></span>
          </div>
          <div className="at-actions">
            <button className="btn sm" title="Publicar cambios al servidor" onClick={store.publish}><Icon name="upload" size={15}/><span className="lbl">Publicar</span></button>
            <button className="iconbtn at-ico" title="Actualizar desde el servidor" onClick={store.refreshFromServer}><Icon name="download" size={18}/></button>
            <button className="iconbtn at-ico" title="Deshacer último cambio" onClick={store.undo}><Icon name="reset" size={18}/></button>
            <button className="iconbtn at-ico" title="Ver carta pública" onClick={onExit}><Icon name="eye" size={18}/></button>
            <button className="iconbtn at-ico" title="Cerrar sesión" onClick={()=>{store.logout();onExit();}}><Icon name="logout" size={18}/></button>
          </div>
        </div>
      </div>
      <div className="admin-body">
        {view==='contenido' && store.can('contenido') && <ContentEditor/>}
        {view==='reservas' && store.can('reservas') && <ReservationsView/>}
        {view==='dashboard' && store.can('dashboard') && <Dashboard/>}
        {view==='usuarios' && store.can('usuarios') && <UsersView/>}
        {view==='restaurante' && store.can('restaurante') && <BrandEditor/>}
      </div>
    </div>
  );
}

function App() {
  const store = useStore();
  const [mode, setMode] = useState('public'); // public | login | admin

  if (store.admin && mode !== 'public') return <AdminShell onExit={()=>setMode('public')} />;
  if (mode === 'login') return <LoginScreen onCancel={()=>setMode('public')} />;
  return <PublicShell onAdmin={()=> setMode(store.admin ? 'admin' : 'login')} />;
}

function Root() {
  return (
    <StoreProvider>
      <App />
    </StoreProvider>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<Root />);
