// Mobile redesign — root.
//
// Orchestrates the feed + detail slide-up. Filters live inline in the top
// bar (3 native-select chips), so there is no filter sheet on this branch.

const { useState: useStateMA, useMemo: useMemoMA, useEffect: useEffectMA } = React;

const _MA_PROFILE_KEY = "r-profile-v3";
const _MA_TWEAKS_KEY = "r-tweaks";

function _maLoadProfile() {
  try {
    const raw = localStorage.getItem(_MA_PROFILE_KEY);
    if (raw) return JSON.parse(raw);
  } catch (_) {}
  return {};
}
function _maSaveProfile(p) {
  try { localStorage.setItem(_MA_PROFILE_KEY, JSON.stringify(p)); } catch (_) {}
}
function _maLoadTweaks() {
  const fallback = {
    lang: "en", dark: false, teaching: "basic", density: "comfortable",
    highlight: "none", hideIneligible: false, currency: "usd",
  };
  try {
    const raw = localStorage.getItem(_MA_TWEAKS_KEY);
    if (raw) return { ...fallback, ...JSON.parse(raw) };
  } catch (_) {}
  return { ...fallback, ...(window.SETTINGS?.defaults || {}) };
}
function _maSaveTweaks(t) {
  try { localStorage.setItem(_MA_TWEAKS_KEY, JSON.stringify(t)); } catch (_) {}
}

function MobileApp() {
  const [tweaks, setTweaks] = useStateMA(_maLoadTweaks);
  const [profile, setProfile] = useStateMA(_maLoadProfile);
  const [selected, setSelected] = useStateMA(null);

  const lang = tweaks.lang;
  const dark = !!tweaks.dark;
  const currency = tweaks.currency || "usd";
  const t = (window.STRINGS && window.STRINGS[lang]) || {};
  const PRODUCTS = window.PRODUCTS || [];

  useEffectMA(() => { _maSaveProfile(profile); }, [profile]);
  useEffectMA(() => { _maSaveTweaks(tweaks); }, [tweaks]);
  useEffectMA(() => { document.documentElement.lang = lang; }, [lang]);
  useEffectMA(() => {
    const root = document.querySelector("#root > div") || document.documentElement;
    root.classList.toggle("dark", !!dark);
  }, [dark]);

  const setLang = (v) => setTweaks(prev => ({ ...prev, lang: v }));
  const setCurrency = (v) => setTweaks(prev => ({ ...prev, currency: v }));

  const columns = useMemoMA(
    () => (window.buildColumns ? window.buildColumns(PRODUCTS, profile) : []),
    [PRODUCTS, profile]
  );

  useEffectMA(() => {
    if (!selected) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prev; };
  }, [selected]);

  useEffectMA(() => {
    const onKey = (e) => { if (e.key === "Escape" && selected) setSelected(null); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [selected]);

  const bg = dark ? "#0D0D0D" : "#FAF7F3";
  const ink = dark ? "#FAF7F3" : "#393433";

  return (
    <div
      className={`r-mobile-app${dark ? " dark" : ""}`}
      style={{
        minHeight: "100dvh",
        background: bg,
        color: ink,
        fontFamily: "var(--font-body)", fontWeight: 400,
      }}
    >
      {window.EmailGate && <window.EmailGate t={t} dark={dark}/>}

      <window.MobileTopBar
        t={t}
        lang={lang}
        setLang={setLang}
        currency={currency}
        setCurrency={setCurrency}
        dark={dark}
        profile={profile}
        setProfile={setProfile}
      />

      <window.MobileStatsBar columns={columns} lang={lang} dark={dark}/>

      <window.MobileFeed
        columns={columns}
        profile={profile}
        t={t}
        lang={lang}
        dark={dark}
        currency={currency}
        onSelectProduct={(p) => setSelected(p)}
      />

      <window.MobileDetailSheet
        product={selected}
        onClose={() => setSelected(null)}
        t={t}
        lang={lang}
        dark={dark}
        profile={profile}
        allProducts={PRODUCTS}
        onSelectProduct={(p) => setSelected(p)}
      />
    </div>
  );
}

Object.assign(window, { MobileApp });
