/* jedai-app.jsx — top-level shell, auth gate, view router. */

(function () {
  const { loadState, saveState } = window.JEDAI_DATA;
  const { Icon } = window.JEDAI_ICONS;

  async function apiFetch(url, options = {}) {
    const response = await fetch(url, {
      credentials: "include",
      headers: {
        "Content-Type": "application/json",
        ...(options.headers || {})
      },
      ...options
    });
    const text = await response.text();
    let payload = {};
    try {
      payload = text ? JSON.parse(text) : {};
    } catch (error) {
      payload = { error: text };
    }
    if (!response.ok) {
      throw new Error(payload.error || "Request failed");
    }
    return payload;
  }

  function App() {
    const [state, setState] = React.useState(loadState);
    const [teacher, setTeacher] = React.useState(null);
    const [serverReady, setServerReady] = React.useState(false);
    const [authMode, setAuthMode] = React.useState("login");
    const [authForm, setAuthForm] = React.useState({ name: "", email: "", password: "" });
    const [authError, setAuthError] = React.useState("");
    const [syncStatus, setSyncStatus] = React.useState("Checking account…");
    const [view, setView] = React.useState("gallery");       // "gallery" | "decodable" | ...
    const [toast, setToast] = React.useState(null);
    const [tweaks, setTweaks] = React.useState(() => window.JEDAI_TWEAK_DEFAULTS);

    /* Listen for dev-panel tweak changes via postMessage (shared protocol) */
    React.useEffect(() => {
      function onMsg(e) {
        const d = e.data;
        if (d && d.type === "__edit_mode_set_keys" && d.edits) {
          setTweaks((prev) => ({ ...prev, ...d.edits }));
        }
      }
      window.addEventListener("message", onMsg);
      return () => window.removeEventListener("message", onMsg);
    }, []);

    /* Apply theme/motion to body */
    React.useEffect(() => {
      document.body.setAttribute("data-theme", tweaks.theme);
      document.body.setAttribute("data-motion", tweaks.motion < 3 ? "low" : "normal");
    }, [tweaks.theme, tweaks.motion]);

    /* Persist locally + sync to server when logged in */
    React.useEffect(() => {
      saveState(state);
      if (!teacher || !serverReady) return;
      clearTimeout(window.__jedaiSaveTimer);
      window.__jedaiSaveTimer = setTimeout(async () => {
        try {
          await apiFetch("/api/jobs", {
            method: "PUT",
            body: JSON.stringify({ jobs: state.jobs })
          });
          setSyncStatus("Synced");
        } catch (err) {
          setSyncStatus("Sync failed — " + (err.message || "?"));
        }
      }, 800);
    }, [state, teacher, serverReady]);

    /* Boot: try to fetch /api/auth/me and load saved jobs */
    React.useEffect(() => {
      let cancelled = false;
      (async () => {
        try {
          const me = await apiFetch("/api/auth/me");
          if (cancelled) return;
          setTeacher(me.teacher);
          await loadJobsFromServer();
          setServerReady(true);
          setSyncStatus("Loaded from Cloudflare");
        } catch (err) {
          if (!cancelled) {
            setTeacher(false);
            setServerReady(false);
            setSyncStatus("Sign in to sync");
          }
        }
      })();
      return () => { cancelled = true; };
    }, []);

    async function loadJobsFromServer() {
      try {
        const result = await apiFetch("/api/jobs");
        const cloudJobs = Array.isArray(result.jobs) ? result.jobs : [];
        setState((prev) => ({
          ...prev,
          jobs: cloudJobs.length ? cloudJobs : prev.jobs
        }));
      } catch (err) { /* ignore — handled by caller */ }
    }

    const submitAuth = async (event) => {
      event.preventDefault();
      setAuthError("");
      setSyncStatus(authMode === "signup" ? "Creating account…" : "Signing in…");
      try {
        const payload = { email: authForm.email, password: authForm.password };
        if (authMode === "signup") payload.name = authForm.name;
        const result = await apiFetch(authMode === "signup" ? "/api/auth/signup" : "/api/auth/login", {
          method: "POST",
          body: JSON.stringify(payload)
        });
        setTeacher(result.teacher);
        await loadJobsFromServer();
        setServerReady(true);
        setAuthForm({ name: "", email: "", password: "" });
        showToast(authMode === "signup" ? "Account ready" : "Welcome back");
        setSyncStatus("Synced");
      } catch (err) {
        setAuthError(err.message || "Could not sign in.");
        setSyncStatus("Sign in to sync");
      }
    };

    const signOut = async () => {
      try {
        await apiFetch("/api/auth/logout", { method: "POST" });
      } catch (e) {}
      setTeacher(false);
      setServerReady(false);
      setSyncStatus("Sign in to sync");
      showToast("Signed out");
    };

    function showToast(text) {
      setToast({ text, id: Date.now() });
      clearTimeout(window.__jedaiToastTimer);
      window.__jedaiToastTimer = setTimeout(() => setToast(null), 2200);
    }

    function setJobs(updater) {
      setState((prev) => {
        const next = typeof updater === "function" ? updater(prev.jobs) : updater;
        return { ...prev, jobs: Array.isArray(next) ? next : prev.jobs };
      });
    }

    /* ----- AUTH GATE ----- */

    if (teacher === null) {
      // booting
      return (
        <div className="auth-page">
          {tweaks.showScene && <window.JedaiScene motion={tweaks.motion} showScene={tweaks.showScene} theme={tweaks.theme}/>}
          <div className="auth-card">
            <div className="brand auth-brand">
              <div className="brand-mark">{Icon.brand()}</div>
              <div>
                <h1>JEDAI Tools</h1>
                <div className="subline"><span className="pin"/>Loading…</div>
              </div>
            </div>
          </div>
        </div>
      );
    }

    if (teacher === false) {
      const isSignup = authMode === "signup";
      return (
        <div className="auth-page">
          {tweaks.showScene && <window.JedaiScene motion={tweaks.motion} showScene={tweaks.showScene} theme={tweaks.theme}/>}
          <div className="auth-card">
            <div className="brand auth-brand">
              <div className="brand-mark">{Icon.brand()}</div>
              <div>
                <h1>JEDAI Tools</h1>
                <div className="subline">
                  <span className="pin"/>
                  Just Educational AI Tools
                </div>
              </div>
            </div>

            <form onSubmit={submitAuth}>
              <div className="auth-tabs">
                <button
                  type="button"
                  className={!isSignup ? "active" : ""}
                  onClick={() => setAuthMode("login")}
                >
                  Sign in
                </button>
                <button
                  type="button"
                  className={isSignup ? "active" : ""}
                  onClick={() => setAuthMode("signup")}
                >
                  Create account
                </button>
              </div>

              {isSignup && (
                <label className="auth-field">
                  <span>Name</span>
                  <input
                    value={authForm.name}
                    onChange={(e) => setAuthForm({ ...authForm, name: e.target.value })}
                    autoComplete="name"
                    placeholder="Teacher name"
                  />
                </label>
              )}
              <label className="auth-field">
                <span>Email</span>
                <input
                  value={authForm.email}
                  onChange={(e) => setAuthForm({ ...authForm, email: e.target.value })}
                  autoComplete="email"
                  type="email"
                  placeholder="teacher@example.com"
                  required
                />
              </label>
              <label className="auth-field">
                <span>Password</span>
                <input
                  value={authForm.password}
                  onChange={(e) => setAuthForm({ ...authForm, password: e.target.value })}
                  autoComplete={isSignup ? "new-password" : "current-password"}
                  type="password"
                  minLength="8"
                  placeholder="At least 8 characters"
                  required
                />
              </label>

              {authError && <div className="auth-error">{authError}</div>}

              <button className="tool-btn auth-submit" type="submit">
                {isSignup ? "Create account" : "Sign in"}
              </button>

              <div className="auth-note">{syncStatus}</div>
            </form>
          </div>
        </div>
      );
    }

    /* ----- AUTHENTICATED APP ----- */

    return (
      <>
        {tweaks.showScene && <window.JedaiScene motion={tweaks.motion} showScene={tweaks.showScene} theme={tweaks.theme}/>}
        <div className="app">
          <div className="topbar">
            <div className="brand">
              <div className="brand-mark">{Icon.brand()}</div>
              <div>
                <h1>JEDAI Tools</h1>
                <div className="subline">
                  <span className="pin"/>
                  Just Educational AI Tools
                </div>
              </div>
            </div>

            <div className="toolbar">
              {view !== "gallery" && (
                <button className="tool-btn tb-back" onClick={() => setView("gallery")}>
                  {Icon.back()}Back to tools
                </button>
              )}
              <button className="tool-btn account-chip" disabled>
                {teacher.name || teacher.email}
              </button>
              <button className="tool-btn" onClick={signOut} title="Sign out">
                {Icon.logout()}
              </button>
            </div>
          </div>

          <div className="sync-line">{syncStatus}</div>

          {view === "gallery" && (
            <window.JedaiGallery onPick={(toolId) => setView(toolId)}/>
          )}
          {view === "decodable" && (
            <window.JedaiDecodable
              apiFetch={apiFetch}
              teacher={teacher}
              tweaks={tweaks}
              showToast={showToast}
              jobs={state.jobs}
              setJobs={setJobs}
            />
          )}
        </div>

        {toast && (
          <div className="toast show">
            {Icon.sparkle()}
            <span>{toast.text}</span>
          </div>
        )}

        <window.JedaiTweaks/>
      </>
    );
  }

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