// auth.jsx — session hook + Login/Register modals for saraslot.
// Loaded after supabase-client.jsx, before data.jsx and pages.jsx.

const { useState: useStateAu, useEffect: useEffectAu, useCallback: useCallbackAu, createContext: createContextAu, useContext: useContextAu } = React;

const SessionContext = createContextAu({ session: null, ready: false, refresh: () => {} });

function SessionProvider({ children }) {
  const [session, setSession] = useStateAu(null);
  const [ready, setReady] = useStateAu(false);

  useEffectAu(() => {
    let mounted = true;
    window.sb.auth.getSession().then(({ data }) => {
      if (!mounted) return;
      setSession(data.session || null);
      setReady(true);
    });
    const { data: sub } = window.sb.auth.onAuthStateChange((_event, sess) => {
      setSession(sess || null);
    });
    return () => { mounted = false; sub?.subscription?.unsubscribe?.(); };
  }, []);

  const refresh = useCallbackAu(async () => {
    const { data } = await window.sb.auth.getSession();
    setSession(data.session || null);
  }, []);

  return <SessionContext.Provider value={{ session, ready, refresh }}>{children}</SessionContext.Provider>;
}
window.SessionProvider = SessionProvider;

function useSession() {
  return useContextAu(SessionContext);
}
window.useSession = useSession;

async function signOut() {
  await window.sb.auth.signOut();
}
window.signOut = signOut;

/* ─────────────────────────────────────────────────────────────
   Auth modal shell
   ──────────────────────────────────────────────────────────── */
function AuthModal({ open, onClose, children, title }) {
  if (!open) return null;
  return (
    <div className="auth-overlay" onClick={onClose}>
      <div className="auth-modal" onClick={(e) => e.stopPropagation()}>
        <button className="auth-close" type="button" onClick={onClose} aria-label="Close">×</button>
        <div className="auth-title accent-fill">{title}</div>
        {children}
      </div>
    </div>
  );
}

function PhoneField({ value, onChange }) {
  return (
    <label className="auth-field">
      <span>Nombor Telefon</span>
      <input
        type="tel"
        placeholder="e.g. 60126668888"
        autoComplete="tel"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        required
      />
    </label>
  );
}

function PasswordField({ value, onChange, label = "Kata Laluan", autoComplete = "current-password" }) {
  return (
    <label className="auth-field">
      <span>{label}</span>
      <input
        type="password"
        placeholder="6-20 characters"
        autoComplete={autoComplete}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        minLength={6}
        required
      />
    </label>
  );
}

/* ─────────────────────────────────────────────────────────────
   LoginModal — phone + password
   ──────────────────────────────────────────────────────────── */
function LoginModal({ open, onClose, onSwitchToRegister }) {
  const [phone, setPhone] = useStateAu("");
  const [password, setPassword] = useStateAu("");
  const [error, setError] = useStateAu("");
  const [busy, setBusy] = useStateAu(false);

  const submit = async (e) => {
    e.preventDefault();
    setError("");
    setBusy(true);
    const email = window.phoneToEmail(phone);
    const { error: err } = await window.sb.auth.signInWithPassword({ email, password });
    setBusy(false);
    if (err) {
      setError("Phone or password incorrect.");
      return;
    }
    setPhone(""); setPassword("");
    onClose();
  };

  return (
    <AuthModal open={open} onClose={onClose} title="Log Masuk">
      <form onSubmit={submit} className="auth-form">
        <PhoneField value={phone} onChange={setPhone} />
        <PasswordField value={password} onChange={setPassword} />
        {error && <div className="auth-error">{error}</div>}
        <button className="btn btn-primary auth-submit" type="submit" disabled={busy}>
          {busy ? "Loading…" : "Log Masuk"}
        </button>
        <div className="auth-switch">
          Belum Ada Akaun? <button type="button" className="auth-link" onClick={onSwitchToRegister}>DAFTAR</button>
        </div>
      </form>
    </AuthModal>
  );
}
window.LoginModal = LoginModal;

/* ─────────────────────────────────────────────────────────────
   RegisterModal — phone + username + password
   ──────────────────────────────────────────────────────────── */
function RegisterModal({ open, onClose, onSwitchToLogin }) {
  const [phone, setPhone] = useStateAu("");
  const [username, setUsername] = useStateAu("");
  const [password, setPassword] = useStateAu("");
  const [error, setError] = useStateAu("");
  const [busy, setBusy] = useStateAu(false);

  const submit = async (e) => {
    e.preventDefault();
    setError("");
    const digits = String(phone).replace(/\D+/g, "");
    if (digits.length < 7) { setError("Enter a valid phone number."); return; }
    if (!username.trim()) { setError("Pick a username."); return; }

    setBusy(true);
    const email = window.phoneToEmail(phone);
    const { data, error: err } = await window.sb.auth.signUp({
      email,
      password,
      options: { data: { phone: digits, username: username.trim() } },
    });
    if (err) {
      setBusy(false);
      setError(err.message || "Could not register. Phone may already be in use.");
      return;
    }
    // The handle_new_user trigger inserted a profiles row using new.phone (null for
    // email signup) or new.id::text fallback. Update the row with the real phone +
    // username now that the session is live.
    try {
      await window.sb.from("profiles").update({
        phone: digits,
        username: username.trim(),
      }).eq("id", data.user.id);
    } catch (_) { /* ignore — trigger should have created the row */ }

    setBusy(false);
    setPhone(""); setUsername(""); setPassword("");
    onClose();
  };

  return (
    <AuthModal open={open} onClose={onClose} title="Daftar">
      <form onSubmit={submit} className="auth-form">
        <PhoneField value={phone} onChange={setPhone} />
        <label className="auth-field">
          <span>Nama Pengguna</span>
          <input type="text" placeholder="3-20 characters" value={username} onChange={(e) => setUsername(e.target.value)} minLength={3} maxLength={20} required />
        </label>
        <PasswordField value={password} onChange={setPassword} label="Kata Laluan" autoComplete="new-password" />
        {error && <div className="auth-error">{error}</div>}
        <button className="btn btn-primary auth-submit" type="submit" disabled={busy}>
          {busy ? "Creating…" : "Daftar"}
        </button>
        <div className="auth-switch">
          Sudah Ada Akaun? <button type="button" className="auth-link" onClick={onSwitchToLogin}>LOG MASUK</button>
        </div>
      </form>
    </AuthModal>
  );
}
window.RegisterModal = RegisterModal;

/* ─────────────────────────────────────────────────────────────
   AuthGate — used by pages that require a session
   ──────────────────────────────────────────────────────────── */
function AuthGate({ children, fallback }) {
  const { session, ready } = useSession();
  if (!ready) return <div className="auth-loading">Loading…</div>;
  if (!session) return fallback || <div className="auth-loading">Please log in to view this page.</div>;
  return children;
}
window.AuthGate = AuthGate;
