// ============== app + router + tweaks ==============

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "density": "default",
  "typePair": "geist-instrument",
  "invert": false
}/*EDITMODE-END*/;

const TYPE_PAIRS = {
  "geist-instrument": { sans: "'Geist', system-ui, sans-serif", serif: "'Instrument Serif', serif", label: "Geist + Instrument" },
  "geist-fraunces":   { sans: "'Geist', system-ui, sans-serif", serif: "'Fraunces', serif",         label: "Geist + Fraunces" },
  "ibm-instrument":   { sans: "'IBM Plex Sans', sans-serif",    serif: "'Instrument Serif', serif", label: "IBM Plex + Instrument" },
};

const ROUTES = ["home", "jobs", "companies", "candidates", "about", "events", "blog", "contact",
                "login", "register", "dashboard", "admin", "forgot", "reset", "accept-invite", "roles"];

function parseHash() {
  // Supports: #home  |  #roles/W3J-0421  |  #reset?token=...  |  #accept-invite?token=...
  const raw = window.location.hash.slice(1);
  if (!raw) return { route: "home", arg: null, query: {} };
  const [pathPart, queryPart = ""] = raw.split("?");
  const segments = pathPart.split("/");
  const route = segments[0];
  const arg = segments.slice(1).join("/") || null;
  const query = {};
  if (queryPart) {
    for (const pair of queryPart.split("&")) {
      const [k, v] = pair.split("=");
      query[decodeURIComponent(k)] = decodeURIComponent(v || "");
    }
  }
  return { route: ROUTES.includes(route) ? route : "home", arg, query };
}

