/* App: router por hash, Tweaks, banner de cookies, montaje. */
(function () {
  const { useState, useEffect } = React;

  const ACCENTS = {
    "#FF7A6B": { deep: "#F0604F", tint: "#FFE7E2", rgb: "255, 122, 107" },
    "#F5B342": { deep: "#E09A1F", tint: "#FDF1DC", rgb: "245, 179, 66" },
    "#7CC4E8": { deep: "#3F9FD0", tint: "#E6F4FB", rgb: "124, 196, 232" },
  };

  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "accent": "#FF7A6B",
    "heroVariant": "A",
    "heroScale": 100,
    "featuredCount": 6,
    "anim": 6
  }/*EDITMODE-END*/;

  function applyTweaks(t) {
    const root = document.documentElement.style;
    const a = ACCENTS[t.accent] || ACCENTS["#FF7A6B"];
    root.setProperty("--accent", t.accent);
    root.setProperty("--accent-deep", a.deep);
    root.setProperty("--accent-tint", a.tint);
    root.setProperty("--accent-shadow", a.rgb);
    root.setProperty("--hero-scale", String(t.heroScale / 100));
    root.setProperty("--anim", String(Math.round((t.anim / 6) * 100) / 100));
  }

  /* ----------------------------------------------------------- mini-thumbs hero */
  const HERO_THUMBS = {
    A: <svg viewBox="0 0 80 44"><rect x="4" y="10" width="30" height="5" rx="2" fill="currentColor"/><rect x="4" y="19" width="22" height="4" rx="2" fill="currentColor" opacity=".5"/><rect x="46" y="6" width="16" height="20" rx="3" fill="currentColor" opacity=".8"/><rect x="60" y="16" width="14" height="18" rx="3" fill="currentColor" opacity=".55"/></svg>,
    B: <svg viewBox="0 0 80 44"><rect x="4" y="12" width="26" height="5" rx="2" fill="currentColor"/><rect x="4" y="21" width="18" height="4" rx="2" fill="currentColor" opacity=".5"/><rect x="48" y="6" width="22" height="30" rx="3" fill="currentColor" opacity=".8"/></svg>,
    C: <svg viewBox="0 0 80 44"><rect x="22" y="10" width="36" height="5" rx="2" fill="currentColor"/><rect x="28" y="19" width="24" height="4" rx="2" fill="currentColor" opacity=".5"/><path d="M0 34 Q20 26 40 32 T80 32 V44 H0Z" fill="currentColor" opacity=".35"/></svg>,
  };

  function HeroTweak({ value, onChange }) {
    return (
      <div className="tweak-hero-thumbs">
        {["A", "B", "C"].map(k => (
          <button key={k} className={"tweak-hero-thumb" + (value === k ? " on" : "")} onClick={() => onChange(k)}
            style={{ color: value === k ? "var(--accent-deep)" : "var(--carbon-soft)" }} aria-pressed={value === k}>
            {HERO_THUMBS[k]}
            <span>{k === "A" ? "Flotante" : k === "B" ? "Portada" : "Ilustración"}</span>
          </button>
        ))}
      </div>
    );
  }

  /* ----------------------------------------------------------------- cookies */
  function Cookie() {
    const [show, setShow] = useState(false);
    useEffect(() => {
      if (!localStorage.getItem("fun_cookie")) { const t = setTimeout(() => setShow(true), 1200); return () => clearTimeout(t); }
    }, []);
    const close = (v) => { localStorage.setItem("fun_cookie", v); setShow(false); };
    return (
      <div className={"cookie" + (show ? " show" : "")} role="dialog" aria-label="Aviso de cookies">
        <p>Usamos cookies para entender qué libros gustan más. Puedes aceptarlas o seguir solo con las necesarias.</p>
        <div className="cookie-actions">
          <button className="cookie-btn cookie-no" onClick={() => close("min")}>Solo necesarias</button>
          <button className="cookie-btn cookie-ok" onClick={() => close("all")}>Aceptar</button>
        </div>
      </div>
    );
  }

  /* ------------------------------------------------------------------- router */
  function useHashRoute() {
    const get = () => (window.location.hash.replace(/^#\/?/, "") || "home");
    const [route, setRoute] = useState(get());
    useEffect(() => {
      const f = () => { setRoute(get()); window.scrollTo(0, 0); };
      window.addEventListener("hashchange", f);
      return () => window.removeEventListener("hashchange", f);
    }, []);
    const navigate = (to) => {
      if (("#/" + to) === window.location.hash) { window.scrollTo({ top: 0, behavior: "smooth" }); return; }
      window.location.hash = "#/" + to;
    };
    return [route, navigate];
  }

  function App() {
    const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
    const [route, navigate] = useHashRoute();
    useEffect(() => { applyTweaks(t); }, [t.accent, t.heroScale, t.anim]);

    const [head, ...rest] = route.split("/");
    let page;
    if (head === "libros") page = <Catalog navigate={navigate} />;
    else if (head === "libro") page = <Detail slug={rest.join("/")} navigate={navigate} />;
    else if (head === "sobre") page = <About navigate={navigate} />;
    else if (head === "contacto") page = <Contact navigate={navigate} />;
    else if (head === "privacidad") page = <Privacy navigate={navigate} />;
    else page = <Home navigate={navigate} tweaks={t} />;

    return (
      <>
        <Navbar route={route} navigate={navigate} />
        {page}
        <Footer navigate={navigate} />
        <Cookie />
        <TweaksPanel>
          <TweakSection label="Hero del Home" />
          <TweakRow label="Variante">
            <HeroTweak value={t.heroVariant} onChange={(v) => { setTweak("heroVariant", v); if (route.split("/")[0] !== "home") navigate("home"); }} />
          </TweakRow>
          <TweakSlider label="Tamaño del título" value={t.heroScale} min={80} max={130} step={1} unit="%"
            onChange={(v) => setTweak("heroScale", v)} />
          <TweakSection label="Marca" />
          <TweakColor label="Color de acento" value={t.accent}
            options={["#FF7A6B", "#F5B342", "#7CC4E8"]}
            onChange={(v) => setTweak("accent", v)} />
          <TweakSection label="Catálogo destacado" />
          <TweakSlider label="Libros en el carrusel" value={t.featuredCount} min={4} max={8} step={1}
            onChange={(v) => setTweak("featuredCount", v)} />
          <TweakSection label="Movimiento" />
          <TweakSlider label="Intensidad de animaciones" value={t.anim} min={0} max={10} step={1}
            onChange={(v) => setTweak("anim", v)} />
        </TweaksPanel>
      </>
    );
  }

  window.FunApp = App;
})();
