/* global React, ReactDOM, Header, Hero, Home, Taller, Catalog, Modelo, Ficha, Clientes, Cursos, Showroom,
   Wishlist, Modal, useUI, TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakToggle, TweakColor, TweakSelect */
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "hero": "A",
  "accent": "#C13B1F",
  "density": "normal",
  "card": "minimal",
  "prices": true,
  "view": "desktop"
}/*EDITMODE-END*/;

function App() {
  // route: { page, params }
  const [route, setRouteRaw] = useState({ page: "home", params: {} });
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const ui = useUI();

  // Cada cambio de ruta pushea estado al historial del navegador
  const setRoute = (newRoute, replace = false) => {
    setRouteRaw(newRoute);
    if (replace) {
      window.history.replaceState(newRoute, "");
    } else {
      window.history.pushState(newRoute, "");
    }
  };

  // Escucha el botón atrás del navegador
  useEffect(() => {
    // Reemplaza el estado inicial para que el primer atrás no saque del sitio
    window.history.replaceState({ page: "home", params: {} }, "");
    const onPop = (e) => {
      if (e.state && e.state.page) {
        setRouteRaw(e.state);
      } else {
        setRouteRaw({ page: "home", params: {} });
      }
    };
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  const setPage = (page, params = {}) => setRoute({ page, params });
  const openCatalog       = (initialFilter = {}) => setRoute({ page: "catalog", params: { filter: initialFilter } });
  const openCategoria     = (cat) => openCatalog({ cat });
  const openModelo        = (modeloName) => setRoute({ page: "modelo", params: { modelo: modeloName } });
  const openFicha         = (productOrId) => {
    const id = typeof productOrId === "string" ? productOrId : (productOrId && productOrId.id);
    if (!id) return;
    setRoute({ page: "ficha", params: { productId: id } });
  };

  useEffect(() => {
    document.documentElement.style.setProperty("--accent", t.accent);
  }, [t.accent]);

  useEffect(() => {
    if (t.view === "mobile") {
      const el = document.querySelector(".phone-scroll");
      if (el) el.scrollTo({ top: 0, behavior: "instant" });
    } else {
      window.scrollTo({ top: 0, behavior: "instant" });
    }
  }, [route.page, route.params, t.view]);

  // Hero variant determines if header should be dark over the home page
  const headerDark =
    (route.page === "home" && t.hero === "A") ||
    route.page === "taller" ||
    route.page === "modelo" ||
    route.page === "showroom";

  const densityCls = t.density === "compact" ? "dens-compact" : t.density === "airy" ? "dens-airy" : "";
  const viewMobile = t.view === "mobile";

  const openProductModal = (p) => ui.openModal(p);

  // Expose route handlers globally so Home cards, Modal "Ver ficha", etc. can call them
  useEffect(() => {
    window.__davasRoute = { openCatalog, openCategoria, openModelo, openFicha, setPage };
  }, [route]);

  const renderPage = () => {
    switch (route.page) {
      case "home":
        return (
          <>
            <Hero variant={t.hero} setPage={(p) => setPage(p === "home" ? "catalog" : p)} openProduct={openProductModal} />
            <Home setPage={(p) => setPage(p)} showPrices={t.prices} cardStyle={t.card} />
          </>
        );
      case "taller":     return <Taller setPage={setPage} />;
      case "catalog":    return <Catalog initialFilter={route.params.filter} setPage={setPage} openModelo={openModelo} openFicha={openFicha} />;
      case "modelo":     return <Modelo modeloName={route.params.modelo} setPage={setPage} openFicha={openFicha} goCatalog={() => setPage("catalog")} />;
      case "ficha":      return <Ficha productId={route.params.productId} setPage={setPage} openFicha={openFicha} openModelo={openModelo} goCatalog={() => setPage("catalog")} />;
      case "clientes":   return <Clientes setPage={setPage} goCatalog={() => setPage("catalog")} />;
      case "cursos":     return <Cursos setPage={setPage} />;
      case "showroom":   return <Showroom setPage={setPage} />;
      default:           return null;
    }
  };

  const PageContent = (
    <>
      <Header page={route.page} setPage={(p) => setPage(p)} dark={headerDark} mobile={viewMobile} />
      {renderPage()}
    </>
  );

  return (
    <div className={`shell ${densityCls} ${viewMobile ? "mobile-view" : ""}`}>
      {viewMobile ? (
        <>
          <div className="phone-label">DAVA'S · MOBILE PREVIEW · {route.page.toUpperCase()}</div>
          <div className="phone-frame">
            <div className="phone-scroll mobile-mode">
              {PageContent}
            </div>
          </div>
        </>
      ) : (
        PageContent
      )}

      <Wishlist />
      <Modal />

      <TweaksPanel title="Tweaks · DAVA'S">
        <TweakSection label="Página">
          <TweakSelect
            label="Ir a"
            value={route.page}
            options={[
              { value: "home",     label: "Home" },
              { value: "catalog",  label: "Catálogo" },
              { value: "modelo",   label: "Modelo · Pavo Real" },
              { value: "ficha",    label: "Ficha · ME-003" },
              { value: "clientes", label: "Clientes felices" },
              { value: "cursos",   label: "Cursos" },
              { value: "showroom", label: "Showroom" },
              { value: "taller",   label: "Taller" },
            ]}
            onChange={(v) => {
              if (v === "modelo") openModelo("Pavo Real");
              else if (v === "ficha") openFicha("ME-003");
              else setPage(v);
            }}
          />
        </TweakSection>

        <TweakSection label="Hero · Home">
          <TweakRadio
            label="Variante"
            value={t.hero}
            options={[
              { value: "A", label: "Foto" },
              { value: "B", label: "Producto" },
              { value: "C", label: "Mosaico" },
            ]}
            onChange={(v) => setTweak("hero", v)}
          />
        </TweakSection>

        <TweakSection label="Sistema">
          <TweakColor
            label="Acento"
            value={t.accent}
            options={["#C13B1F", "#E3A724", "#4B6E5A", "#1A1714"]}
            onChange={(v) => setTweak("accent", v)}
          />
          <TweakRadio
            label="Densidad"
            value={t.density}
            options={[
              { value: "compact", label: "Compacta" },
              { value: "normal", label: "Normal" },
              { value: "airy", label: "Aireada" },
            ]}
            onChange={(v) => setTweak("density", v)}
          />
          <TweakRadio
            label="Vista"
            value={t.view}
            options={[
              { value: "desktop", label: "Desktop" },
              { value: "mobile", label: "Mobile" },
            ]}
            onChange={(v) => setTweak("view", v)}
          />
        </TweakSection>

        <TweakSection label="Cards de producto">
          <TweakRadio
            label="Estilo"
            value={t.card}
            options={[
              { value: "minimal", label: "Minimal" },
              { value: "labeled", label: "Etiquetado" },
              { value: "overlay", label: "Overlay" },
            ]}
            onChange={(v) => setTweak("card", v)}
          />
          <TweakToggle
            label="Mostrar precios"
            value={t.prices}
            onChange={(v) => setTweak("prices", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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