
// ── App Shell Responsive ──────────────────────────────────────────────────────
const { useState: useStateShell, useEffect: useEffectShell } = React;

const TABS = [
  { id: 0, label: 'Inicio',    icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M3 9.5L12 3l9 6.5V20a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V9.5z" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"/><path d="M9 21V12h6v9" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"/></svg> },
  { id: 1, label: 'Comidas',   icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M3 6h2l2 9h10l2-9h2" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/><circle cx="9" cy="20" r="1.5" fill="currentColor"/><circle cx="17" cy="20" r="1.5" fill="currentColor"/></svg> },
  { id: 2, label: 'Menú',      icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><rect x="4" y="3" width="16" height="18" rx="2" stroke="currentColor" strokeWidth="1.8"/><path d="M8 8h8M8 12h8M8 16h5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg> },
  { id: 3, label: 'Progreso',  icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M3 17l4-4 4 4 4-6 4 2" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg> },
  { id: 4, label: 'Entrenos',  icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M6 12h12M9 8l-3 4 3 4M15 8l3 4-3 4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg> },
  { id: 5, label: 'Biblioteca',icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M4 6h16M4 10h16M4 14h10" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg> },
  { id: 6, label: 'Historial', icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><rect x="3" y="4" width="18" height="18" rx="2" stroke="currentColor" strokeWidth="1.8"/><path d="M8 2v4M16 2v4M3 10h18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg> },
  { id: 7, label: 'Ajustes',   icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="1.8"/><path d="M12 2v2M12 20v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M2 12h2M20 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg> },
];

// Solo 5 tabs en bottom nav móvil
const MOBILE_TABS = [0, 1, 2, 3, 7];

function Sidebar({ active, onSelect, username, onLogout }) {
  return (
    <aside className="sidebar">
      <div className="sidebar-logo">
        <div className="sidebar-logo-icon">🥗</div>
        <div>
          <div className="sidebar-logo-text">Salud</div>
          <div className="sidebar-logo-sub">rubenfer.es</div>
        </div>
      </div>
      {TABS.map(t => (
        <button key={t.id} className={`nav-item${active === t.id ? ' active' : ''}`} onClick={() => onSelect(t.id)}>
          {t.icon} {t.label}
        </button>
      ))}
      <div className="sidebar-bottom">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 8px', borderTop: '1px solid #F2F2F7', marginTop: 8 }}>
          <div className="avatar" style={{ width: 32, height: 32, fontSize: 13 }}>{(username||'R').charAt(0).toUpperCase()}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#1C1C1E', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{username || 'ruben'}</div>
          </div>
          <button onClick={onLogout} style={{ background: 'none', border: 'none', color: '#8E8E93', fontSize: 13, cursor: 'pointer', padding: '4px 6px' }} title="Cerrar sesión">⬡</button>
        </div>
      </div>
    </aside>
  );
}

function TopBar({ active }) {
  const tab = TABS.find(t => t.id === active);
  return (
    <header className="topbar">
      <div className="topbar-logo">
        <div className="topbar-logo-icon">🥗</div>
        <span style={{ fontWeight: 700, fontSize: 16 }}>Salud</span>
      </div>
      <div style={{ fontWeight: 600, fontSize: 15, color: '#1C1C1E' }}>{tab?.label}</div>
      <div style={{ width: 60 }} />
    </header>
  );
}

function BottomNav({ active, onSelect }) {
  return (
    <nav className="bottom-nav">
      <div className="bottom-nav-inner">
        {MOBILE_TABS.map(id => {
          const t = TABS.find(x => x.id === id);
          return (
            <button key={id} className={`bottom-nav-item${active === id ? ' active' : ''}`} onClick={() => onSelect(id)}>
              {t.icon}
              <span>{t.label}</span>
            </button>
          );
        })}
      </div>
    </nav>
  );
}

function LoadingScreen() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: 16, background: '#F5F5F0' }}>
      <div style={{ width: 64, height: 64, borderRadius: 18, background: 'linear-gradient(145deg,#FF6B35,#FF3B30)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 32 }}>🥗</div>
      <div style={{ fontSize: 16, color: '#8E8E93' }}>Cargando…</div>
    </div>
  );
}

function AppContent({ username, onLogout }) {
  const [tab, setTab] = useStateShell(0);
  const { state, loadMealsForDate } = useSalud();
  const today = new Date().toISOString().split('T')[0];

  useEffectShell(() => {
    if (tab === 0 || tab === 1) loadMealsForDate(today);
  }, [tab]);

  if (state.loading) return <LoadingScreen />;

  const screens = {
    0: <ScreenDashboard onNavigate={setTab} />,
    1: <ScreenFoodLog />,
    2: <ScreenMenu />,
    3: <ScreenProgress />,
    4: <ScreenWorkouts />,
    5: <ScreenLibrary />,
    6: <ScreenHistory />,
    7: <ScreenSettings onLogout={onLogout} username={username} />,
  };

  return (
    <div className="app-layout">
      <Sidebar active={tab} onSelect={setTab} username={username} onLogout={onLogout} />
      <TopBar active={tab} />
      <main className="main-content">
        {screens[tab]}
      </main>
      <BottomNav active={tab} onSelect={setTab} />
    </div>
  );
}

function AppShell() {
  const [username, setUsername] = useStateShell(() => {
    const token = api.getToken();
    return token ? localStorage.getItem('salud_username') || null : null;
  });

  useEffectShell(() => {
    const handler = () => { setUsername(null); };
    window.addEventListener('salud:logout', handler);
    return () => window.removeEventListener('salud:logout', handler);
  }, []);

  const handleLogin = (user) => {
    localStorage.setItem('salud_username', user);
    setUsername(user);
  };

  const handleLogout = () => {
    api.clearToken();
    localStorage.removeItem('salud_username');
    setUsername(null);
  };

  if (!username) return <ScreenLogin onLogin={handleLogin} />;

  return (
    <SaludProvider>
      <AppContent username={username} onLogout={handleLogout} />
    </SaludProvider>
  );
}

Object.assign(window, { AppShell });
