/* ===== AI Ki Baat — app shell =====
   Loads the live content from Supabase (falling back to the bundled default),
   applies theme / layout / motion, and renders the page. */
const { createClient } = supabase;
const sb = createClient(window.AKB_CONFIG.SUPABASE_URL, window.AKB_CONFIG.SUPABASE_KEY);

function applySettings(settings) {
  const s = settings || {};
  const r = document.documentElement;
  r.setAttribute("data-theme", s.theme || "sky");
  r.setAttribute("data-hero", s.heroLayout || "split");
  r.setAttribute("data-motion", s.motion === false ? "off" : "on");
}

function Splash() {
  return (
    <div style={{ position: "fixed", inset: 0, display: "grid", placeItems: "center",
      background: "linear-gradient(180deg,#8ED2F4,#46A6E6 52%,#2C84CB)" }}>
      <div style={{ textAlign: "center", color: "#fff", fontFamily: "'Baloo 2',sans-serif" }}>
        <div style={{ width: 46, height: 46, margin: "0 auto 14px", border: "4px solid rgba(255,255,255,.4)",
          borderTopColor: "#fff", borderRadius: "50%", animation: "akbspin .9s linear infinite" }}></div>
        <div style={{ fontWeight: 800, fontSize: "1.2rem", letterSpacing: ".02em" }}>AI की बात</div>
      </div>
      <style>{`@keyframes akbspin{to{transform:rotate(360deg)}}`}</style>
    </div>
  );
}

function App() {
  const [content, setContent] = useState(null);
  const [video, setVideo] = useState(null);
  const [lang, setLangState] = useState(() => localStorage.getItem("akb_lang") || "en");
  const setLang = (v) => { setLangState(v); try { localStorage.setItem("akb_lang", v); } catch (e) {} };

  useEffect(() => {
    let alive = true;
    (async () => {
      let data = null;
      try {
        const res = await sb.from("site_content").select("content")
          .eq("id", window.AKB_CONFIG.CONTENT_ID).maybeSingle();
        if (res.data && res.data.content) data = res.data.content;
      } catch (e) { /* network/RLS — fall back to bundled default */ }
      if (!alive) return;
      const merged = data || window.AKB_DEFAULT;
      window.AKB = merged;
      window.__resources = merged.images || {};
      applySettings(merged.settings);
      setContent(merged);
    })();
    return () => { alive = false; };
  }, []);

  if (!content) return <Splash />;

  // sections read the global AKB; keep it current for re-renders
  window.AKB = content;
  window.__resources = content.images || {};
  const onPlay = (yt, title) => setVideo({ yt, title });

  return (
    <LangCtx.Provider value={[lang, setLang]}>
      <Nav />
      <Hero onPlay={onPlay} />
      <ListenStrip />
      <Episodes onPlay={onPlay} />
      <Quiz />
      <Blog />
      <About />
      <Newsletter />
      <Footer />
      <VideoModal video={video} onClose={() => setVideo(null)} />
    </LangCtx.Provider>
  );
}

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