function App() {
  const [tweaks, setTweaks] = useState(() => ({ ...window.TWEAK_DEFAULTS }));
  const [tweaksOpen, setTweaksOpen] = useState(false);
  const [favCount, setFavCount] = useState(() => {
    try { return JSON.parse(localStorage.getItem("cal:favs") || "[]").length; } catch { return 0; }
  });

  // apply tweaks to css
  useEffect(() => { applyTweaks(tweaks); }, [tweaks]);

  // favs sync
  useEffect(() => {
    const h = (e) => setFavCount((e.detail || []).length);
    window.addEventListener("favsChanged", h);
    return () => window.removeEventListener("favsChanged", h);
  }, []);

  // host edit mode handshake
  useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === "__activate_edit_mode") setTweaksOpen(true);
      if (d.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", onMsg);
    try { window.parent.postMessage({ type: "__edit_mode_available" }, "*"); } catch {}
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const [activeStory, setActiveStory] = useState(null);
  const toggleDark = () => setTweaks(t => ({ ...t, dark: !t.dark }));

  return (
    <>
      <Header
        dark={tweaks.dark}
        onToggleDark={toggleDark}
        favCount={favCount}
      />
      <Hero layout={tweaks.heroLayout} />
      <Featured onOpen={setActiveStory} />
      <StoriesGrid cardStyle={tweaks.cardStyle} onOpen={setActiveStory} />
      <CalabriaMap />
      <EventsSection />
      <ThemesSection />
      <ProvincesSection />
      <Newsletter />
      <Footer />

      {/* Floating toggle for Tweaks panel when host hasn't activated */}
      {!tweaksOpen && (
        <button onClick={() => setTweaksOpen(true)} style={{
          position: "fixed", bottom: 24, right: 24, zIndex: 300,
          background: "var(--ink)", color: "var(--paper)", border: "none",
          padding: "12px 18px", fontFamily: "var(--font-mono)",
          fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase",
          boxShadow: "0 10px 30px -10px rgba(0,0,0,.4)",
        }}>⚙ Tweaks</button>
      )}
      {tweaksOpen && <TweaksPanel state={tweaks} setState={setTweaks} onClose={() => setTweaksOpen(false)} />}
      {activeStory && <ArticleModal story={activeStory} onClose={() => setActiveStory(null)} />}
    </>
  );
}

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