// =====================================================================
// SOMOS SETAS — App Router
// =====================================================================

function App() {
  const store = useStore();
  const route = useHashRoute();
  const [cartOpen, setCartOpen] = useState(false);
  const [waOpen, setWaOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [toast, setToast] = useState(null);
  const [cartSummary, setCartSummary] = useState(null);

  // Scroll to top on route change
  useEffect(() => { window.scrollTo({ top: 0, behavior: "instant" }); }, [route.raw]);

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 2200);
  };

  const handleQuickAdd = (product) => {
    const pres = product.presentations[0];
    store.addToCart(product, pres.id, 1);
    showToast(`${product.name} agregado al carrito`);
  };

  const handleCheckout = (summary) => {
    setCartSummary(summary);
    setCartOpen(false);
    setWaOpen(true);
  };

  // ---------- Route resolution ----------
  const parts = route.parts;
  const root = parts[0] || "home";

  // ===== LOADING =====
  if (store.dbLoading) {
    return (
      <div style={{minHeight: "100vh", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 18, background: "var(--bg)"}}>
        <img src="assets/logo-vertical.png" alt="Somos Setas" style={{height: 90, opacity: 0.7}}/>
        <div style={{width: 36, height: 36, border: "3px solid var(--line-2)", borderTopColor: "var(--primary)", borderRadius: "50%", animation: "spin 0.8s linear infinite"}}></div>
      </div>
    );
  }

  // ===== ADMIN ROUTES =====
  if (root === "admin") {
    if (!store.auth) return <AdminLogin/>;
    const section = parts[1] || "dashboard";
    return <AdminShell store={store} section={section}/>;
  }

  // ===== STOREFRONT ROUTES =====
  let page;
  let currentRoute = "home";
  if (root === "home" || !root) {
    page = <HomePage store={store} onQuickAdd={handleQuickAdd}/>;
    currentRoute = "home";
  } else if (root === "catalogo") {
    page = <CatalogPage store={store} onQuickAdd={handleQuickAdd} slug={parts[1]}/>;
    currentRoute = "catalogo";
  } else if (root === "producto") {
    page = <ProductDetailPage store={store} productId={parts[1]}/>;
    currentRoute = "catalogo";
  } else if (root === "filosofia") {
    page = <HomePage store={store} onQuickAdd={handleQuickAdd}/>;
    // anchor scroll
    setTimeout(() => {
      const el = document.getElementById("filosofia");
      if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
    }, 60);
    currentRoute = "home";
  } else if (root === "como-comprar") {
    page = <HomePage store={store} onQuickAdd={handleQuickAdd}/>;
    setTimeout(() => {
      const el = document.getElementById("como-comprar");
      if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
    }, 60);
    currentRoute = "home";
  } else {
    page = <HomePage store={store} onQuickAdd={handleQuickAdd}/>;
  }

  return (
    <React.Fragment>
      <Header store={store} currentRoute={currentRoute} onCartOpen={() => setCartOpen(true)} onSearchOpen={() => setSearchOpen(true)}/>
      {page}
      <Footer store={store}/>
      <CartDrawer open={cartOpen} store={store} onClose={() => setCartOpen(false)} onCheckout={handleCheckout}/>
      <WhatsAppCheckout open={waOpen} store={store} onClose={() => setWaOpen(false)} cartSummary={cartSummary}/>
      <SearchModal open={searchOpen} store={store} onClose={() => setSearchOpen(false)}/>
      {/* Botón flotante de WhatsApp */}
      <a
        href={`https://wa.me/${store.config.whatsapp}`}
        target="_blank"
        rel="noopener"
        aria-label="Contactar por WhatsApp"
        className={"wa-fab" + (cartOpen || waOpen || searchOpen ? " is-hidden" : "")}
      >
        <img src="assets/whatsapp-logo.png" alt="WhatsApp" className="wa-fab-icon"/>
        <span className="wa-fab-label">Chateá con un Representante</span>
      </a>
      <div className={"toast" + (toast ? " is-visible" : "")}>
        <span className="dot-ok"></span>
        {toast}
      </div>
    </React.Fragment>
  );
}

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