// app.jsx — root component, routing, auth, companion wiring

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "direction": "console",
  "theme": "auto",
  "accent": "terracotta"
}/*EDITMODE-END*/;

// Helper for authenticated API calls
async function apiFetch(url, options = {}) {
  if (!window.sb) throw new Error('Auth non configurée');
  const { data: { session } } = await window.sb.auth.getSession();
  if (!session) throw new Error('Non authentifié');
  const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${session.access_token}`,
    ...options.headers
  };
  return fetch(url, { ...options, headers });
}
window.apiFetch = apiFetch;

const IS_MARKETING = window.location.hostname === 'www.fmautoscript.com' || window.location.hostname === 'fmautoscript.com';
const APP_URL = 'https://www.fmautoscript.app';
const MARKETING_URL = 'https://www.fmautoscript.com';

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = React.useState(IS_MARKETING ? "market.home" : "market.home");
  const [companion, setCompanion] = React.useState(false);
  const [user, setUser] = React.useState(null);
  const [authLoading, setAuthLoading] = React.useState(true);
  const [sidebarOpen, setSidebarOpen] = React.useState(false);
  const [scriptCount, setScriptCount] = React.useState(null);
  const [loadedScript, setLoadedScript] = React.useState(null);

  const [fmVersions, setFmVersions] = React.useState(() => {
    try { const s = localStorage.getItem('fmVersions'); return s ? JSON.parse(s) : [{ label: "FileMaker Pro", appName: "FileMaker Pro" }]; }
    catch { return [{ label: "FileMaker Pro", appName: "FileMaker Pro" }]; }
  });
  const [activeFmVersion, setActiveFmVersion] = React.useState(() => {
    return localStorage.getItem('activeFmVersion') || "FileMaker Pro";
  });
  React.useEffect(() => { localStorage.setItem('fmVersions', JSON.stringify(fmVersions)); }, [fmVersions]);
  React.useEffect(() => { localStorage.setItem('activeFmVersion', activeFmVersion); }, [activeFmVersion]);

  // Fetch script count for sidebar badge
  React.useEffect(() => {
    if (!user) { setScriptCount(null); return; }
    const load = async () => {
      try {
        const res = await apiFetch('/api/scripts/history');
        const data = await res.json();
        setScriptCount((data.scripts || []).length);
      } catch { /* silent */ }
    };
    load();
  }, [user, route]);

  // Resolve "auto" theme to system preference
  const resolvedTheme = React.useMemo(() => {
    if (t.theme !== "auto") return t.theme;
    return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
  }, [t.theme]);

  // Listen for system theme changes when in auto mode
  React.useEffect(() => {
    if (t.theme !== "auto") return;
    const mq = window.matchMedia("(prefers-color-scheme: dark)");
    const apply = () => {
      const body = document.body;
      body.classList.remove("theme-light", "theme-dark");
      body.classList.add(mq.matches ? "theme-dark" : "theme-light");
    };
    apply();
    mq.addEventListener("change", apply);
    return () => mq.removeEventListener("change", apply);
  }, [t.theme]);

  // Apply direction + theme + accent as body classes
  React.useEffect(() => {
    const body = document.body;
    body.classList.remove("dir-console", "dir-atelier");
    body.classList.add(`dir-${t.direction}`);
    body.classList.remove("theme-light", "theme-dark");
    body.classList.add(`theme-${t.theme === "auto" ? resolvedTheme : t.theme}`);
    body.classList.remove("accent-terracotta", "accent-indigo", "accent-green", "accent-cyan");
    body.classList.add(`accent-${t.accent}`);
  }, [t.direction, t.theme, t.accent, resolvedTheme]);

  // Auth state management
  React.useEffect(() => {
    if (!window.sb) {
      setAuthLoading(false);
      return;
    }

    const initAuth = async () => {
      try {
        const { data: { session } } = await window.sb.auth.getSession();
        if (session) {
          setUser(session.user);
          setRoute('app.scripts');
        } else if (!IS_MARKETING) {
          setRoute('market.login');
        }
      } catch (e) {
        console.error('Auth check failed:', e);
      }
      setAuthLoading(false);
    };

    const { data: { subscription } } = window.sb.auth.onAuthStateChange((event, session) => {
      if (event === 'SIGNED_IN' && session) {
        setUser(prev => {
          if (!prev) setRoute('app.scripts');
          return session.user;
        });
      } else if (event === 'SIGNED_OUT') {
        setUser(null);
        setRoute('market.home');
      }
    });

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

  // Companion health check
  React.useEffect(() => {
    const check = async () => {
      try {
        const res = await fetch('http://localhost:27184/health', {
          signal: AbortSignal.timeout(2000)
        });
        setCompanion(res.ok);
      } catch {
        setCompanion(false);
      }
    };
    check();
    const interval = setInterval(check, 10000);
    return () => clearInterval(interval);
  }, []);

  const navigate = (r) => {
    if (IS_MARKETING && r.startsWith('app.')) {
      window.location.href = APP_URL;
      return;
    }
    if (r.startsWith('app.') && !user) {
      setRoute('market.login');
      return;
    }
    setRoute(r);
    setTimeout(() => window.scrollTo(0, 0), 0);
  };

  const logout = async () => {
    if (window.sb) await window.sb.auth.signOut();
    setUser(null);
    if (IS_MARKETING) {
      setRoute('market.home');
    } else {
      window.location.href = MARKETING_URL;
    }
  };

  const login = () => navigate('app.scripts');

  // Loading state
  if (authLoading) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh' }}>
        <Logo size={32} />
      </div>
    );
  }

  // ──── ROUTER ────
  let view = null;
  if (route === "market.home")         view = <HomePage navigate={navigate}/>;
  else if (route === "market.login")   view = <LoginPage navigate={navigate} onLogin={login}/>;
  else if (route === "market.signup")  view = <SignupPage navigate={navigate} onLogin={login}/>;
  else if (route === "market.forgot")  view = <ForgotPage navigate={navigate}/>;
  else if (route === "market.404")     view = <FourOhFour navigate={navigate}/>;
  else if (route.startsWith("app.")) {
    if (!user) {
      view = <LoginPage navigate={navigate} onLogin={login}/>;
    } else {
      const toggleSidebar = () => setSidebarOpen(v => !v);
      const closeSidebar = () => setSidebarOpen(false);
      let inner = null;
      const loadToEditor = (s) => { setLoadedScript(s); navigate("app.scripts"); };
      if (route === "app.scripts")    inner = <ScriptsPage companion={companion} onMenuToggle={toggleSidebar} loadedScript={loadedScript} onScriptLoaded={() => setLoadedScript(null)} fmVersion={activeFmVersion} fmVersions={fmVersions} onFmVersionChange={setActiveFmVersion}/>;
      if (route === "app.history")    inner = <HistoryPage onMenuToggle={toggleSidebar} onLoadScript={loadToEditor}/>;
      if (route === "app.community")  inner = <CommunityPage onMenuToggle={toggleSidebar} onLoadScript={loadToEditor}/>;
      if (route === "app.favorites")  inner = <FavoritesPage onMenuToggle={toggleSidebar} onLoadScript={loadToEditor}/>;
      if (route === "app.profile")    inner = <ProfilePage navigate={navigate} user={user} onMenuToggle={toggleSidebar} onUserUpdate={setUser}/>;
      if (route === "app.settings")   inner = <SettingsPage companion={companion} onMenuToggle={toggleSidebar} fmVersions={fmVersions} setFmVersions={setFmVersions} activeFmVersion={activeFmVersion} setActiveFmVersion={setActiveFmVersion}/>;
      view = (
        <div className="app-shell">
          <div className={`sidebar-overlay ${sidebarOpen ? "open" : ""}`} onClick={closeSidebar}/>
          <Sidebar route={route} navigate={navigate} onLogout={logout} open={sidebarOpen} onClose={closeSidebar} scriptCount={scriptCount}/>
          <main className="app-main">{inner}</main>
        </div>
      );
    }
  }

  // Curated accent swatches (4 options)
  const ACCENTS = ["#c2410c", "#5b4ad6", "#2f8e57", "#1b7c9c"];
  const ACCENT_NAMES = ["terracotta", "indigo", "green", "cyan"];

  return (
    <>
      {view}

      <TweaksPanel>
        <TweakSection label="Direction"/>
        <TweakRadio
          label="Style"
          value={t.direction}
          options={["console", "atelier"]}
          onChange={(v) => setTweak("direction", v)}
        />

        <TweakSection label="Apparence"/>
        <TweakRadio
          label="Mode"
          value={t.theme}
          options={["auto", "light", "dark"]}
          onChange={(v) => setTweak("theme", v)}
        />
        <TweakColor
          label="Accent"
          value={ACCENTS[ACCENT_NAMES.indexOf(t.accent)] || ACCENTS[0]}
          options={ACCENTS}
          onChange={(v) => setTweak("accent", ACCENT_NAMES[ACCENTS.indexOf(v)] || "terracotta")}
        />

        <TweakSection label="Navigation"/>
        <TweakSelect
          label="Aller à"
          value={route}
          options={[
            { value: "market.home",   label: "Homepage" },
            { value: "market.login",  label: "Login" },
            { value: "market.signup", label: "Signup" },
            { value: "market.forgot", label: "Mot de passe oublié" },
            { value: "market.404",    label: "404" },
            { value: "app.scripts",   label: "App · Scripts" },
            { value: "app.history",   label: "App · Historique" },
            { value: "app.community", label: "App · Communauté" },
            { value: "app.favorites", label: "App · Favoris" },
            { value: "app.profile",   label: "App · Profil" },
            { value: "app.settings",  label: "App · Paramètres" },
          ]}
          onChange={(v) => navigate(v)}
        />
        <TweakToggle
          label="Companion connecté"
          value={companion}
          onChange={setCompanion}
        />
      </TweaksPanel>
    </>
  );
}

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