// 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) {
      const parsed = JSON.parse(raw);
      // Investment-type emphasis always resets to its Equity default on a
      // fresh load (mirrors public/app.jsx): absent key = untouched default.
      if (parsed && typeof parsed === "object") { delete parsed.typeInterest; }
      return parsed;
    }
  } 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 [projectCol, setProjectCol] = useStateMA(null);
  // Gates open/close URL-sync so URL-driven updates (popstate / load) don't
  // re-enter setPanel — prevents a popstate↔pushState history loop.
  const applyingUrlRef = React.useRef(false);

  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 }));

  useEffectMA(() => {
    window.openProduct = (productId) => {
      const p = (window.PRODUCTS || []).find((x) => x.id === productId);
      if (p) {
        setProjectCol(null); setSelected(p);
        if (!applyingUrlRef.current && window.urlState) {
          window.urlState.setPanel({ kind: "offering", id: p.id });
        }
      }
    };
    return () => { delete window.openProduct; };
  }, []);

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

  useEffectMA(() => {
    window.openProject = (nameOrCol) => {
      const col = typeof nameOrCol === "string"
        ? (columns || []).find((c) => c.name === nameOrCol) : nameOrCol;
      if (!col || !(window.canOpenProject ? window.canOpenProject(col) : window.hasProjectContent(col.name))) return;
      setSelected(null);
      setProjectCol(col);
      if (!applyingUrlRef.current && window.urlState) {
        window.urlState.setPanel({ kind: "project", slug: window.projectSlug(col.name) });
      }
    };
    return () => { delete window.openProject; };
  }, [columns]);

  // Deep-linking: resolve ?offering=/?project= on load, sync on Back/Forward.
  // Mirrors desktop (app.jsx). applyingUrlRef prevents a history loop.
  useEffectMA(() => {
    const resolve = () => {
      const panel = window.urlState && window.urlState.getPanel();
      applyingUrlRef.current = true;
      try {
        if (panel && panel.kind === "offering") {
          const p = (window.PRODUCTS || []).find((x) => x.id === panel.id);
          if (p) { setProjectCol(null); setSelected(p); }
          else { setProjectCol(null); setSelected(null); }
        } else if (panel && panel.kind === "project") {
          const col = (columns || []).find((c) => window.projectSlug(c.name) === panel.slug);
          if (col && (window.canOpenProject ? window.canOpenProject(col) : window.hasProjectContent(col.name))) { setSelected(null); setProjectCol(col); }
          else { setSelected(null); setProjectCol(null); }
        } else {
          setSelected(null); setProjectCol(null);
        }
      } finally { applyingUrlRef.current = false; }
    };
    resolve();
    window.addEventListener("popstate", resolve);
    return () => window.removeEventListener("popstate", resolve);
  }, [columns]);

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

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

  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.FaqSurface && <window.FaqSurface lang={lang} dark={dark} profile={profile} />}
      {window.EmailGate && <window.EmailGate t={t} dark={dark}/>}
      {/* bp is fixed: App only renders MobileApp at "mobile" or "narrow", and
          the coach mark resolves the same anchor for both. */}
      {window.CoachMark && <window.CoachMark profile={profile} lang={lang} dark={dark} bp="mobile" t={t}/>}

      {window.StoryPage && <window.StoryPage lang={lang} setLang={setLang} shell="mobile" />}

      {/* The offerings, after the story. The top strip stays sticky, but only within this wrapper.
          StoryPage finds it by this id. */}
      <div id="r-offerings" className="r-offerings r-offerings--mobile">
        <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) => { setProjectCol(null); setSelected(p); }}
        />
      </div>

      <window.MobileDetailSheet
        product={selected}
        col={projectCol || (selected ? (columns || []).find(c => c.name === selected.project) : null)}
        mode={projectCol ? "project" : "offering"}
        onOpenProject={(col) => window.openProject && window.openProject(col)}
        open={!!selected || !!projectCol}
        onClose={() => {
          setSelected(null); setProjectCol(null);
          if (window.urlState) window.urlState.setPanel(null, { replace: true });
        }}
        t={t}
        lang={lang}
        dark={dark}
        profile={profile}
        allProducts={PRODUCTS}
        onSelectProduct={(p) => { setProjectCol(null); setSelected(p); }}
      />
    </div>
  );
}

Object.assign(window, { MobileApp });
