// Auth shim — replaces the static design-canvas LoginPage/SignupPage/
// ForgotPasswordPage with versions wired to Supabase (window.proveSupabase).
//
// The visual layout is rebuilt with the same primitives (AuthShell, FormField,
// CoralButton, OrDivider, AuthBrandHeader, AppleButton) so the look matches
// the design exactly — only the behaviour is real.

const { useState: useStateAS } = React;

const _authCardStyle = {
  width: 440, padding: 32, borderRadius: 20,
  background: "rgba(255,255,255,0.03)",
  border: "1px solid rgba(255,255,255,0.08)",
  boxShadow: "0 24px 48px rgba(0,0,0,0.5)",
};
const _authSubStyle = {
  color: "rgba(255,255,255,0.55)", fontSize: 14, margin: 0,
};
const _authLinkStyle = {
  color: "var(--coral)", fontSize: 13, fontWeight: 600,
  textDecoration: "none", cursor: "pointer",
};

function _navigate(hash) {
  window.location.hash = hash;
}

// ─── LOGIN ─────────────────────────────────────────────────────────────
function LoginPageReal({ width, height }) {
  const [email, setEmail] = useStateAS("");
  const [pw, setPw] = useStateAS("");
  const [busy, setBusy] = useStateAS(false);
  const [err, setErr] = useStateAS(null);

  async function submit() {
    if (!email.trim() || !pw) {
      setErr("Enter an email and password");
      return;
    }
    setErr(null);
    setBusy(true);
    try {
      const { error } = await window.proveSupabase.auth.signInWithPassword({
        email: email.trim(),
        password: pw,
      });
      if (error) {
        setErr(error.message);
      } else {
        _navigate("/feed");
      }
    } finally {
      setBusy(false);
    }
  }

  async function loginWithApple() {
    setBusy(true);
    setErr(null);
    const { error } = await window.proveSupabase.auth.signInWithOAuth({
      provider: "apple",
      options: { redirectTo: window.location.origin + "/#/feed" },
    });
    if (error) {
      setBusy(false);
      setErr(error.message);
    }
  }

  return (
    <AuthShell width={width} height={height}>
      <div style={_authCardStyle}>
        <AuthBrandHeader size={36} />
        <h1
          style={{
            fontFamily: "var(--display)",
            fontSize: 40,
            fontWeight: 800,
            letterSpacing: "-0.04em",
            margin: "4px 0 10px",
            textTransform: "uppercase",
            color: "#fff",
            lineHeight: 0.94,
            textAlign: "center",
          }}
        >
          Welcome{" "}
          <span style={{ color: "var(--coral)", fontStyle: "italic", fontWeight: 900 }}>
            back.
          </span>
        </h1>
        <p style={{ ..._authSubStyle, textAlign: "center", marginBottom: 28 }}>
          Pick up where your streak left off.
        </p>

        <div onClick={loginWithApple}>
          <AppleButton full />
        </div>

        <OrDivider />

        <FormField
          label="Email"
          type="email"
          value={email}
          onChange={setEmail}
          placeholder="you@email.com"
        />
        <FormField
          label="Password"
          type="password"
          value={pw}
          onChange={setPw}
          placeholder="••••••••"
          rightHint={
            <a style={_authLinkStyle} onClick={() => _navigate("/forgot")}>
              Forgot password?
            </a>
          }
        />

        {err ? (
          <div
            style={{
              marginTop: 4,
              fontSize: 12,
              color: "var(--coral)",
              fontWeight: 600,
            }}
          >
            {err}
          </div>
        ) : null}

        <div style={{ marginTop: 8 }}>
          <CoralButton full size="lg" onClick={submit}>
            {busy ? "Signing in…" : "Sign in"}
          </CoralButton>
        </div>

        <div
          style={{
            textAlign: "center",
            fontSize: 13,
            color: "var(--text-2)",
            marginTop: 22,
          }}
        >
          New here?{" "}
          <a
            style={{ ..._authLinkStyle, marginLeft: 4 }}
            onClick={() => _navigate("/signup")}
          >
            Create account →
          </a>
        </div>
      </div>
    </AuthShell>
  );
}

