import React, { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAuth } from "../../auth/AuthContext";
import { registerUser, updateProfileUsername, fetchFriendRequests, toSmallImageUrl } from "../../api/client";
import AuthToast from "../Auth/AuthToast";
import { promptInstall, isRunningAsPWA, canInstall } from '../../pwaInstall';
import { trackEvent } from "../../utils/analytics";
import FriendsList from "../Friends/FriendsList";

const SUPPORTED_LANGS = ['en', 'fr', 'es'];
const THEMES = ['dark', 'blue', 'light'];
const LAST_SIGNUP_KEY = "sociowire:lastSignup";

function initialLetter(name = "") {
  const s = (name || "").trim();
  return s ? s[0].toUpperCase() : "G";
}

function truthyParam(v) {
  if (!v) return false;
  const x = String(v).toLowerCase().trim();
  return x === "1" || x === "true" || x === "yes" || x === "ok";
}

function readLastSignup() {
  try {
    const raw = localStorage.getItem(LAST_SIGNUP_KEY);
    if (!raw) return null;
    const j = JSON.parse(raw);
    if (!j || typeof j !== "object") return null;
    return {
      username: (j.username || "").toString().trim(),
      email: (j.email || "").toString().trim(),
    };
  } catch {
    return null;
  }
}

function parseMergedParams() {
  const search = window.location.search || "";
  const hash = window.location.hash || "";

  const qs = new URLSearchParams(search.startsWith("?") ? search.slice(1) : search);

  let hashQs = "";
  if (hash.includes("?")) hashQs = hash.slice(hash.indexOf("?") + 1);
  const hs = new URLSearchParams(hashQs);

  const get = (k) => {
    const a = qs.get(k);
    if (a != null && a !== "") return a;
    const b = hs.get(k);
    return b != null ? b : null;
  };

  return { qs, hs, get, hash };
}

