// Gestopia — app shell with real Supabase auth state
const { useState: useStateApp, useEffect: useEffectApp } = React;

const sb = () => window.__supabase;

// Tweak defaults
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "mode": "dark",
  "accent": "#FF4D6D",
  "heroScale": 1,
  "heroMedia": "motion"
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = [
  "#FF4D6D",
  "#FF6A00",
  "#00E5A0",
  "#4F8BFF",
  "#B26BFF",
  "#FFD400",
];

function App() {
  const [view, setView] = useStateApp("landing");
  const [infoTopic, setInfoTopic] = useStateApp("fonctionnalites");
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [session, setSession] = useStateApp(null);
  const [authReady, setAuthReady] = useStateApp(false);
  const [recoveryMode, setRecoveryMode] = useStateApp(false);

  const goToInfo = (topicId) => {
    setInfoTopic(topicId);
    setView("info");
  };

  // ── Auth state listener ──
  useEffectApp(() => {
    // 1. Check existing session
    sb().auth.getSession().then(({ data: { session: s } }) => {
      if (s) {
        setSession(s);
        // Don't auto-redirect to success on page load if user is already logged in
        // and browsing the landing. Only redirect if they're on a login/signup page.
      }
      setAuthReady(true);
    });

    // 2. Listen for auth changes (login, logout, token refresh, recovery)
    const { data: { subscription } } = sb().auth.onAuthStateChange((event, s) => {
      setSession(s);

      if (event === "PASSWORD_RECOVERY") {
        // User clicked a password reset link — show the update-password form
        setRecoveryMode(true);
        setView("update-password");
      } else if (event === "SIGNED_IN") {
        if (recoveryMode) {
          return;
        }
        // Successful login or OAuth callback — go to dashboard
        setView("dashboard");
      } else if (event === "SIGNED_OUT") {
        setSession(null);
        setView("landing");
      }
    });

    return () => subscription.unsubscribe();
  }, []);

  // ── Logout handler ──
  async function handleLogout() {
    await sb().auth.signOut();
    setSession(null);
    setRecoveryMode(false);
    setView("landing");
  }

  // ── Password updated handler ──
  function handlePasswordUpdated() {
    setRecoveryMode(false);
    setView("success");
  }

  // Expose goToInfo for footer
  useEffectApp(() => {
    window.__goToInfo = goToInfo;
    return () => { delete window.__goToInfo; };
  }, []);

  // Apply mode + accent
  useEffectApp(() => {
    document.documentElement.dataset.mode = tweaks.mode;
    document.documentElement.style.setProperty("--accent", tweaks.accent);
    document.documentElement.style.setProperty(
      "--accent-soft",
      hexToRgba(tweaks.accent, tweaks.mode === "light" ? 0.10 : 0.14)
    );
  }, [tweaks.mode, tweaks.accent]);

  // Scroll to top on view change
  useEffectApp(() => {
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [view]);

  // Scroll-reveal observer
  useEffectApp(() => {
    if (!("IntersectionObserver" in window)) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.15, rootMargin: "0px 0px -40px 0px" }
    );
    const scan = () => {
      document.querySelectorAll(".reveal:not(.in)").forEach((el) => io.observe(el));
    };
    const raf = requestAnimationFrame(scan);
    const mo = new MutationObserver(scan);
    mo.observe(document.body, { childList: true, subtree: true });
    return () => {
      cancelAnimationFrame(raf);
      io.disconnect();
      mo.disconnect();
    };
  }, [view]);

  // ── Loading state while checking auth ──
  if (!authReady) {
    return (
      <div style={{
        minHeight: "100vh",
        background: "var(--bg)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}>
        <div style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          gap: 20,
        }}>
          <Logo size={32} />
          <div className="dash-pulse" style={{
            width: 32, height: 3, borderRadius: 999,
            background: "var(--accent)",
          }} />
        </div>
      </div>
    );
  }

  return (
    <>
      {view === "landing" && (
        <>
          <Nav view={view} setView={setView} session={session} />
          <Landing setView={setView} tweaks={tweaks} goToInfo={goToInfo} />
        </>
      )}
      {view === "login" && <Login setView={setView} />}
      {view === "signup" && <Signup setView={setView} />}
      {view === "forgot" && <ForgotPassword setView={setView} />}
      {view === "check-email" && <CheckEmail setView={setView} />}
      {view === "update-password" && (
        <UpdatePassword setView={setView} onDone={handlePasswordUpdated} />
      )}
      {view === "dashboard" && (
        <DashboardApp session={session} onLogout={handleLogout} />
      )}
      {view === "info" && (
        <InfoPage
          topicId={infoTopic}
          setView={setView}
          setTopicId={setInfoTopic}
        />
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Apparence">
          <TweakRadio
            label="Mode"
            value={tweaks.mode}
            onChange={(v) => setTweak("mode", v)}
            options={[
              { label: "Dark", value: "dark" },
              { label: "Light", value: "light" },
            ]}
          />
          <TweakColor
            label="Couleur d'accent"
            value={tweaks.accent}
            onChange={(v) => setTweak("accent", v)}
            options={ACCENT_OPTIONS}
          />
        </TweakSection>

        <TweakSection label="Hero">
          <TweakSlider
            label="Échelle typo hero"
            min={70}
            max={130}
            step={5}
            unit="%"
            value={Math.round(tweaks.heroScale * 100)}
            onChange={(v) => setTweak("heroScale", v / 100)}
          />
          <TweakSelect
            label="Visuel hero"
            value={tweaks.heroMedia}
            onChange={(v) => setTweak("heroMedia", v)}
            options={[
              { label: "Motion abstrait (grille + glow)", value: "motion" },
              { label: "Mockup dashboard", value: "mockup" },
            ]}
          />
        </TweakSection>

        <TweakSection label="Navigation">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }}>
            {[
              ["landing", "Home"],
              ["login", "Login"],
              ["signup", "Sign-up"],
              ["info", "Info"],
            ].map(([v, label]) => (
              <button
                key={v}
                className="btn btn-sm"
                style={{
                  background: view === v ? "var(--accent)" : "var(--surface)",
                  color: view === v ? "#fff" : "var(--fg)",
                  border: "1px solid var(--line-strong)",
                  justifyContent: "center",
                  fontSize: 12,
                }}
                onClick={() => setView(v)}
              >
                {label}
              </button>
            ))}
          </div>
          {session && (
            <button
              className="btn btn-sm"
              style={{
                marginTop: 8,
                width: "100%",
                background: "var(--surface)",
                border: "1px solid var(--line-strong)",
                justifyContent: "center",
                fontSize: 12,
                color: "var(--accent)",
              }}
              onClick={handleLogout}
            >
              Déconnexion ({session.user?.email?.split("@")[0]})
            </button>
          )}
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

// ─────────────────────────────────────────────────────────────
function hexToRgba(hex, alpha) {
  const m = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex || "");
  if (!m) return `rgba(220,80,98,${alpha})`;
  return `rgba(${parseInt(m[1], 16)},${parseInt(m[2], 16)},${parseInt(m[3], 16)},${alpha})`;
}

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