/* ============================================================
   FLORÍADE — App root (rotas, tweaks, mount)
   ============================================================ */
const { useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "nupcias",
  "titleFont": "Cinzel",
  "spin": true,
  "frames": true
}/*EDITMODE-END*/;

const FONT_MAP = {
  "Cinzel": '"Cinzel", serif',
  "Cormorant": '"Cormorant Garamond", serif',
  "Garamond": '"EB Garamond", serif',
};

function useReveal(dep){
  useEffect(()=>{
    const els = [...document.querySelectorAll(".reveal:not(.in)")];
    const show = el => el.classList.add("in");
    if(!("IntersectionObserver" in window)){ els.forEach(show); return; }
    const io = new IntersectionObserver((entries, obs)=>{
      entries.forEach(en=>{ if(en.isIntersecting){ show(en.target); obs.unobserve(en.target); } });
    }, { threshold:0, rootMargin:"0px 0px -5% 0px" });
    els.forEach(e=>io.observe(e));
    const t = setTimeout(()=> els.forEach(e=>{ if(!e.classList.contains("in")) show(e); }), 1400);
    return ()=>{ io.disconnect(); clearTimeout(t); };
  }, [dep]);
}

function App(){
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = useState("home");
  const [param, setParam] = useState(null);

  const go = useCallback((r, p=null)=>{
    setRoute(r); setParam(p);
    if(r!=="produto") window.scrollTo({top:0, behavior:"instant" in window ? "instant" : "auto"});
    else window.scrollTo(0,0);
  },[]);

  // aplicar tweaks — troca de paleta instantânea (sem "arrasto" de cor)
  useEffect(()=>{
    const html = document.documentElement;
    html.classList.add("pal-switching");
    html.dataset.palette = t.palette;
    const id = setTimeout(()=> html.classList.remove("pal-switching"), 60);
    return ()=> clearTimeout(id);
  }, [t.palette]);
  useEffect(()=>{ document.documentElement.style.setProperty("--font-display", FONT_MAP[t.titleFont]||FONT_MAP.Cinzel); }, [t.titleFont]);
  useEffect(()=>{ document.body.classList.toggle("no-spin", !t.spin); }, [t.spin]);
  useEffect(()=>{ document.body.classList.toggle("no-frames", !t.frames); }, [t.frames]);

  useReveal(route+"|"+param);

  let view;
  if(route==="home") view = <Home go={go}/>;
  else if(route==="loja") view = <Loja go={go} initialLine={param||"todos"}/>;
  else if(route==="produto") view = <Produto id={param} go={go}/>;
  else if(route==="alquimia") view = <Alquimia go={go}/>;
  else if(route==="diario") view = <Diario/>;
  else if(route==="contato") view = <Contato/>;
  else view = <Home go={go}/>;

  return (
    <CartProvider>
      <Header route={route} go={go}/>
      <main className="main">{view}</main>
      <Footer go={go}/>
      <CartDrawer onGoProduct={(id)=>go("produto",id)}/>

      <TweaksPanel>
        <TweakSection label="Paleta · Sol et Luna"/>
        <PaletteTweak value={t.palette} onChange={v=>setTweak("palette",v)}/>
        <TweakSection label="Tipografia"/>
        <TweakRadio label="Títulos" value={t.titleFont}
          options={["Cinzel","Cormorant","Garamond"]}
          onChange={v=>setTweak("titleFont",v)}/>
        <TweakSection label="Ornamento"/>
        <TweakToggle label="Roda alquímica girando" value={t.spin} onChange={v=>setTweak("spin",v)}/>
        <TweakToggle label="Molduras de tapete" value={t.frames} onChange={v=>setTweak("frames",v)}/>
      </TweaksPanel>
    </CartProvider>
  );
}

/* Swatches de paleta customizados */
function PaletteTweak({ value, onChange }){
  const sw = {
    nupcias:    ["#0c1022","#c4cde3","#caa257"],
    pergaminho: ["#ece0c4","#9a7a2c","#5f6678"],
    ritual:     ["#1d0e09","#cda44a","#c3cad9"],
    terra:      ["#411e15","#d8a740","#c8ccd6"],
  };
  return (
    <div className="pal-tweak">
      {PALETTES.map(p=>(
        <button key={p.id} className={"pal-opt"+(value===p.id?" is-on":"")} onClick={()=>onChange(p.id)}>
          <span className="pal-sw">
            {sw[p.id].map((c,i)=><span key={i} style={{background:c}}></span>)}
          </span>
          <span className="pal-label">{p.label}</span>
          <span className="pal-note">{p.note}</span>
        </button>
      ))}
    </div>
  );
}

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