// app.jsx — Root app

const MODULE_ROUTES = Object.freeze({});

const canonicalModuleId = (id) => id === "calendar" ? "clock" : id;
const moduleRoute = (id) => MODULE_ROUTES[canonicalModuleId(id)] || null;

// ----- Decorative animated background (cyan/gold dots, drifting rings, faint wire lines) -----
const Decor = () => {
  const dots = React.useMemo(() =>
  Array.from({ length: 28 }, (_, i) => ({
    x: Math.random() * 100, y: Math.random() * 100,
    s: 2 + Math.random() * 3, d: Math.random() * 4,
    gold: Math.random() > 0.6
  })), []);
  const rings = React.useMemo(() =>
  Array.from({ length: 4 }, (_, i) => ({
    x: [10, 88, 6, 92][i], y: [12, 18, 88, 78][i],
    size: 280 + Math.random() * 180,
    gold: i % 2 === 0,
    dur: 60 + i * 14
  })), []);
  return (
    <div className="bg-decor" aria-hidden="true">
      {dots.map((d, i) =>
      <span key={i} className={"dot" + (d.gold ? " g" : "")} style={{
        left: d.x + "%", top: d.y + "%",
        width: d.s + "px", height: d.s + "px",
        animationDelay: d.d + "s"
      }} />
      )}
      {rings.map((r, i) =>
      <div key={i} className={"ring" + (r.gold ? " g" : "")} style={{
        left: r.x + "%", top: r.y + "%",
        width: r.size + "px", height: r.size + "px",
        marginLeft: -r.size / 2 + "px", marginTop: -r.size / 2 + "px",
        animationDuration: r.dur + "s"
      }} />
      )}
      <svg className="wires" viewBox="0 0 1440 900" preserveAspectRatio="none">
        <path d="M-50 80 Q200 60 380 140 T780 100 T1180 180 T1500 120" />
        <path d="M-50 820 Q280 760 520 800 T940 760 T1500 820" className="gold" />
        <path d="M-50 420 Q200 380 420 460 T820 420 T1500 480" />
        <path d="M120 -20 Q160 200 130 380 T180 720 T140 920" className="gold" />
      </svg>
    </div>);

};

