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 }) {
  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 [langMenuPos, setLangMenuPos] = useState({ top: 0, right: 0 });
  const langBtnRef = useRef(null);

  const [showThemeMenu, setShowThemeMenu] = useState(false);
  const [themeMenuPos, setThemeMenuPos] = useState({ top: 0, right: 0 });
  const themeBtnRef = useRef(null);

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

  const toggleLangMenu = () => {
    if (!showLangMenu && langBtnRef.current) {
      const rect = langBtnRef.current.getBoundingClientRect();
      setLangMenuPos({
        top: rect.bottom + 6,
        right: window.innerWidth - rect.right,
      });
    }
    setShowLangMenu(!showLangMenu);
    setShowThemeMenu(false);
  };

  const toggleThemeMenu = () => {
    if (!showThemeMenu && themeBtnRef.current) {
      const rect = themeBtnRef.current.getBoundingClientRect();
      setThemeMenuPos({
        top: rect.bottom + 6,
        right: window.innerWidth - rect.right,
      });
    }
    setShowThemeMenu(!showThemeMenu);
    setShowLangMenu(false);
  };

  // Close lang/theme menu when clicking outside
  useEffect(() => {
    if (!showLangMenu && !showThemeMenu) 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);
      }
    };
    document.addEventListener("click", handleClick);
    return () => document.removeEventListener("click", handleClick);
  }, [showLangMenu, showThemeMenu]);

  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 invalidSinceRef = useRef(null);
  const [stableUsername, setStableUsername] = useState("");

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

  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();
        // Only count received requests (not sent ones)
        const received = (res?.requests || []).filter(r => r?.direction === 'received');
        setPendingRequestsCount(received.length);
      } catch (err) {
        console.error('[TopBar] Error fetching friend requests:', err);
        setPendingRequestsCount(0);
      }
    };
    loadRequests();
    // Refresh every 30 seconds
    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 (simple: hide if already PWA)
  useEffect(() => {
    const checkInstall = () => {
      // Hide if already running as PWA
      if (isRunningAsPWA()) {
        setShowInstallBtn(false);
        return;
      }
      // Show if can install
      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)) {
        const who = (email || uname || last?.email || last?.username || "").trim();
        setSignupInfo("✅ " + t('auth.accountCreatedMsg') + (who ? " (" + who + ")" : ""));
        setMode("login");
        setShowAuth(true);

        const prefill = (uname || email || last?.username || last?.email || "").trim();
        if (prefill) setLoginUser(prefill);
      } 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) {
      // ignore
    }
  }, []);

  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) {
      console.error(err);
      setSignupError(err.message || t('auth.registrationError'));
    } finally {
      setSignupLoading(false);
    }
  };

  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]);

  return (
    <>
      {/* Toast area (under topbar) */}
      {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>
      ) : null}

      <header className="topbar">
        <div className="brand-stack">
          <div className="brand-toprow">
            <div className="logo-circle"><img src="/logo.png" alt="SocioWire" /></div>
            <div className="title-block">
              <div className="main-title">SOCIOWIRE.com</div>
              <div className="sub-title">{t('topbar.wiredToLife')}</div>
            </div>
          </div>

          {/* Theme dots */}
          <div className="brand-under">
            <div className="theme-switch">
              {["dark", "blue", "light"].map((themeKey) => (
                <button
                  key={themeKey}
                  type="button"
                  className={"theme-dot" + (theme === themeKey ? " theme-dot-active" : "")}
                  title={t(`theme.${themeKey}`)}
                  onClick={() => onChangeTheme && onChangeTheme(themeKey)}
                >
                  {t(`theme.${themeKey}`)[0]}
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="topbar-right">
          {/* User info */}
          <div className="topbar-user-section">
            {authenticated ? (
              <button
                type="button"
                className="sw-userchip sw-userchip-btn"
                title={username}
                onClick={() => onUserIsland && onUserIsland(username)}
              >
                <div className="sw-avatar">
                  {avatarUrl ? <img src={toSmallImageUrl(avatarUrl)} alt={username} /> : <span>{initialLetter(username)}</span>}
                </div>
                <div className="sw-usertext">
                  <div className="sw-userline">{t('common.online')}</div>
                  <div className="sw-userhandle">@{displayUsername}</div>
                </div>
              </button>
            ) : (
              <div className="sw-userchip" title={t('common.guest')}>
                <div className="sw-avatar sw-avatar-guest">
                  <i className="fa-solid fa-user" />
                </div>
                <div className="sw-usertext">
                  <div className="sw-userline">{loading ? t('common.loading') : t('common.guest')}</div>
                  <div className="sw-userhandle">{t('common.anon')}</div>
                </div>
              </div>
            )}

          </div>

          {/* Action buttons - separate section */}
          <div className="topbar-actions">
            {/* PWA Install button - no dismiss X */}
            {showInstallBtn && (
              <button
                className="btn-action btn-action-install"
                type="button"
                onClick={() => promptInstall()}
                title={t('topbar.installApp')}
              >
                <i className="fa-solid fa-download"></i>
              </button>
            )}

            {/* Theme selector (mobile dropdown) */}
            <div className="theme-selector-wrap">
              <button
                ref={themeBtnRef}
                className={"btn-action btn-action-theme" + (showThemeMenu ? " is-active" : "")}
                type="button"
                onClick={toggleThemeMenu}
                title={t(`theme.${theme}`)}
              >
                <i className="fa-solid fa-palette"></i>
              </button>
              {showThemeMenu && (
                <div
                  className="theme-dropdown"
                  style={{ top: themeMenuPos.top, right: themeMenuPos.right }}
                >
                  {THEMES.map((themeKey) => (
                    <button
                      key={themeKey}
                      type="button"
                      className={"theme-option" + (theme === themeKey ? " is-active" : "")}
                      onClick={() => {
                        onChangeTheme && onChangeTheme(themeKey);
                        setShowThemeMenu(false);
                      }}
                    >
                      {t(`theme.${themeKey}`)}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Language selector */}
            <div className="lang-selector-wrap">
              <button
                ref={langBtnRef}
                className={"btn-action btn-action-lang" + (showLangMenu ? " is-active" : "")}
                type="button"
                onClick={toggleLangMenu}
                title={t('language.selectLanguage')}
              >
                <i className="fa-solid fa-globe"></i>
                <span className="btn-label">{i18n.language?.toUpperCase().slice(0, 2)}</span>
              </button>
              {showLangMenu && (
                <div
                  className="lang-dropdown"
                  style={{ top: langMenuPos.top, right: langMenuPos.right }}
                >
                  {SUPPORTED_LANGS.map((lang) => (
                    <button
                      key={lang}
                      type="button"
                      className={"lang-option" + (i18n.language?.startsWith(lang) ? " is-active" : "")}
                      onClick={() => changeLanguage(lang)}
                    >
                      {t(`language.${lang}`)}
                    </button>
                  ))}
                </div>
              )}
            </div>

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

            {/* Login/Logout button */}
            <button
              className="btn-action btn-action-auth"
              type="button"
              onClick={() => {
                if (authenticated) {
                  trackEvent("logout_click");
                  logout();
                } else {
                  openModal("login");
                }
              }}
              disabled={loading}
              title={authenticated ? t('topbar.logout') : t('topbar.login')}
            >
              <i className={authenticated ? "fa-solid fa-right-from-bracket" : "fa-solid fa-right-to-bracket"}></i>
              <span className="btn-label">{authenticated ? t('topbar.logout') : t('topbar.login')}</span>
            </button>
          </div>
        </div>
      </header>

      {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> : null}
            {authNotice ? <div className="auth-notice auth-notice-warn">{authNotice}</div> : null}
            {mode === "login" && lastError ? (
              <div className={"auth-notice " + (needsEmailVerification ? "auth-notice-warn" : "auth-notice-error")}>
                {lastError}
              </div>
            ) : null}

            {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>
                ) : null}

                {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>
                  </>
                ) : null}

              </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> : null}

                <button type="submit" className="btn-primary btn-full" disabled={signupLoading}>
                  {signupLoading ? "..." : t('auth.createAccount')}
                </button>
              </form>
            )}
          </div>
        </div>
      ) : null}

      {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> : null}
            {usernameInfo ? <div className="auth-notice auth-notice-success">{usernameInfo}</div> : null}
            <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>
      ) : null}

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