// LC4lab — Main app
const { useState: uS, useEffect: uE, useRef: uR } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#22d3ee",
  "accent2": "#8b5cf6",
  "theme": "dark",
  "heroStyle": "showcase",
  "fontHead": "Space Grotesk"
}/*EDITMODE-END*/;

function App() {
  const [route, setRoute] = uS({ page: "home" });
  const [cart, setCart] = uS([]);
  const [cartOpen, setCartOpen] = uS(false);
  const [modal, setModal] = uS(null);
  const [toasts, setToasts] = uS([]);
  const [search, setSearch] = uS("");
  const [theme, setTheme] = uS("dark");
  const brandsRef = uR(null);
  const combosRef = uR(null);

  uE(() => {
    document.body.classList.toggle("theme-light", theme === "light");
    // Broadcast theme to all iframes (sub-pages)
    document.querySelectorAll("iframe").forEach(f => {
      try { f.contentWindow && f.contentWindow.postMessage({type: "lc4-theme", theme}, "*"); } catch(_) {}
    });
  }, [theme]);

  uE(() => {
    function onMsg(e) {
      if (e.data && e.data.type === "lc4-iframe-ready") {
        try { e.source && e.source.postMessage({type: "lc4-theme", theme}, "*"); } catch(_) {}
      }
      if (e.data && e.data.type === "lc4-navigate") {
        const r = e.data.route;
        if (r === "home") setRoute({page: "home"});
        else if (r === "sobre") setRoute({page: "produto", id: "sobre"});
        else if (r === "blog") setRoute({page: "produto", id: "blog"});
        else if (r === "privacidade") setRoute({page: "produto", id: "privacidade"});
        else if (r === "termos") setRoute({page: "produto", id: "termos"});
        else if (r === "aviso-legal") setRoute({page: "produto", id: "aviso-legal"});
        else if (r === "contato") setRoute({page: "contato"});
        else if (r === "login") setRoute({page: "login"});
        else if (r === "marcas") { setRoute({page: "home"}); setTimeout(() => brandsRef.current?.scrollIntoView({behavior: "smooth", block: "start"}), 120); }
      }
    }
    window.addEventListener("message", onMsg);
    return () => window.removeEventListener("message", onMsg);
  }, [theme]);

  uE(() => {
    function handleHash() {
      const h = window.location.hash;
      if (!h) return;
      if (h === "#marcas") {
        if (route.page !== "home") { setRoute({page: "home"}); }
        setTimeout(() => brandsRef.current?.scrollIntoView({behavior: "smooth", block: "start"}), 120);
      } else if (h === "#blog") {
        setRoute({page: "produto", id: "blog"});
      } else if (h === "#sobre") {
        setRoute({page: "produto", id: "sobre"});
      } else if (h === "#contato") {
        setRoute({page: "contato"});
      } else if (h === "#login") {
        setRoute({page: "login"});
      } else if (h === "#privacidade") {
        setRoute({page: "produto", id: "privacidade"});
      } else if (h === "#termos") {
        setRoute({page: "produto", id: "termos"});
      } else if (h === "#aviso-legal") {
        setRoute({page: "produto", id: "aviso-legal"});
      }
      // Clear hash so the same link can be clicked again
      history.replaceState(null, "", window.location.pathname + window.location.search);
    }
    handleHash();
    window.addEventListener("hashchange", handleHash);
    return () => window.removeEventListener("hashchange", handleHash);
  }, [route.page]);

  useReveal();

  function go(r) { setRoute(r); window.scrollTo({top: 0, behavior: "instant"}); }

  function addToCart(brand, product) {
    setCart(c => [...c, { brand, product }]);
    pushToast(`"${product.title}" adicionado ao carrinho`);
  }

  function addBundle(b) {
    const bundleProduct = { id: b.id, title: b.title, type: "Combo", price: b.price, original: b.original, desc: b.desc };
    const bundleBrand = { id: "lc4-bundle", name: "LC4lab Bundle", accent: "#22d3ee", accent2: "#8b5cf6", bg: "#0a0f1d" };
    setCart(c => [...c, { brand: bundleBrand, product: bundleProduct }]);
    pushToast(`Combo "${b.title}" adicionado`);
  }

  function pushToast(msg) {
    const id = Date.now() + Math.random();
    setToasts(t => [...t, { id, msg }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 3000);
  }

  function onSearchSubmit(e) {
    e.preventDefault();
    if (search.trim()) go({page: "search", q: search.trim()});
  }

  return (
    <>
      <div className="bg-orbs"/>
      <div className="bg-grid"/>

      <nav className="nav">
        <div className="container nav-inner">
          <a className="brand" onClick={() => go({page: "home"})}>
            <img src="assets/logo-lc4lab.png" alt="LC4lab"/>
            <span className="brand-name">LC<b>4</b>lab</span>
          </a>
          <div className="nav-links">
            <a onClick={() => { go({page: "home"}); setTimeout(() => brandsRef.current?.scrollIntoView({behavior: "smooth", block: "start"}), 50); }}>Marcas</a>
            <a onClick={() => go({page: "brand", id: "combos"})}>Combos</a>
            <a onClick={() => go({page: "produto", id: "blog"})}>Blog</a>
            <a onClick={() => go({page: "produto", id: "sobre"})}>Sobre</a>
          </div>
          <form onSubmit={onSearchSubmit}>
            <div className="search-bar" style={{width: 220, height: 40}}>
              {Icons.search(16)}
              <input placeholder="Buscar produtos..." value={search} onChange={e => setSearch(e.target.value)}/>
            </div>
          </form>
          <div className="nav-actions">
            <button className="icon-btn" title="Tema" onClick={() => setTheme(t => t === "dark" ? "light" : "dark")}>
              {theme === "dark" ? Icons.sun(16) : Icons.moon(16)}
            </button>
            <button className="icon-btn" title="Área do aluno" onClick={() => go({page: "login"})}>{Icons.user(16)}</button>
            <button className="icon-btn" title="Carrinho" onClick={() => setCartOpen(true)}>
              {Icons.cart(16)}
              {cart.length > 0 && <span className="cart-badge">{cart.length}</span>}
            </button>
          </div>
        </div>
      </nav>

      {route.page === "home" && (
        <>
          <Hero
            onExplore={() => brandsRef.current?.scrollIntoView({behavior: "smooth"})}
            onScroll={() => go({page: "brand", id: "combos"})}/>
          <Categories onPick={() => brandsRef.current?.scrollIntoView({behavior: "smooth"})}/>
          <BrandsSection sectionRef={brandsRef} onOpenBrand={(id) => go({page: "brand", id})}/>
          <About/>
          {/* <Testimonials/> */}
          <Blog/>
          <Newsletter onSubmit={() => pushToast("Bem-vindo(a) à newsletter LC4lab")}/>
          <FAQ/>
        </>
      )}

      {route.page === "brand" && (
        <BrandPage brandId={route.id} go={go}
          onOpenProduct={(b,p) => setModal({brand: b, product: p})}
          onAdd={addToCart}/>
      )}

      {route.page === "search" && (
        <SearchPage query={route.q || ""} go={go}
          onOpenProduct={(b,p) => setModal({brand: b, product: p})}
          onAdd={addToCart}/>
      )}

      {route.page === "checkout" && (
        <CheckoutPage items={cart} go={go} onClear={() => setCart([])}/>
      )}

      {route.page === "login" && <LoginPage go={go}/>}

      {route.page === "produto" && <ProductPage slug={route.id} go={go}/>}

      {route.page === "contato" && <ContactPage go={go}/>}

      <a href="https://wa.me/5519000000000" target="_blank" rel="noopener" aria-label="WhatsApp"
         style={{position: "fixed", bottom: 24, right: 24, width: 58, height: 58, borderRadius: "50%", background: "#25d366", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 12px 32px rgba(37,211,102,0.45), 0 0 0 1px rgba(255,255,255,0.1)", zIndex: 90, color: "#fff"}}>
        <svg width="30" height="30" viewBox="0 0 24 24" fill="currentColor"><path d="M20.5 3.5A11 11 0 0 0 3.4 17.1L2 22l5-1.4A11 11 0 1 0 20.5 3.5zM12 20.2c-1.7 0-3.4-.5-4.8-1.3l-.4-.2-3 .8.8-2.9-.2-.4A9 9 0 1 1 12 20.2zm5-6.7c-.3-.1-1.6-.8-1.9-.9-.3-.1-.4-.1-.6.1l-.9 1.1c-.2.2-.3.2-.6.1-.3-.1-1.2-.4-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.4.1-.6l.5-.5c.1-.2.2-.3.3-.5 0-.2 0-.4 0-.5l-.8-2c-.2-.5-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.3-.3.3-1 1-1 2.4s1 2.7 1.1 2.9c.1.2 2 3.1 4.9 4.4.7.3 1.2.5 1.6.6.7.2 1.3.2 1.8.1.5-.1 1.6-.7 1.8-1.3.2-.6.2-1.2.2-1.3 0-.1-.2-.2-.5-.3z"/></svg>
      </a>

      {route.page !== "produto" && <Footer go={go}/>}

      {modal && <ProductModal brand={modal.brand} product={modal.product}
        onClose={() => setModal(null)} onAdd={addToCart} go={go}/>}

      <CartDrawer open={cartOpen} items={cart}
        onClose={() => setCartOpen(false)}
        onRemove={(idx) => setCart(c => c.filter((_, i) => i !== idx))}
        onCheckout={() => { setCartOpen(false); go({page: "checkout"}); }}/>

      <Toasts toasts={toasts}/>
    </>
  );
}

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