/* ============================================================
   BridgeOS — Auth UI (login / signup / add friends)
   ============================================================ */

// ── Auth modal (login / signup) ───────────────────────────────
function AuthModal({ onAuthed, onDemo: _onDemo }) {
  function onDemo() { localStorage.setItem("_bridgeAuthDismissed", "1"); _onDemo(); }
  const [mode, setMode] = useState("login");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [username, setUsername] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const isConfigured = window.Bridge && Bridge.isConfigured();

  async function handleGoogle() {
    if (!isConfigured) return;
    setError("");
    setLoading(true);
    const { error: err } = await Bridge.signInWithGoogle();
    // On success the page redirects away — no need to setLoading(false).
    if (err) { setError(err.message || "Google sign-in failed"); setLoading(false); }
  }

  async function handleSubmit(e) {
    e.preventDefault();
    setError("");
    if (!isConfigured) { setError("Supabase not configured. Use demo mode."); return; }
    setLoading(true);
    try {
      if (mode === "login") {
        const { data, error: err } = await Bridge.signIn(email, password);
        if (err) throw err;
        onAuthed(data.user, data.session);
      } else {
        if (username.length < 3) throw new Error("Username must be at least 3 characters");
        if (!/^[a-zA-Z0-9_]+$/.test(username)) throw new Error("Username: letters, numbers, underscores only");
        const { data, error: err } = await Bridge.signUp(email, password, username);
        if (err) throw err;
        // Supabase may auto-confirm or require email verification
        if (data.session) {
          onAuthed(data.user, data.session);
        } else {
          setMode("verify");
        }
      }
    } catch (err) {
      setError(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  }

  function switchMode(m) { setMode(m); setError(""); }

  if (mode === "verify") {
    return (
      <div className="auth-scrim">
        <div className="auth-box">
          <AuthBrand />
          <div className="auth-title">Check your email</div>
          <div className="auth-sub">We sent a confirmation link to <b>{email}</b>. Click it, then come back to log in.</div>
          <button className="btn btn-accent" style={{ width: "100%", marginTop: 20 }} onClick={() => switchMode("login")}>Back to login →</button>
        </div>
      </div>
    );
  }

  return (
    <div className="auth-scrim">
      <div className="auth-box">
        <AuthBrand />
        <div className="auth-title">{mode === "login" ? "Welcome back" : "Create account"}</div>
        <div className="auth-sub">{mode === "login" ? "Your progress lives in the cloud." : "Start your run. Track everything."}</div>

        {!isConfigured && (
          <div className="auth-warn">Backend not configured yet — use demo mode or paste your Supabase anon key into supabase.js.</div>
        )}

        {error && <div className="auth-error">{error}</div>}

        <form className="stack" style={{ marginTop: 18 }} onSubmit={handleSubmit}>
          {mode === "signup" && (
            <Field label="Username">
              <input className="inp" value={username} onChange={e => setUsername(e.target.value)}
                placeholder="atlas_" autoComplete="username" required minLength={3} maxLength={24} />
            </Field>
          )}
          <Field label="Email">
            <input className="inp" type="email" value={email} onChange={e => setEmail(e.target.value)}
              placeholder="you@email.com" autoComplete="email" required />
          </Field>
          <Field label="Password">
            <input className="inp" type="password" value={password} onChange={e => setPassword(e.target.value)}
              placeholder="••••••••" autoComplete={mode === "login" ? "current-password" : "new-password"} required minLength={6} />
          </Field>
          <button className="btn btn-accent" type="submit" disabled={loading || !isConfigured} style={{ width: "100%" }}>
            {loading ? "…" : mode === "login" ? "Log in" : "Create account"}
          </button>
        </form>

        <div className="auth-switch">
          {mode === "login"
            ? <><span className="dim">No account?</span> <button className="link-btn" onClick={() => switchMode("signup")}>Sign up</button></>
            : <><span className="dim">Already a member?</span> <button className="link-btn" onClick={() => switchMode("login")}>Log in</button></>}
        </div>

        <div className="auth-divider"><span>or</span></div>
        <button className="btn-google" onClick={handleGoogle} disabled={loading || !isConfigured}>
          <GoogleIcon />
          Continue with Google
        </button>
        <div className="auth-divider" style={{ margin: "12px 0 8px" }}><span>or</span></div>
        <button className="btn" style={{ width: "100%" }} onClick={onDemo}>
          Continue in demo mode
        </button>
        <div className="auth-note dim">Demo mode is local-only. Create an account to sync across devices and compete with real friends.</div>
      </div>
    </div>
  );
}

function GoogleIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" style={{ flexShrink: 0 }}>
      <path fill="#4285F4" d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615z"/>
      <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.184l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z"/>
      <path fill="#FBBC05" d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z"/>
      <path fill="#EA4335" d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 6.29C4.672 4.163 6.656 3.58 9 3.58z"/>
    </svg>
  );
}