const App = () => {
  const [loaded, setLoaded] = React.useState(false);
  const [portalBgReady, setPortalBgReady] = React.useState(false);
  const [enterRequested, setEnterRequested] = React.useState(false);
  const [lang, setLang] = React.useState("fa");
  const [muted, setMuted] = React.useState(false);
  const [active, setActive] = React.useState("dashboard");
  const [stack, setStack] = React.useState([]); // modal stack
  const [autoTimer, setAutoTimer] = React.useState(true);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const session = useSession();
  const [authOpen, setAuthOpen] = React.useState(false);
  const [authIntent, setAuthIntent] = React.useState(null);
  const [nudge, setNudge] = React.useState(false);
  const nudgeShownRef = React.useRef(false);

  React.useEffect(() => {
    const img = new Image();
    img.onload = () => setPortalBgReady(true);
    img.onerror = () => setPortalBgReady(true);
    img.src = "uploads/portal-stars-bg-full.jpg";
  }, []);

  React.useEffect(() => {
    if (enterRequested && portalBgReady) setLoaded(true);
  }, [enterRequested, portalBgReady]);

  // Auto-dismiss the loader after 6s once the portal background is ready.
  React.useEffect(() => {
    if (!autoTimer) return;
    if (!portalBgReady) return;
    const tm = setTimeout(() => setLoaded(true), 6000);
    return () => clearTimeout(tm);
  }, [autoTimer, portalBgReady]);

  // Fade music when leaving loader
  React.useEffect(() => {
    if (loaded) {
      AudioCtl.fadeMusic(1.2);
    }
  }, [loaded]);

  React.useEffect(() => {
    document.documentElement.dir = lang === "en" ? "ltr" : "rtl";
    document.documentElement.lang = lang;
  }, [lang]);

  React.useEffect(() => {
    const hasOpenModal = stack.length > 0 || authOpen;
    document.documentElement.classList.toggle("modal-open", hasOpenModal);
    document.body.classList.toggle("modal-open", hasOpenModal);
    return () => {
      document.documentElement.classList.remove("modal-open");
      document.body.classList.remove("modal-open");
    };
  }, [stack.length, authOpen]);

  // Auto-fit the right column to the available height so nothing is clipped at 100% zoom.
  React.useEffect(() => {
    const fit = () => {
      const col = document.querySelector(".right-col");
      const inner = document.querySelector(".rc-fit");
      if (!col || !inner) return;
      if (window.innerWidth <= 900) { inner.style.transform = ""; inner.style.width = ""; inner.style.height = ""; return; }
      // measure natural height at full width
      inner.style.transform = "none";
      inner.style.width = "100%";
      inner.style.height = "auto";
      const need = inner.scrollHeight;
      const have = col.clientHeight - 6; // small safety margin against reflow rounding
      let s = Math.min(1, have / Math.max(1, need));
      if (s < 0.999) {
        inner.style.transform = `scale(${s})`;
        inner.style.width = `${100 / s}%`;
        inner.style.height = "auto";
        // correction pass: widening to 100/s% can reflow text taller, so re-measure and adjust
        let measured = inner.getBoundingClientRect().height;
        if (measured > have) {
          s = Math.max(0.5, s * (have / measured));
          inner.style.transform = `scale(${s})`;
          inner.style.width = `${100 / s}%`;
          measured = inner.getBoundingClientRect().height;
          if (measured > have) s = Math.max(0.5, s * (have / measured)), inner.style.transform = `scale(${s})`, inner.style.width = `${100 / s}%`;
        }
      } else {
        inner.style.transform = "";
        inner.style.width = "";
        inner.style.height = "100%";
      }
    };
    const raf = requestAnimationFrame(fit);
    const t1 = setTimeout(fit, 350);
    const t2 = setTimeout(fit, 1200);
    window.addEventListener("resize", fit);
    return () => { cancelAnimationFrame(raf); clearTimeout(t1); clearTimeout(t2); window.removeEventListener("resize", fit); };
  }, [lang, loaded]);

  // First-gesture audio init: any pointerdown anywhere starts the context.
  React.useEffect(() => {
    const handler = () => {
      if (!AudioCtl.isInited()) {
        AudioCtl.initOnGesture();
        AudioCtl.setMuted(false);
        AudioCtl.startPad();
      }
    };
    window.addEventListener("pointerdown", handler, { once: true });
    return () => window.removeEventListener("pointerdown", handler);
  }, []);

  const enterDashboard = () => {
    AudioCtl.initOnGesture();
    AudioCtl.setMuted(false);
    AudioCtl.startPad();
    AudioCtl.click();
    if (portalBgReady) setLoaded(true);
    else setEnterRequested(true);
    setAutoTimer(false);
  };

  const toggleMute = () => {
    AudioCtl.initOnGesture();
    const nowMuted = AudioCtl.toggle();
    setMuted(nowMuted);
    if (!nowMuted) AudioCtl.click();
  };

  // Soft signup nudge: show once per session, respect a 24h dismissal.
  const maybeNudge = () => {
    if (nudgeShownRef.current) return;
    let until = 0;
    try {until = +localStorage.getItem("shahdad_nudge_dismiss") || 0;} catch (e) {}
    if (Date.now() < until) return;
    nudgeShownRef.current = true;
    setTimeout(() => setNudge(true), 700);
  };
  const closeNudge = () => {
    setNudge(false);
    try {localStorage.setItem("shahdad_nudge_dismiss", String(Date.now() + 86400000));} catch (e) {}
  };

  const openModule = (id) => {
    const moduleId = canonicalModuleId(id);
    const route = moduleRoute(moduleId);
    if (route) {
      window.location.assign(route);
      return;
    }
    AudioCtl.open();
    setStack((s) => s.includes(moduleId) ? s : [...s, moduleId]);
    if (session && session.isGuest && moduleId !== "aiChat" && moduleId !== "plans" && moduleId !== "wallet") maybeNudge();
  };
  const requestAuth = (returnTo = null, mode = "login") => {
    const requestedModuleId = typeof returnTo === "string"
      ? returnTo
      : returnTo && typeof returnTo.moduleId === "string"
        ? returnTo.moduleId
        : null;
    const safeReturn = requestedModuleId && window.MODULES?.[requestedModuleId]
      ? {
          moduleId: requestedModuleId,
          detail: typeof returnTo === "object" && returnTo ? returnTo.detail ?? null : null
        }
      : null;
    setAuthIntent({
      mode: mode === "signup" ? "signup" : "login",
      returnTo: safeReturn
    });
    setAuthOpen(true);
  };
  const closeAuth = () => {
    setAuthOpen(false);
    setAuthIntent(null);
  };
  // Bridge so module views (e.g. the ecosystem map) can open sibling modules.
  window.__openModule = openModule;
  window.__requestAuth = requestAuth;
  React.useEffect(() => {
    const requestedModuleId = new URLSearchParams(window.location.search).get("module");
    if (!requestedModuleId) return undefined;
    const moduleId = canonicalModuleId(requestedModuleId);
    const route = moduleRoute(moduleId);
    if (route) {
      window.location.replace(route);
      return undefined;
    }
    const openRequestedModule = () => {
      if (!window.MODULES?.[moduleId]) return false;
      setStack((s) => s.includes(moduleId) ? s : [...s, moduleId]);
      return true;
    };
    if (openRequestedModule()) return undefined;
    const timer = window.setInterval(() => {
      if (openRequestedModule()) window.clearInterval(timer);
    }, 50);
    return () => window.clearInterval(timer);
  }, []);
  const closeId = (id) => {
    AudioCtl.close();
    setStack((s) => s.filter((x) => x !== id));
  };

  return (
    <div className="app">
      <Decor />
      <Loading done={loaded} onEnter={enterDashboard} />

      <TopBar lang={lang} setLang={setLang}
      muted={muted} toggleMute={toggleMute} onOpen={openModule}
      onAuth={() => { AudioCtl.click(); requestAuth(null, "login"); }}
      menuOpen={menuOpen} setMenuOpen={setMenuOpen}
      session={session} />

      <main className="main">
        <div className="portal-area">
          <Portal lang={lang} onOpen={openModule} muted={muted} />
        </div>

        <div className="right-col">
          <div className="rc-fit">
            <button className="eco-card-cta" onClick={() => {AudioCtl.open();openModule("ecosystem");}}>
              <Ic.chip size={18} />
              <div className="ecc-txt">
                <span className="ecc-title">{lang === "fa" ? "کاوش کامل اکوسیستم" : lang === "ar" ? "استكشف النظام الكامل" : "Explore the full ecosystem"}</span>
                <span className="ecc-meta">{lang === "fa" ? "۵ لایه · ۵۳ ماژول هوشمند" : lang === "ar" ? "٥ طبقات · ٥٣ وحدة" : "5 layers · 53 modules"}</span>
              </div>
              <Ic.chevL size={15} />
            </button>

            <QuickActions lang={lang} onOpen={openModule} />

            <div className="bottom-row">
              <StatsCard lang={lang} />
              <CalCard lang={lang} onOpen={openModule} session={session} />
            </div>
          </div>
        </div>
      </main>

      <div className="mobile-footer">
        <button className="mfoot-btn" onClick={() => {AudioCtl.open();openModule("about");}}>
          <Ic.info size={16} />
          <span>{lang === "fa" ? "درباره ما" : lang === "ar" ? "عن شهداد" : "About Us"}</span>
        </button>
      </div>

      {stack.map((id, index) => {
        const mod = window.MODULES?.[id];
        if (!mod) return null;
        const View = mod.View;
        const baseSub = mod.s ? mod.s[lang] || mod.s.en : "";
        const sceneSub = mod.sceneLabel ? mod.sceneLabel[lang] || mod.sceneLabel.en : "";
        const modalSub = [baseSub, sceneSub].filter(Boolean).join(" · ");
        return (
          <Modal key={id} title={mod.t[lang] || mod.t.en} sub={modalSub}
            className={["clock","calendar"].includes(id) ? "calendar-modal" : ["lawyer","bookLawyer","expert"].includes(id) ? "lawyer-modal" : id === "aiChat" ? "ai-chat-modal" : id === "profile" ? "profile-modal" : id === "plans" ? "plans-modal" : id === "wallet" ? "wallet-modal" : id === "communications" ? "communications-modal" : ""}
          iconKey={mod.iconKey} onClose={() => closeId(id)}
          isTopMost={index === stack.length - 1 && !authOpen}>
            <View
              lang={lang}
              mod={mod}
              session={session}
              onOpen={openModule}
              onRequireAuth={(detail = null) => {
                AudioCtl.click();
                requestAuth({ moduleId: id, detail }, "login");
              }}
            />
          </Modal>);

      })}

      {authOpen &&
      <Modal iconKey="user"
      className="auth-modal"
      title={lang === "fa" ? "ورود یا ساخت حساب" : lang === "ar" ? "تسجيل الدخول أو إنشاء حساب" : "Sign in or create an account"}
      sub={lang === "fa" ? "احراز هویت امن، بازیابی حساب و ادامه به‌عنوان مهمان" : lang === "ar" ? "مصادقة آمنة واستعادة الحساب والمتابعة كضيف" : "Secure authentication, account recovery and guest access"}
      isTopMost={true}
      onClose={closeAuth}>
        <AuthCenterView
          lang={lang}
          initialMode={authIntent?.mode || "login"}
          returnTo={authIntent?.returnTo || null}
          onGuest={closeAuth}
        />
      </Modal>}

      {nudge && session && session.isGuest &&
      <GuestNudge lang={lang}
      onSignup={() => {closeNudge();requestAuth(null, "signup");}}
      onClose={closeNudge} />}
    </div>);

};

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