export default function TopBar({ theme = "dark", onChangeTheme, onIslandsClick, onUserIsland, onSearch, onMyLocation }) {
  const { t, i18n } = useTranslation();
  const {
    loading,
    authenticated,
    username,
    login,
    logout,
    restore,
    loginWithProvider,
    ssoEnabled,
    avatarUrl,
    profileLoaded,
    needsUsername,
    needsEmailVerification,
    lastError,
    lastInfo,
    clearError,
    clearInfo,
  } = useAuth();

  const [showLangMenu, setShowLangMenu] = useState(false);
  const [showThemeMenu, setShowThemeMenu] = useState(false);
  const [showUserMenu, setShowUserMenu] = useState(false);
  const langBtnRef = useRef(null);
  const themeBtnRef = useRef(null);
  const userMenuRef = useRef(null);

  const [searchQuery, setSearchQuery] = useState("");
  const [searchFocused, setSearchFocused] = useState(false);

  const changeLanguage = (lang) => {
    i18n.changeLanguage(lang);
    setShowLangMenu(false);
  };

  // Close menus when clicking outside
  useEffect(() => {
    if (!showLangMenu && !showThemeMenu && !showUserMenu) return;
    const handleClick = (e) => {
      if (showLangMenu && langBtnRef.current && !langBtnRef.current.contains(e.target)) {
        setShowLangMenu(false);
      }
      if (showThemeMenu && themeBtnRef.current && !themeBtnRef.current.contains(e.target)) {
        setShowThemeMenu(false);
      }
      if (showUserMenu && userMenuRef.current && !userMenuRef.current.contains(e.target)) {
        setShowUserMenu(false);
      }
    };
    document.addEventListener("click", handleClick);
    return () => document.removeEventListener("click", handleClick);
  }, [showLangMenu, showThemeMenu, showUserMenu]);

  const [showAuth, setShowAuth] = useState(false);
  const [mode, setMode] = useState("login");
  const [showUsernameModal, setShowUsernameModal] = useState(false);
  const [showFriends, setShowFriends] = useState(false);
  const [pendingRequestsCount, setPendingRequestsCount] = useState(0);
  const [desiredUsername, setDesiredUsername] = useState("");
  const [usernameError, setUsernameError] = useState("");
  const [usernameInfo, setUsernameInfo] = useState("");
  const [usernameSaving, setUsernameSaving] = useState(false);
  const usernamePromptTimer = useRef(null);
  const [stableUsername, setStableUsername] = useState("");

  const displayUsername = (() => {
    const raw = (stableUsername || username || "user").toString();
    if (!stableUsername && raw.includes("@")) return "user";
    if (raw.length <= 12) return raw;
    return raw.slice(0, 12) + "..";
  })();

  const [loginUser, setLoginUser] = useState("");
  const [loginPass, setLoginPass] = useState("");

  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [regUser, setRegUser] = useState("");
  const [regEmail, setRegEmail] = useState("");
  const [regPass, setRegPass] = useState("");
  const [signupError, setSignupError] = useState("");
  const [signupInfo, setSignupInfo] = useState("");
  const [signupLoading, setSignupLoading] = useState(false);
  const [showInstallBtn, setShowInstallBtn] = useState(false);
  const [authNotice, setAuthNotice] = useState("");

  const resetPasswordUrl = useMemo(() => {
    const base = (import.meta?.env?.VITE_KC_URL || "https://auth.sociowire.com").replace(/\/+$/, "");
    const realm = import.meta?.env?.VITE_KC_REALM || "sociowire";
    const clientId = import.meta?.env?.VITE_KC_CLIENT_ID || "sociowire-frontend";
    const redirectUri = window.location.origin + window.location.pathname;
    const params = new URLSearchParams({
      client_id: clientId,
      redirect_uri: redirectUri,
    });
    return `${base}/realms/${realm}/login-actions/reset-credentials?${params.toString()}`;
  }, []);

  const openModal = (nextMode) => {
    setMode(nextMode);
    setShowAuth(true);
    setSignupError("");
    trackEvent("auth_modal_open", { mode: nextMode || "login" });
  };

  const closeModal = () => {
    setShowAuth(false);
    setLoginPass("");
    setSignupError("");
    setAuthNotice("");
  };

  const handleUsernameSave = async (e) => {
    e.preventDefault();
    const next = (desiredUsername || "").trim();
    const re = /^[A-Za-z0-9_.]{3,24}$/;
    if (!re.test(next) || next.includes("@")) {
      setUsernameError(t('auth.usernameHint'));
      return;
    }
    setUsernameSaving(true);
    setUsernameError("");
    setUsernameInfo("");
    const res = await updateProfileUsername(next);
    setUsernameSaving(false);
    if (!res.ok) {
      if (res.status === 409) {
        setUsernameError(t('auth.usernameTaken'));
      } else {
        setUsernameError(res.text || t('auth.usernameUpdateError'));
      }
      return;
    }
    setUsernameInfo(t('auth.usernameSaved'));
    setShowUsernameModal(false);
    await restore();
  };

  useEffect(() => {
    if (authenticated) setShowAuth(false);
  }, [authenticated]);

  // Fetch pending friend requests count
  useEffect(() => {
    if (!authenticated) {
      setPendingRequestsCount(0);
      return;
    }
    const loadRequests = async () => {
      try {
        const res = await fetchFriendRequests();
        const received = (res?.requests || []).filter(r => r?.direction === 'received');
        setPendingRequestsCount(received.length);
      } catch (err) {
        setPendingRequestsCount(0);
      }
    };
    loadRequests();
    const interval = setInterval(loadRequests, 30000);
    return () => clearInterval(interval);
  }, [authenticated]);

  useEffect(() => {
    if (!authenticated) {
      setStableUsername("");
      return;
    }
    const next = (username || "").trim();
    if (!next) return;
    const looksLikeEmail = next.includes("@");
    if (!looksLikeEmail) {
      setStableUsername(next);
      return;
    }
    if (stableUsername) return;
  }, [authenticated, username, stableUsername]);

  useEffect(() => {
    const requiresUsername = (name) => {
      if (!name) return false;
      if (name.includes("@")) return true;
      const re = /^[A-Za-z0-9_.]{3,24}$/;
      return !re.test(name);
    };
    if (usernamePromptTimer.current) {
      clearTimeout(usernamePromptTimer.current);
      usernamePromptTimer.current = null;
    }
    if (loading) return;
    if (!authenticated) {
      setShowUsernameModal(false);
      return;
    }
    const shouldPrompt = !!needsUsername || requiresUsername(username);
    if (shouldPrompt) {
      if (!showUsernameModal) {
        const base = (username || "").split("@")[0] || "";
        const cleaned = base.replace(/[^A-Za-z0-9_.]/g, "").slice(0, 24);
        setDesiredUsername(cleaned);
        setUsernameError("");
        setUsernameInfo("");
        usernamePromptTimer.current = setTimeout(() => {
          setShowUsernameModal(true);
        }, 600);
      }
    } else if (showUsernameModal) {
      setShowUsernameModal(false);
    }
  }, [authenticated, username, showUsernameModal, loading, needsUsername]);

  useEffect(() => {
    return () => {
      if (usernamePromptTimer.current) {
        clearTimeout(usernamePromptTimer.current);
        usernamePromptTimer.current = null;
      }
    };
  }, []);

  useEffect(() => {
    const handler = (e) => {
      const detail = e?.detail || {};
      const msg = (detail.message || "").toString().trim() || t('auth.pleaseSignIn');
      setAuthNotice(msg);
      setMode(detail.mode === "signup" ? "signup" : "login");
      setShowAuth(true);
    };
    window.addEventListener("sociowire:auth-required", handler);
    return () => window.removeEventListener("sociowire:auth-required", handler);
  }, []);

  // Check if PWA install should be shown
  useEffect(() => {
    const checkInstall = () => {
      if (isRunningAsPWA()) {
        setShowInstallBtn(false);
        return;
      }
      setShowInstallBtn(canInstall());
    };
    checkInstall();
    const handlePrompt = () => setTimeout(checkInstall, 100);
    window.addEventListener('beforeinstallprompt', handlePrompt);
    window.addEventListener('appinstalled', () => setShowInstallBtn(false));
    return () => {
      window.removeEventListener('beforeinstallprompt', handlePrompt);
      window.removeEventListener('appinstalled', () => setShowInstallBtn(false));
    };
  }, []);

  useEffect(() => {
    try {
      const { get, qs, hs, hash } = parseMergedParams();
      const verified = get("verified") || get("validated") || get("email_verified") || get("emailVerified") || get("kc_verified");
      const signup = get("signup");
      const notice = get("notice");
      const email = get("email") || get("user_email") || get("mail");
      const uname = get("username") || get("user") || get("preferred_username") || get("login");
      const last = readLastSignup();

      if (truthyParam(verified)) {
        const who = (email || uname || last?.email || last?.username || "").trim();
        setSignupInfo("✅ " + t('auth.emailConfirmedMsg') + (who ? " (" + who + ")" : ""));
        setMode("login");
        setShowAuth(true);
        const prefill = (uname || email || last?.username || last?.email || "").trim();
        if (prefill) setLoginUser(prefill);
      } else if (truthyParam(signup)) {
        try { localStorage.removeItem(LAST_SIGNUP_KEY); } catch {}
        setSignupInfo("");
        setSignupError("");
        setAuthNotice("");
        setLoginUser("");
        setMode("signup");
        setShowAuth(true);
      } else if (notice) {
        const msg = decodeURIComponent(notice);
        if (msg && msg.trim()) {
          setSignupInfo(msg.trim());
          setMode("login");
          setShowAuth(true);
        }
      }

      const touched = qs.has("verified") || qs.has("validated") || qs.has("email_verified") || qs.has("emailVerified") || qs.has("signup") || qs.has("notice") ||
        hs.has("verified") || hs.has("validated") || hs.has("email_verified") || hs.has("emailVerified") || hs.has("signup") || hs.has("notice");

      if (touched) {
        const cleanHash = hash.includes("?") ? hash.split("?")[0] : hash;
        const clean = window.location.pathname + cleanHash;
        window.history.replaceState({}, "", clean);
      }
    } catch (e) {}
  }, []);

  const handleLoginSubmit = async (e) => {
    e.preventDefault();
    trackEvent("login_submit");
    const res = await login(loginUser, loginPass);
    if (res?.ok) trackEvent("login_success");
  };

  const handleSignupSubmit = async (e) => {
    e.preventDefault();
    setSignupError("");
    setSignupInfo("");

    if (!firstName.trim() || !lastName.trim() || !regUser.trim() || !regEmail.trim() || !regPass) {
      setSignupError(t('auth.fieldsRequired'));
      return;
    }

    try {
      setSignupLoading(true);
      trackEvent("signup_submit");
      const u = regUser.trim();
      const em = regEmail.trim();
      await registerUser({ username: u, email: em, password: regPass, firstName: firstName.trim(), lastName: lastName.trim() });
      try { localStorage.setItem(LAST_SIGNUP_KEY, JSON.stringify({ username: u, email: em })); } catch {}
      setSignupInfo("✅ " + t('auth.accountCreatedMsg') + " (" + em + ")");
      trackEvent("signup_success");
      setMode("login");
      setLoginUser(u || em);
      setLoginPass("");
    } catch (err) {
      setSignupError(err.message || t('auth.registrationError'));
    } finally {
      setSignupLoading(false);
    }
  };

  const handleSearchSubmit = (e) => {
    e.preventDefault();
    if (searchQuery.trim() && onSearch) {
      onSearch(searchQuery.trim());
    }
  };

  const toast = useMemo(() => {
    if (lastError) {
      const toastType = needsEmailVerification ? "warn" : "error";
      const title = needsEmailVerification ? t('auth.emailVerificationRequired') : t('auth.loginFailed');
      return { type: toastType, title, message: lastError };
    }
    if (lastInfo) {
      return { type: "success", title: "", message: lastInfo };
    }
    return null;
  }, [lastError, lastInfo, needsEmailVerification, t]);

  const themeIcon = theme === 'dark' ? 'fa-moon' : theme === 'light' ? 'fa-sun' : 'fa-droplet';

  return (
    <>
      {/* Toast area */}
      {toast?.message && (
        <div className="sw-toast-wrap">
          <AuthToast
            type={toast.type}
            title={toast.title}
            message={toast.message}
            onClose={() => {
              if (lastError && typeof clearError === "function") clearError();
              if (lastInfo && typeof clearInfo === "function") clearInfo();
            }}
          />
        </div>
      )}

      <header className="sw-topbar">
        {/* LEFT: Logo + Brand */}
        <div className="sw-topbar-left">
          <div className="sw-logo">
            <img src="/logo.png" alt="SocioWire" />
          </div>
          <div className="sw-brand">
            <span className="sw-brand-name">SocioWire</span>
            <span className="sw-brand-tagline">{t('topbar.wiredToLife')}</span>
          </div>
        </div>

        {/* CENTER: Search Bar */}
        <div className={`sw-topbar-center ${searchFocused ? 'is-focused' : ''}`}>
          <form onSubmit={handleSearchSubmit} className="sw-search-form">
            <i className="fa-solid fa-magnifying-glass sw-search-icon" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onFocus={() => setSearchFocused(true)}
              onBlur={() => setSearchFocused(false)}
              placeholder={t('map.searchPlaceholder')}
              className="sw-search-input"
            />
            {searchQuery && (
              <button type="button" className="sw-search-clear" onClick={() => setSearchQuery("")}>
                <i className="fa-solid fa-times" />
              </button>
            )}
          </form>
        </div>

        {/* RIGHT: Actions */}
        <div className="sw-topbar-right">
          {/* My Location */}
          <button
            type="button"
            className="sw-topbar-btn sw-topbar-btn-location"
            onClick={() => onMyLocation && onMyLocation()}
            title={t('map.mySpot')}
          >
            <i className="fa-solid fa-location-crosshairs" />
          </button>

          {/* Islands */}
          <button
            type="button"
            className="sw-topbar-btn sw-topbar-btn-islands"
            onClick={() => onIslandsClick && onIslandsClick()}
            title={t('nav.islands')}
          >
            <i className="fa-solid fa-globe" />
          </button>

          {/* Install PWA */}
          {showInstallBtn && (
            <button
              type="button"
              className="sw-topbar-btn sw-topbar-btn-install"
              onClick={() => promptInstall()}
              title={t('topbar.installApp')}
            >
              <i className="fa-solid fa-download" />
            </button>
          )}

          {/* Theme */}
          <div className="sw-topbar-dropdown" ref={themeBtnRef}>
            <button
              type="button"
              className={`sw-topbar-btn sw-topbar-btn-theme ${showThemeMenu ? 'is-active' : ''}`}
              onClick={() => { setShowThemeMenu(!showThemeMenu); setShowLangMenu(false); }}
              title={t(`theme.${theme}`)}
            >
              <i className={`fa-solid ${themeIcon}`} />
            </button>
            {showThemeMenu && (
              <div className="sw-dropdown-menu sw-dropdown-theme">
                {THEMES.map((themeKey) => (
                  <button
                    key={themeKey}
                    type="button"
                    className={`sw-dropdown-item ${theme === themeKey ? 'is-active' : ''}`}
                    onClick={() => { onChangeTheme && onChangeTheme(themeKey); setShowThemeMenu(false); }}
                  >
                    <i className={`fa-solid ${themeKey === 'dark' ? 'fa-moon' : themeKey === 'light' ? 'fa-sun' : 'fa-droplet'}`} />
                    <span>{t(`theme.${themeKey}`)}</span>
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Language */}
          <div className="sw-topbar-dropdown" ref={langBtnRef}>
            <button
              type="button"
              className={`sw-topbar-btn sw-topbar-btn-lang ${showLangMenu ? 'is-active' : ''}`}
              onClick={() => { setShowLangMenu(!showLangMenu); setShowThemeMenu(false); }}
              title={t('language.selectLanguage')}
            >
              <span className="sw-lang-code">{i18n.language?.toUpperCase().slice(0, 2)}</span>
            </button>
            {showLangMenu && (
              <div className="sw-dropdown-menu sw-dropdown-lang">
                {SUPPORTED_LANGS.map((lang) => (
                  <button
                    key={lang}
                    type="button"
                    className={`sw-dropdown-item ${i18n.language?.startsWith(lang) ? 'is-active' : ''}`}
                    onClick={() => changeLanguage(lang)}
                  >
                    {t(`language.${lang}`)}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Friends - only when authenticated */}
          {authenticated && (
            <button
              type="button"
              className={`sw-topbar-btn sw-topbar-btn-friends ${showFriends ? 'is-active' : ''}`}
              onClick={() => setShowFriends(!showFriends)}
              title={t('topbar.friends')}
            >
              <i className="fa-solid fa-user-group" />
              {pendingRequestsCount > 0 && (
                <span className="sw-badge">{pendingRequestsCount}</span>
              )}
            </button>
          )}

          {/* User / Login */}
          <div className="sw-topbar-dropdown" ref={userMenuRef}>
            <button
              type="button"
              className={`sw-topbar-user ${showUserMenu ? 'is-active' : ''}`}
              onClick={() => {
                if (authenticated) {
                  setShowUserMenu(!showUserMenu);
                } else {
                  openModal("login");
                }
              }}
              title={authenticated ? username : t('topbar.login')}
            >
              <div className="sw-user-avatar">
                {authenticated && avatarUrl ? (
                  <img src={toSmallImageUrl(avatarUrl)} alt={username} />
                ) : authenticated ? (
                  <span>{initialLetter(username)}</span>
                ) : (
                  <i className="fa-solid fa-user" />
                )}
              </div>
              {authenticated && (
                <div className="sw-user-info">
                  <span className="sw-user-name">@{displayUsername}</span>
                  <span className="sw-user-status">{t('common.online')}</span>
                </div>
              )}
              <i className="fa-solid fa-chevron-down sw-user-chevron" />
            </button>
            {showUserMenu && authenticated && (
              <div className="sw-dropdown-menu sw-dropdown-user">
                <button
                  type="button"
                  className="sw-dropdown-item"
                  onClick={() => { setShowUserMenu(false); onUserIsland && onUserIsland(username); }}
                >
                  <i className="fa-solid fa-user" />
                  <span>{t('map.profileIsland')}</span>
                </button>
                <button
                  type="button"
                  className="sw-dropdown-item sw-dropdown-logout"
                  onClick={() => { setShowUserMenu(false); trackEvent("logout_click"); logout(); }}
                >
                  <i className="fa-solid fa-right-from-bracket" />
                  <span>{t('topbar.logout')}</span>
                </button>
              </div>
            )}
          </div>
        </div>
      </header>

      {/* Auth Modal */}
      {showAuth && (
        <div className="auth-modal-backdrop" onClick={closeModal}>
          <div className="auth-modal" onClick={(e) => e.stopPropagation()}>
            <div className="auth-modal-header">
              <button
                type="button"
                className={"auth-tab" + (mode === "login" ? " auth-tab-active" : "")}
                onClick={() => setMode("login")}
              >
                {t('auth.login')}
              </button>
              <button
                type="button"
                className={"auth-tab" + (mode === "signup" ? " auth-tab-active" : "")}
                onClick={() => setMode("signup")}
              >
                {t('auth.signup')}
              </button>
              <button type="button" className="auth-close" onClick={closeModal}>✕</button>
            </div>

            {signupInfo && <div className="auth-notice auth-notice-success">{signupInfo}</div>}
            {authNotice && <div className="auth-notice auth-notice-warn">{authNotice}</div>}
            {mode === "login" && lastError && (
              <div className={"auth-notice " + (needsEmailVerification ? "auth-notice-warn" : "auth-notice-error")}>
                {lastError}
              </div>
            )}

            {mode === "login" ? (
              <form className="auth-form" onSubmit={handleLoginSubmit}>
                <label>
                  {t('auth.usernameOrEmail')}
                  <input type="text" value={loginUser} onChange={(e) => setLoginUser(e.target.value)} autoComplete="username" />
                </label>
                <label>
                  {t('auth.password')}
                  <input type="password" value={loginPass} onChange={(e) => setLoginPass(e.target.value)} autoComplete="current-password" />
                </label>
                <button type="button" className="auth-link" onClick={() => window.open(resetPasswordUrl, "_blank", "noopener,noreferrer")}>
                  {t('auth.forgotPassword')}
                </button>
                <button type="submit" className="btn-primary btn-full" disabled={loading}>
                  {loading ? "..." : t('auth.signIn')}
                </button>

                {needsEmailVerification && (
                  <div className="auth-notice auth-notice-warn" style={{ marginTop: 10 }}>
                    ⚠️ {t('auth.verifyEmail')}
                  </div>
                )}

                {ssoEnabled && (
                  <>
                    <div className="auth-divider">{t('auth.orContinueWith')}</div>
                    <div className="auth-oauth">
                      <button type="button" className="btn-oauth btn-oauth-google" disabled={loading}
                        onClick={() => { trackEvent("login_provider_click", { provider: "google" }); loginWithProvider && loginWithProvider("google"); }}>
                        <i className="fa-brands fa-google"></i>
                        <span>{t('auth.continueWithGoogle')}</span>
                      </button>
                      <button type="button" className="btn-oauth btn-oauth-facebook" disabled={loading}
                        onClick={() => { trackEvent("login_provider_click", { provider: "facebook" }); loginWithProvider && loginWithProvider("facebook"); }}>
                        <i className="fa-brands fa-facebook-f"></i>
                        <span>{t('auth.continueWithFacebook')}</span>
                      </button>
                    </div>
                  </>
                )}
              </form>
            ) : (
              <form className="auth-form" onSubmit={handleSignupSubmit}>
                <div className="auth-row">
                  <label>
                    {t('auth.firstName')}
                    <input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} />
                  </label>
                  <label>
                    {t('auth.lastName')}
                    <input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} />
                  </label>
                </div>
                <label>
                  {t('auth.username')}
                  <input type="text" value={regUser} onChange={(e) => setRegUser(e.target.value)} />
                </label>
                <label>
                  {t('auth.email')}
                  <input type="email" value={regEmail} onChange={(e) => setRegEmail(e.target.value)} />
                </label>
                <label>
                  {t('auth.password')}
                  <input type="password" value={regPass} onChange={(e) => setRegPass(e.target.value)} />
                </label>
                {signupError && <div className="auth-notice auth-notice-error">{signupError}</div>}
                <button type="submit" className="btn-primary btn-full" disabled={signupLoading}>
                  {signupLoading ? "..." : t('auth.createAccount')}
                </button>
              </form>
            )}
          </div>
        </div>
      )}

      {/* Username Modal */}
      {showUsernameModal && (
        <div className="auth-modal-backdrop" onClick={() => {}}>
          <div className="auth-modal" onClick={(e) => e.stopPropagation()}>
            <div className="auth-modal-header">
              <div className="auth-tab auth-tab-active">{t('auth.chooseUsername')}</div>
            </div>
            <div className="auth-notice auth-notice-info">{t('auth.pickUsername')}</div>
            {usernameError && <div className="auth-notice auth-notice-error">{usernameError}</div>}
            {usernameInfo && <div className="auth-notice auth-notice-success">{usernameInfo}</div>}
            <form className="auth-form" onSubmit={handleUsernameSave}>
              <label>
                {t('auth.username')}
                <input type="text" value={desiredUsername} onChange={(e) => setDesiredUsername(e.target.value)} autoComplete="username" />
              </label>
              <button type="submit" className="btn-primary btn-full" disabled={usernameSaving}>
                {usernameSaving ? t('auth.savingUsername') : t('auth.saveUsername')}
              </button>
            </form>
          </div>
        </div>
      )}

      {/* Friends Panel */}
      {showFriends && (
        <div className="friends-dropdown-wrap">
          <FriendsList
            onSelectUser={(uname) => { setShowFriends(false); if (onUserIsland) onUserIsland(uname); }}
            onClose={() => setShowFriends(false)}
          />
        </div>
      )}
    </>
  );
}
