/* Sync / sign-in popover in the topbar.

   Three states:
   - Supabase not configured  → button hidden.
   - Signed out               → OAuth (Google/Apple) + email sign-in link fallback.
   - Signed in                → email, sync toggle, manual pull/push, sign out. */

function AuthMenu({ user, syncEnabled, onToggleSync, onSignOut, onPullNow, onPushNow, syncStatus }) {
  const [open, setOpen] = React.useState(false);
  const [showEmail, setShowEmail] = React.useState(false);
  const [email, setEmail] = React.useState("");
  const [sending, setSending] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [error, setError] = React.useState("");
  const popRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (popRef.current && !popRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  if (!window.TVCloud || !window.TVCloud.isConfigured()) return null;

  const sendLink = async (e) => {
    e.preventDefault();
    setError(""); setSent(false);
    if (!email.trim()) { setError("Enter your email"); return; }
    setSending(true);
    try {
      await window.TVCloud.signInWithMagicLink(email.trim());
      setSent(true);
    } catch (err) {
      setError(err.message || "Couldn't send sign-in link");
    } finally {
      setSending(false);
    }
  };

  const oauth = async (provider) => {
    setError("");
    try {
      await window.TVCloud.signInWithOAuth(provider);
      // Redirect happens automatically; this code only runs if it errors.
    } catch (err) {
      setError(err.message || `Couldn't start ${provider} sign-in`);
    }
  };

  const initials = user ? (user.email || "").slice(0, 2).toUpperCase() : "";

  return (
    <div className="auth-menu" ref={popRef}>
      <button
        className={`btn ${user ? (syncEnabled ? "sync-on" : "outline") : "outline"}`}
        title={user ? `Signed in as ${user.email}` : "Sign in to sync"}
        onClick={() => setOpen(o => !o)}
      >
        <Icon name={user ? "cloud" : "cloud-off"} size={13} />
        {user ? (syncEnabled ? "Sync on" : "Sync off") : "Sign in"}
      </button>
      {open && (
        <div className="auth-pop">
          {!user && (
            <div className="auth-pop-body">
              <div className="auth-title">Sync across devices</div>
              <div className="auth-sub">Trees stay on this device by default. Sign in to back them up and access them anywhere.</div>
              <button className="btn oauth-btn" onClick={() => oauth("google")}>
                <Icon name="google" size={14} /> Continue with Google
              </button>
              {!showEmail ? (
                <button className="btn ghost auth-btn-sm" onClick={() => setShowEmail(true)}>
                  Or use email instead
                </button>
              ) : (
                <form onSubmit={sendLink} className="auth-email-form">
                  <input
                    type="email"
                    placeholder="you@example.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="auth-input"
                    autoFocus
                  />
                  <button className="btn outline auth-btn" type="submit" disabled={sending}>
                    {sending ? "Sending..." : "Send sign-in link"}
                  </button>
                  {sent && <div className="auth-ok">Check your inbox — click the link to sign in.</div>}
                </form>
              )}
              {error && <div className="auth-err">{error}</div>}
              <div className="auth-foot">Or just keep using this device — no account needed.</div>
            </div>
          )}
          {user && (
            <div className="auth-pop-body">
              <div className="auth-row">
                <div className="auth-avatar">{initials}</div>
                <div className="auth-id">
                  <div className="auth-id-email">{user.email}</div>
                  <div className="auth-id-sub">{syncStatus || (syncEnabled ? "Auto-sync on" : "Sync paused")}</div>
                </div>
              </div>
              <label className="auth-toggle">
                <input type="checkbox" checked={syncEnabled} onChange={(e) => onToggleSync(e.target.checked)} />
                <span>Auto-sync this device to the cloud</span>
              </label>
              <button className="btn ghost auth-btn-sm auth-signout" onClick={onSignOut}>
                Sign out
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

window.AuthMenu = AuthMenu;
