/* RINAU HEX — App composition + contexts */
/* Exposes window.useApp() with { lang, setLang, theme, toggleTheme, cart, addItem, removeItem, clearCart } */

const { useState: useStateA, useEffect: useEffectA, createContext, useContext } = React;

/* --- Single combined context --- */
const AppCtx = createContext(null);
window.useApp = () => useContext(AppCtx);

function AppProvider({ children }) {
  // Lang
  const [lang, setLang] = useStateA(() => {
    try { return localStorage.getItem('rhx-lang') || 'es'; } catch(e) { return 'es'; }
  });
  useEffectA(() => { try { localStorage.setItem('rhx-lang', lang); } catch(e){} }, [lang]);

  // Theme
  const [theme, setTheme] = useStateA(() => {
    try { return localStorage.getItem('rhx-theme') || 'dark'; } catch(e) { return 'dark'; }
  });
  useEffectA(() => {
    const root = document.documentElement;
    if (theme === 'dark') root.classList.add('dark');
    else root.classList.remove('dark');
    try { localStorage.setItem('rhx-theme', theme); } catch(e){}
  }, [theme]);
  const toggleTheme = () => setTheme(t => t==='dark'?'light':'dark');

  // Cart
  const [cart, setCart] = useStateA(() => {
    try { return JSON.parse(localStorage.getItem('rhx-cart') || '[]'); } catch(e) { return []; }
  });
  useEffectA(() => { try { localStorage.setItem('rhx-cart', JSON.stringify(cart)); } catch(e){} }, [cart]);
  const addItem = (id) => setCart(c => c.includes(id) ? c : [...c, id]);
  const removeItem = (id) => setCart(c => c.filter(x => x !== id));
  const clearCart = () => setCart([]);

  return (
    <AppCtx.Provider value={{ lang, setLang, theme, toggleTheme, cart, addItem, removeItem, clearCart }}>
      {children}
    </AppCtx.Provider>
  );
}

function Shell() {
  const { cart } = window.useApp();
  const [cartOpen, setCartOpen] = useStateA(false);

  return (
    <div className="min-h-screen bg-white dark:bg-[#06090F] text-gray-900 dark:text-gray-100 transition-colors font-sans antialiased">
      <window.TopBar/>
      <window.Header onQuote={()=>setCartOpen(true)} cartCount={cart.length}/>
      <main>
        <window.Hero onQuote={()=>setCartOpen(true)}/>
        <window.Features/>
        <window.About/>
        <window.SectorExplorer/>
        <window.Portfolio/>
        <window.Team/>
        <window.Partners/>
        <window.Contact/>
      </main>
      <window.Footer/>
      <window.FloatingQuote onClick={()=>setCartOpen(true)} count={cart.length}/>
      <window.CartModal open={cartOpen} onClose={()=>setCartOpen(false)}/>
      <window.LoginModal/>
      <window.AdminPanel/>
      <window.CommandPalette/>
    </div>
  );
}

function App() {
  return (
    <AppProvider>
      <window.AdminProvider>
        <Shell/>
      </window.AdminProvider>
    </AppProvider>
  );
}

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