// App for Propuesta 1
const { useState, useEffect } = React;

const SCREEN_COMPONENTS = {
  home:     window.HomeScreen,
  shop:     window.ShopScreen,
  product:  window.ProductScreen,
  cart:     window.CartScreen,
  checkout: window.CheckoutScreen,
  auth:     window.AuthScreen,
  tech:     window.TechScreen,
};

const App = () => {
  const initial = (window.location.hash || '#home').slice(1);
  const [screen, setScreen] = useState(SCREEN_COMPONENTS[initial] ? initial : 'home');

  const onNav = (id) => {
    setScreen(id);
    window.location.hash = id;
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  useEffect(() => {
    const onHash = () => {
      const id = (window.location.hash || '#home').slice(1);
      if (SCREEN_COMPONENTS[id]) setScreen(id);
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // Render tabs in chrome
  useEffect(() => {
    const host = document.getElementById('tabs');
    if (!host) return;
    host.innerHTML = SCREENS.map(s =>
      `<button class="tab ${s.id===screen?'active':''}" data-id="${s.id}"><span class="num">${s.num}</span>${s.label}</button>`
    ).join('');
    host.querySelectorAll('button').forEach(b => {
      b.onclick = () => onNav(b.dataset.id);
    });
  }, [screen]);

  const Component = SCREEN_COMPONENTS[screen];
  return (
    <div className="site" data-screen-label={`PROPUESTA1 / ${screen.toUpperCase()}`}>
      <Component onNav={onNav}/>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('screen-host')).render(<App/>);