// ─── SIGNUP ────────────────────────────────────────────────────────────
function SignupPageReal({ width, height }) {
  const [email, setEmail] = useStateAS("");
  const [pw, setPw] = useStateAS("");
  const [handle, setHandle] = useStateAS("");
  const [busy, setBusy] = useStateAS(false);
  const [err, setErr] = useStateAS(null);

  async function submit() {
    if (!email.trim() || pw.length < 8) {
      setErr("Email + password (8+ chars) required");
      return;
    }
    setErr(null);
    setBusy(true);
    try {
      const { data, error } = await window.proveSupabase.auth.signUp({
        email: email.trim(),
        password: pw,
        options: { data: { username: handle.trim() || undefined } },
      });
      if (error) {
        setErr(error.message);
      } else if (data.session) {
        _navigate("/onboarding/habit");
      } else {
        setErr("Check your inbox to confirm your email, then sign in.");
      }
    } finally {
      setBusy(false);
    }
  }

  return (
    <AuthShell width={width} height={height}>
      <div style={_authCardStyle}>
        <AuthBrandHeader size={36} />
        <h1
          style={{
            fontFamily: "var(--display)",
            fontSize: 40,
            fontWeight: 800,
            letterSpacing: "-0.04em",
            margin: "4px 0 10px",
            textTransform: "uppercase",
            color: "#fff",
            lineHeight: 0.94,
            textAlign: "center",
          }}
        >
          Show{" "}
          <span style={{ color: "var(--coral)", fontStyle: "italic", fontWeight: 900 }}>
            up.
          </span>
        </h1>
        <p style={{ ..._authSubStyle, textAlign: "center", marginBottom: 28 }}>
          Every day. In public.
        </p>

        <AppleButton full label="Sign up with Apple" />

        <OrDivider />

        <FormField
          label="Email"
          type="email"
          value={email}
          onChange={setEmail}
          placeholder="you@email.com"
        />
        <FormField
          label="Handle"
          value={handle}
          onChange={setHandle}
          placeholder="@your-handle"
          hint="3–20 chars, letters / numbers / underscore"
        />
        <FormField
          label="Password"
          type="password"
          value={pw}
          onChange={setPw}
          placeholder="8+ chars"
        />

        {err ? (
          <div
            style={{
              marginTop: 4,
              fontSize: 12,
              color: "var(--coral)",
              fontWeight: 600,
            }}
          >
            {err}
          </div>
        ) : null}

        <div style={{ marginTop: 8 }}>
          <CoralButton full size="lg" onClick={submit}>
            {busy ? "Creating…" : "Create account"}
          </CoralButton>
        </div>

        <div
          style={{
            textAlign: "center",
            fontSize: 13,
            color: "var(--text-2)",
            marginTop: 22,
          }}
        >
          Already on PROVE?{" "}
          <a
            style={{ ..._authLinkStyle, marginLeft: 4 }}
            onClick={() => _navigate("/login")}
          >
            Sign in →
          </a>
        </div>
      </div>
    </AuthShell>
  );
}

// ─── FORGOT PASSWORD ───────────────────────────────────────────────────
function ForgotPasswordPageReal({ width, height, state = "form" }) {
  const [email, setEmail] = useStateAS("");
  const [busy, setBusy] = useStateAS(false);
  const [err, setErr] = useStateAS(null);

  async function send() {
    if (!email.trim()) {
      setErr("Enter your email");
      return;
    }
    setErr(null);
    setBusy(true);
    const { error } = await window.proveSupabase.auth.resetPasswordForEmail(
      email.trim(),
      { redirectTo: window.location.origin + "/#/login" },
    );
    setBusy(false);
    if (error) setErr(error.message);
    else _navigate("/forgot-sent");
  }

  if (state === "sent") {
    return (
      <AuthShell width={width} height={height}>
        <div style={_authCardStyle}>
          <AuthBrandHeader size={36} />
          <h1
            style={{
              fontFamily: "var(--display)",
              fontSize: 40,
              fontWeight: 800,
              letterSpacing: "-0.04em",
              margin: "4px 0 10px",
              textTransform: "uppercase",
              color: "#fff",
              lineHeight: 0.94,
              textAlign: "center",
            }}
          >
            Check{" "}
            <span style={{ color: "var(--coral)", fontStyle: "italic", fontWeight: 900 }}>
              your inbox.
            </span>
          </h1>
          <p style={{ ..._authSubStyle, textAlign: "center", marginBottom: 28 }}>
            We sent a reset link. Open it from this device to set a new password.
          </p>
          <CoralButton full size="lg" onClick={() => _navigate("/login")}>
            Back to sign in
          </CoralButton>
        </div>
      </AuthShell>
    );
  }

  return (
    <AuthShell width={width} height={height}>
      <div style={_authCardStyle}>
        <AuthBrandHeader size={36} />
        <h1
          style={{
            fontFamily: "var(--display)",
            fontSize: 40,
            fontWeight: 800,
            letterSpacing: "-0.04em",
            margin: "4px 0 10px",
            textTransform: "uppercase",
            color: "#fff",
            lineHeight: 0.94,
            textAlign: "center",
          }}
        >
          Reset{" "}
          <span style={{ color: "var(--coral)", fontStyle: "italic", fontWeight: 900 }}>
            password.
          </span>
        </h1>
        <p style={{ ..._authSubStyle, textAlign: "center", marginBottom: 28 }}>
          We'll email you a link to set a new one.
        </p>

        <FormField
          label="Email"
          type="email"
          value={email}
          onChange={setEmail}
          placeholder="you@email.com"
        />

        {err ? (
          <div
            style={{
              marginTop: 4,
              fontSize: 12,
              color: "var(--coral)",
              fontWeight: 600,
            }}
          >
            {err}
          </div>
        ) : null}

        <div style={{ marginTop: 8 }}>
          <CoralButton full size="lg" onClick={send}>
            {busy ? "Sending…" : "Send reset link"}
          </CoralButton>
        </div>

        <div
          style={{
            textAlign: "center",
            fontSize: 13,
            color: "var(--text-2)",
            marginTop: 22,
          }}
        >
          Remembered it?{" "}
          <a
            style={{ ..._authLinkStyle, marginLeft: 4 }}
            onClick={() => _navigate("/login")}
          >
            Sign in →
          </a>
        </div>
      </div>
    </AuthShell>
  );
}

// Override the static pages so the router renders real ones.
window.LoginPage = LoginPageReal;
window.SignupPage = SignupPageReal;
window.ForgotPasswordPage = ForgotPasswordPageReal;