function AuthBrand() {
  return (
    <div className="auth-brand">
      <div className="brand-mark">◆</div>
      <div className="brand-text">BRIDGE<span>OS</span></div>
    </div>
  );
}

// ── Add-friend modal (used from Leaderboard / Messages) ────────
function AddFriendModal({ myId, onClose, onAdded }) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [sending, setSending] = useState({});
  const [sent, setSent] = useState({});
  const [addErr, setAddErr] = useState({});

  async function search(e) {
    e.preventDefault();
    if (!query.trim()) return;
    setLoading(true);
    const { data, error } = await Bridge.searchUsers(query.trim());
    if (error) console.error("[Bridge] searchUsers:", error);
    setResults((data || []).filter(u => u.id !== myId));
    setLoading(false);
  }

  async function addFriend(friendId) {
    setSending(s => ({ ...s, [friendId]: true }));
    setAddErr(e => ({ ...e, [friendId]: null }));
    const { error } = await Bridge.sendFriendRequest(myId, friendId);
    setSending(s => ({ ...s, [friendId]: false }));
    if (error) {
      console.error("[Bridge] sendFriendRequest:", error);
      const msg = error.code === "23505" ? "Already sent" : (error.message || "Failed");
      setAddErr(e => ({ ...e, [friendId]: msg }));
    } else {
      setSent(s => ({ ...s, [friendId]: true }));
      if (onAdded) onAdded(friendId);
    }
  }

  return (
    <Modal open onClose={onClose} title="Add friends">
      <form className="picker-top" onSubmit={search}>
        <input className="inp" value={query} onChange={e => setQuery(e.target.value)} placeholder="Search by username…" autoFocus />
        <button className="btn btn-accent" type="submit" disabled={loading}>
          {loading ? "…" : "Search"}
        </button>
      </form>
      <div className="picker-list" style={{ marginTop: 10 }}>
        {results.length === 0 && query && !loading && <Empty>No users found.</Empty>}
        {results.map(u => (
          <div key={u.id} className="picker-item">
            <div className="picker-item-main">
              <div className="picker-item-name">{u.display_name || u.username} <span className="mono dim" style={{ fontSize: 11 }}>@{u.username}</span></div>
              <div className="picker-item-meta mono dim">Lv {u.level || 1} · ⚡{u.power || 0}
                {addErr[u.id] && <span style={{ color: "var(--danger)", marginLeft: 8 }}>{addErr[u.id]}</span>}
              </div>
            </div>
            <button className="btn btn-sm btn-accent"
              disabled={!!sent[u.id] || !!sending[u.id]}
              onClick={() => addFriend(u.id)}>
              {sending[u.id] ? "…" : sent[u.id] ? "Sent ✓" : "Add"}
            </button>
          </div>
        ))}
      </div>
    </Modal>
  );
}

// ── Account panel (shown in Settings when logged in) ──────────
function AccountPanel({ authUser, onSignOut }) {
  const [profile, setProfile] = useState(null);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    if (authUser) Bridge.getProfile(authUser.id).then(({ data }) => setProfile(data));
  }, [authUser]);

  function copyInviteLink() {
    const link = `${window.location.origin}?invite=${authUser.id}`;
    navigator.clipboard?.writeText(link).then(() => { setCopied(true); setTimeout(() => setCopied(false), 2000); });
  }

  if (!authUser) return (
    <div className="settings-row" style={{ flexDirection: "column", alignItems: "flex-start", gap: 10 }}>
      <div><div className="set-label">Not signed in</div><div className="set-sub dim">Sign in to sync across devices and compete with real friends.</div></div>
      <button className="btn btn-accent btn-sm" onClick={() => window._bridgeShowAuth && window._bridgeShowAuth()}>Sign in / Sign up</button>
    </div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <div className="settings-row">
        <div>
          <div className="set-label">{profile?.display_name || authUser.email}</div>
          <div className="set-sub mono dim">@{profile?.username || "…"} · {authUser.email}</div>
        </div>
        <button className="btn btn-sm btn-danger" onClick={onSignOut}>Sign out</button>
      </div>
      <div className="settings-row">
        <div><div className="set-label">Cloud sync</div><div className="set-sub dim">State syncs every ~4 s.</div></div>
        <span className="mono" style={{ color: "var(--accent)", fontSize: 12 }}>● live</span>
      </div>
      <div className="settings-row">
        <div><div className="set-label">Invite a friend</div><div className="set-sub dim">They open the link and you're auto-connected.</div></div>
        <button className="btn btn-sm" onClick={copyInviteLink} style={copied ? { color: "var(--accent)" } : {}}>
          {copied ? "Copied ✓" : "Copy link"}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { AuthModal, AddFriendModal, AccountPanel });