function Shell() {
  const [hashState, setHashState] = React.useState(() => parseHash());
  const { route, arg: hashArg, query: hashQuery } = hashState;
  const [routeArg, setRouteArg] = React.useState(null);
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const { user, loading: authLoading } = useAuth();

  const go = (id, arg = null) => {
    if (id === "events") {
      window.open("https://lu.ma/web3joe", "_blank", "noopener");
      return;
    }
    setRouteArg(arg);
    const hash = arg && arg.publicId ? `${id}/${arg.publicId}` : id;
    setHashState({ route: id, arg: arg?.publicId || null, query: {} });
    window.location.hash = hash;
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  React.useEffect(() => {
    const onHash = () => setHashState(parseHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  React.useEffect(() => {
    const root = document.documentElement;
    root.style.removeProperty("--accent");
    root.style.removeProperty("--accent-fg");
    root.style.removeProperty("--accent-soft");
    root.setAttribute("data-density", tweaks.density);
    root.setAttribute("data-theme", tweaks.invert ? "light" : "dark");
    const tp = TYPE_PAIRS[tweaks.typePair] || TYPE_PAIRS["geist-instrument"];
    root.style.setProperty("--sans", tp.sans);
    root.style.setProperty("--serif", tp.serif);
  }, [tweaks]);

  // Auth gates — redirect AFTER auth load completes
  React.useEffect(() => {
    if (authLoading) return;
    if ((route === "dashboard" || route === "admin") && !user) {
      go("login");
    } else if (route === "dashboard" && user && user.role !== "candidate") {
      go("admin");
    } else if (route === "admin" && user && user.role === "candidate") {
      go("dashboard");
    }
  }, [route, user, authLoading]);

  let Page = null;
  if (route === "home") Page = <Landing go={go} />;
  else if (route === "jobs") Page = <Jobs go={go} focusId={routeArg?.id} />;
  else if (route === "roles" && hashArg) Page = <window.RoleDetailPage publicId={hashArg} go={go} />;
  else if (route === "companies") Page = <Companies go={go} />;
  else if (route === "candidates") Page = <Candidates go={go} />;
  else if (route === "about") Page = <About go={go} />;
  else if (route === "blog") Page = <Blog go={go} />;
  else if (route === "contact") Page = <Contact go={go} />;
  else if (route === "login") Page = <AuthPage mode="login" go={go} />;
  else if (route === "register") Page = <AuthPage mode="register" go={go} />;
  else if (route === "forgot") Page = <window.ForgotPasswordPage go={go} />;
  else if (route === "reset") Page = <window.ResetPasswordPage token={hashQuery.token} go={go} />;
  else if (route === "accept-invite") Page = <window.AcceptInvitePage token={hashQuery.token} go={go} />;
  else if (route === "dashboard") Page = user ? <CandidateDashboard go={go} /> : <AuthPage mode="login" go={go} />;
  else if (route === "admin") Page = (user && user.role !== "candidate") ? <RecruiterDashboard go={go} /> : <AuthPage mode="login" go={go} />;
  else Page = <Landing go={go} />;

  return (
    <div data-screen-label={route}>
      <Nav route={route} go={go} light={!!tweaks.invert} onToggleTheme={() => setTweak("invert", !tweaks.invert)} user={user} />
      {Page}
      <Footer go={go} />

      <window.TweaksPanel title="Tweaks">
        <window.TweakSection label="Theme" />
        <window.TweakToggle label="Light mode" value={tweaks.invert} onChange={(v) => setTweak("invert", v)} />
        <window.TweakSection label="Typography" />
        <window.TweakSelect
          label="Type pair" value={tweaks.typePair}
          onChange={(v) => setTweak("typePair", v)}
          options={Object.entries(TYPE_PAIRS).map(([k, v]) => ({ value: k, label: v.label }))}
        />
        <window.TweakSection label="Layout" />
        <window.TweakRadio label="Density" value={tweaks.density}
          onChange={(v) => setTweak("density", v)} options={["compact", "default", "cozy"]} />
        <window.TweakSection label="Jump to" />
        <window.TweakButton label="Home" onClick={() => go("home")} />
        <window.TweakButton label="Job board" onClick={() => go("jobs")} />
        <window.TweakButton label="Dashboard" onClick={() => go("dashboard")} secondary />
        <window.TweakButton label="Admin" onClick={() => go("admin")} secondary />
      </window.TweaksPanel>
    </div>
  );
}

function AuthPage({ mode, go }) {
  const { user } = useAuth();
  React.useEffect(() => {
    if (user) go(user.role === "candidate" ? "dashboard" : "admin");
  }, [user]);

  return (
    <main>
      <section className="page-hero">
        <div className="shell">
          <Eyebrow>{mode === "login" ? "Sign in" : "Create account"}</Eyebrow>
          <h1 style={{ marginTop: 24 }}>
            {mode === "login" ? <>Welcome <em>back.</em></> : <>Join the <em>network.</em></>}
          </h1>
          <p className="lede" style={{ marginTop: 28, maxWidth: 540 }}>
            {mode === "login"
              ? "Sign in to your candidate dashboard or recruiter control room."
              : "Build a private candidate file. We only share it with companies you'd actually want to work for."}
          </p>
        </div>
      </section>
      <section className="section">
        <div className="shell" style={{ maxWidth: 520 }}>
          <window.GoogleButton />
          <AuthForm mode={mode} />
          <div className="modal-switch" style={{ marginTop: 24 }}>
            {mode === "login"
              ? <>New here? <a href="#register" onClick={(e) => { e.preventDefault(); go("register"); }}>Create an account</a> · <a href="#forgot" onClick={(e) => { e.preventDefault(); go("forgot"); }}>Forgot password?</a></>
              : <>Have an account? <a href="#login" onClick={(e) => { e.preventDefault(); go("login"); }}>Sign in</a></>}
          </div>
        </div>
      </section>
    </main>
  );
}

function AuthForm({ mode }) {
  const { login, register } = useAuth();
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [fullName, setFullName] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr(""); setBusy(true);
    try {
      if (mode === "login") await login(email, password);
      else await register(email, password, fullName);
    } catch (ex) {
      setErr(ex.message);
    } finally { setBusy(false); }
  };

  return (
    <form className="form-grid" onSubmit={submit}>
      <div className="form-section">
        {mode === "register" && (
          <label className="field"><span className="field-label">Full name</span>
            <input value={fullName} onChange={(e) => setFullName(e.target.value)} required maxLength={160} /></label>
        )}
        <label className="field"><span className="field-label">Email</span>
          <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required /></label>
        <label className="field"><span className="field-label">Password</span>
          <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={mode === "register" ? 10 : 1} />
          {mode === "register" && <span className="field-hint">Minimum 10 characters.</span>}</label>
        {err && <div className="form-error">{err}</div>}
        <button type="submit" className="btn btn--primary" disabled={busy}>
          {busy ? "…" : (mode === "login" ? "Sign in" : "Create account")} <Icon.Arrow />
        </button>
      </div>
    </form>
  );
}

function App() {
  return <AuthProvider><Shell /></AuthProvider>;
}

const extraFonts = document.createElement("link");
extraFonts.rel = "stylesheet";
extraFonts.href = "https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,400;0,9..144,500;0,9..144,600;1,9..144,400&family=IBM+Plex+Sans:wght@400;500;600;700&display=swap";
document.head.appendChild(extraFonts);

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