// Auth UI — Google sign-in / sign-out. Mirrors the window.useTweaks global-hook
// pattern. The sync engine (sync.js) subscribes to onAuthStateChange independently,
// so auth UI and data sync are decoupled.

function useAuth() {
  const [user, setUser] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    let sub = null;
    let cancelled = false;
    if (!window.RPGSupabase) { setLoading(false); return; }
    window.RPGSupabase.ready().then((client) => {
      if (cancelled || !client) { setLoading(false); return; }
      client.auth.getSession().then(({ data }) => {
        if (cancelled) return;
        setUser(data.session ? data.session.user : null);
        setLoading(false);
      });
      sub = client.auth.onAuthStateChange((_event, session) => {
        setUser(session ? session.user : null);
      }).data.subscription;
    });
    return () => { cancelled = true; if (sub) sub.unsubscribe(); };
  }, []);

  const signIn = async () => {
    const client = window.RPGSupabase && await window.RPGSupabase.ready();
    if (!client) { alert("Cloud sync isn't configured. Add SUPABASE_URL and SUPABASE_ANON_KEY to .env."); return; }
    await client.auth.signInWithOAuth({
      provider: "google",
      options: { redirectTo: window.location.origin },
    });
  };

  const signOut = async () => {
    const client = window.RPGSupabase && await window.RPGSupabase.ready();
    if (client) await client.auth.signOut();
  };

  return { user, loading, signIn, signOut };
}

function GoogleMark() {
  return (
    <svg width="15" height="15" viewBox="0 0 48 48" aria-hidden="true">
      <path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3C33.7 32.9 29.3 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.5 6.5 29.5 4.5 24 4.5 13.2 4.5 4.5 13.2 4.5 24S13.2 43.5 24 43.5 43.5 34.8 43.5 24c0-1.2-.1-2.3-.3-3.5z"/>
      <path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.5 6.5 29.5 4.5 24 4.5 16.3 4.5 9.7 8.9 6.3 14.7z"/>
      <path fill="#4CAF50" d="M24 43.5c5.2 0 10-2 13.6-5.2l-6.3-5.3c-2 1.5-4.6 2.5-7.3 2.5-5.3 0-9.7-3.1-11.3-7.9l-6.5 5C9.6 39 16.2 43.5 24 43.5z"/>
      <path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.1-4 5.5l6.3 5.3C41.1 36.3 43.5 30.6 43.5 24c0-1.2-.1-2.3-.3-3.5z"/>
    </svg>
  );
}

function AuthControls() {
  const { user, loading, signIn, signOut } = useAuth();
  const [open, setOpen] = React.useState(false);
  const [imgError, setImgError] = React.useState(false);

  // Supabase not configured at all — render nothing rather than a dead button.
  if (!window.RPGSupabase) return null;
  if (loading) return null;

  if (!user) {
    return (
      <button type="button" className="btn btn-sm" onClick={signIn} title="Sync your data across devices">
        <GoogleMark /> Sign in
      </button>
    );
  }

  const email = user.email || (user.user_metadata && user.user_metadata.email) || "Signed in";
  const avatar = user.user_metadata && (user.user_metadata.avatar_url || user.user_metadata.picture);

  return (
    <div className="auth-controls" style={{ position: "relative" }}>
      <button type="button" className="btn btn-sm" onClick={() => setOpen((o) => !o)} title={email}>
        {avatar && !imgError
          ? <img src={avatar} alt="" width={18} height={18} referrerPolicy="no-referrer"
              style={{ borderRadius: "50%" }} onError={() => setImgError(true)} />
          : <window.Icon name="users" size={15} />}
        <span className="mode-label">{email.split("@")[0]}</span>
      </button>
      {open && (
        <div role="menu" style={{
          position: "absolute", right: 0, top: "calc(100% + 6px)", zIndex: 50,
          background: "var(--panel, #fff)", color: "var(--ink)",
          border: "1px solid var(--line, rgba(0,0,0,.15))", borderRadius: 10,
          padding: 10, minWidth: 200, boxShadow: "0 8px 28px rgba(0,0,0,.18)",
        }}>
          <div style={{ fontSize: 13, color: "var(--ink-soft)", padding: "2px 6px 8px", wordBreak: "break-all" }}>{email}</div>
          <button type="button" className="btn btn-sm" style={{ width: "100%" }}
            onClick={() => { setOpen(false); signOut(); }}>
            <window.Icon name="back" size={14} /> Sign out
          </button>
        </div>
      )}
    </div>
  );
}

window.useAuth = useAuth;
window.AuthControls = AuthControls;
