
// FriendBarV2.jsx — Replacement top header.
// Layout:
//   Left   — Cozy Draft logo with paw mascot + hexagonal lobby code badge
//   Center — Live presence cluster: overlapping hex avatars per claimed player
//            (pulsing green dot when online; hover tooltip = name + role)
//   Right  — Identity badge: my colour hex + name + role icon + chevron menu
//            (Change name · Release lane · Re-do onboarding · Leave lobby)

const { useState, useRef, useEffect } = React;

function ThemeTogglePill() {
  const [theme, setTheme] = useState(() => {
    return document.documentElement.getAttribute('data-theme') || 'light';
  });

  const toggleTheme = () => {
    const nextTheme = theme === 'dark' ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', nextTheme);
    try {
      localStorage.setItem('cozy_theme', nextTheme);
    } catch (e) {}
    setTheme(nextTheme);
  };

  const isDark = theme === 'dark';

  return (
    <button
      onClick={toggleTheme}
      className="header-theme-toggle cozy-btn"
      title={isDark ? 'Switch to Light Mode ☀️' : 'Switch to Dark Mode 🌙'}
      aria-label="Toggle theme"
      style={{
        position: 'relative',
        display: 'inline-flex',
        alignItems: 'center',
        width: 56,
        height: 30,
        padding: 0,
        background: 'var(--surface-nested)',
        border: '1.5px solid var(--border-emphasis)',
        borderRadius: 16,
        cursor: 'pointer',
        flexShrink: 0,
        overflow: 'hidden',
        boxSizing: 'border-box',
        transition: 'background 0.23s ease, border-color 0.23s ease',
      }}
    >
      {/* Sun icon on left track */}
      <span style={{
        position: 'absolute',
        left: 6,
        fontSize: 12,
        lineHeight: 1,
        userSelect: 'none',
        opacity: isDark ? 0.85 : 0.4,
        transition: 'opacity 0.23s ease',
      }}>
        ☀️
      </span>

      {/* Moon icon on right track */}
      <span style={{
        position: 'absolute',
        right: 6,
        fontSize: 12,
        lineHeight: 1,
        userSelect: 'none',
        opacity: isDark ? 0.4 : 0.85,
        transition: 'opacity 0.23s ease',
      }}>
        🌙
      </span>

      {/* Sliding Knob */}
      <span
        style={{
          position: 'absolute',
          top: 2,
          left: isDark ? 28 : 2,
          width: 22,
          height: 22,
          borderRadius: '50%',
          background: 'var(--surface-card)',
          border: '1.5px solid var(--border-emphasis)',
          boxShadow: '0 2px 4px var(--border-default)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: 11,
          lineHeight: 1,
          transition: 'left 230ms cubic-bezier(0.4, 0, 0.2, 1)',
          zIndex: 2,
        }}
      >
        {isDark ? '🌙' : '☀️'}
      </span>
    </button>
  );
}

function FriendBarV2({ onOpenOnboarding }) {
  const {
    players, myUserId, sessionUserId, lobbyCode, teamName, myTeams,
    activePlayerId, setActivePlayer, setTab,
    updatePlayerName, updatePlayerIdentity, releaseLane, leaveLobby,
    setOnboarded, setLobbyCode, kickPlayer, resetLobby, showToast,
    POSITION_COLORS, POSITION_LABELS, IDENTITY_COLORS, userProfile, signOutUser,
  } = window.useApp();

  const ROLE_EMOJIS = {
    TOP: '⚔️',
    JUNGLE: '🌾',
    MID: '🔮',
    ADC: '🏹',
    SUPPORT: '💛',
  };

  const [menuOpen, setMenuOpen] = useState(false);
  const [teamMenuOpen, setTeamMenuOpen] = useState(false);
  const [editName, setEditName] = useState(false);
  const [nameDraft, setNameDraft] = useState('');
  const [pickColor, setPickColor] = useState(false);
  const [manageOpen, setManageOpen] = useState(false);
  const [showLeaveModal, setShowLeaveModal] = useState(false);
  const menuRef = useRef(null);
  const teamMenuRef = useRef(null);

  const authUser = window.firebase && window.firebase.auth && window.firebase.auth().currentUser;
  const authUid = authUser ? authUser.uid : null;

  const me = players.find(p => p && (p.claimed || !!p.ownerId || !!p.uid) && (
    (authUid && (p.uid === authUid || p.ownerId === authUid)) ||
    (!authUid && sessionUserId && p.ownerId === sessionUserId)
  )) || null;

  const iOwnALane = !!(me && (me.claimed || me.ownerId));

  const myDisplayName = (iOwnALane && me && me.name) ? me.name : (userProfile?.displayName || (me && me.name) || 'Player');
  const myIdentityColor = (iOwnALane && me && me.identityColor) ? me.identityColor : (userProfile?.identityColor || (me && me.identityColor) || '#F7DFA0');
  const myPosition = iOwnALane && me ? me.position : (userProfile?.preferredLane || 'JUNGLE');

  useEffect(() => {
    const handler = (e) => {
      if (menuRef.current && !menuRef.current.contains(e.target)) {
        setMenuOpen(false); setEditName(false); setPickColor(false);
      }
      if (teamMenuRef.current && !teamMenuRef.current.contains(e.target)) {
        setTeamMenuOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const saveName = () => {
    if (me && nameDraft.trim().length >= 2) updatePlayerIdentity(me.id, { name: nameDraft.trim() });
    setEditName(false);
  };

  const handleSignOut = async () => {
    setMenuOpen(false);
    if (typeof signOutUser === 'function') {
      await signOutUser();
    } else {
      try {
        if (window.firebase && window.firebase.auth) {
          await window.firebase.auth().signOut();
        }
      } catch (e) {}
      setLobbyCode(null);
      setOnboarded(false);
    }
    if (showToast) showToast('Signed out 🌸');
  };

  // ---------------------------------------------------------------------------
  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 200,
      background: 'var(--surface-page)', borderBottom: '2px solid var(--border-default)',
      padding: '8px 16px', display: 'flex', alignItems: 'center',
      justifyContent: 'space-between', height: 56, gap: 12,
    }}>
      {/* ── LEFT: Logo + lobby code + theme toggle ───────────────────────── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
        <button
          onClick={() => setTab('home')}
          aria-label="Go to home"
          style={{
            display: 'flex', alignItems: 'center', gap: 6,
            background: 'none', border: 'none', padding: 0,
            cursor: 'pointer',
          }}
        >
          <div style={{
            width: 34, height: 34, borderRadius: '50%',
            background: 'var(--surface-nested)', border: '2px solid var(--border-emphasis)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>
            <window.PawMascot size={24} color="var(--accent-orange)" />
          </div>
          <span className="fredoka header-logo-text" style={{ color: 'var(--accent-orange)', fontSize: 20, whiteSpace: 'nowrap' }}>
            Cozy Draft
          </span>
        </button>

        {/* Lobby badge — click opens Team Switcher Popover */}
        {lobbyCode ? (
          <div ref={teamMenuRef} style={{ position: 'relative' }}>
            <button
              onClick={() => setTeamMenuOpen(o => !o)}
              className="header-lobby-badge cozy-btn"
              title={`Lobby code ${lobbyCode} — Click to switch teams or return to dashboard`}
              style={{
                display: 'flex', alignItems: 'center', gap: 6,
                background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
                borderRadius: 14, padding: '3px 10px 3px 4px',
                fontFamily: "'Nunito', sans-serif", fontWeight: 800, fontSize: 11,
                color: 'var(--text-primary)', letterSpacing: 0.5, whiteSpace: 'nowrap',
                cursor: 'pointer',
              }}
            >
              <window.HexFrame size={22} color="#F7DFA0" borderColor="var(--border-emphasis)" borderWidth={1.5} />
              <span style={{ color: 'var(--text-muted)', fontSize: 10 }}>LOBBY</span>
              <span className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 14, letterSpacing: 1 }}>{lobbyCode}</span>
              <span style={{ fontSize: 10, color: 'var(--accent-orange)' }}>{teamMenuOpen ? '▲' : '▾'}</span>
            </button>

            {teamMenuOpen && (
              <div className="pop-in" style={{
                position: 'absolute', top: 'calc(100% + 8px)', left: 0,
                background: 'var(--surface-page)', border: '2px solid var(--border-emphasis)',
                borderRadius: 18, padding: 14, minWidth: 260,
                boxShadow: '0 10px 32px var(--border-default)', zIndex: 300,
                transformOrigin: 'top left',
              }}>
                {/* MY TEAMS header */}
                <div style={{
                  fontSize: 11, fontFamily: "'Nunito', sans-serif", fontWeight: 800,
                  color: 'var(--text-muted)', letterSpacing: 0.8, textTransform: 'uppercase',
                  marginBottom: 8, paddingLeft: 2
                }}>
                  MY TEAMS ({(myTeams && myTeams.length) || (lobbyCode ? 1 : 0)})
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {((myTeams && myTeams.length > 0) ? myTeams : (lobbyCode ? [{
                    code: lobbyCode,
                    teamName: teamName || 'Cozy crew',
                    myRoleLabel: POSITION_LABELS[myPosition] || myPosition || 'Jungle',
                    myRoleEmoji: ROLE_EMOJIS[myPosition] || '🌾',
                  }] : [])).map(t => {
                    const isHere = t.code === lobbyCode;
                    return (
                      <div
                        key={t.code}
                        onClick={() => {
                          if (!isHere) {
                            setLobbyCode(t.code);
                            setTeamMenuOpen(false);
                          }
                        }}
                        style={{
                          background: isHere ? 'var(--surface-nested)' : 'var(--surface-page)',
                          border: isHere ? '1.5px solid var(--border-emphasis)' : '1px solid var(--border-default)',
                          borderRadius: 14, padding: '8px 12px',
                          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
                          cursor: isHere ? 'default' : 'pointer'
                        }}
                      >
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                          <div style={{ fontSize: 20, flexShrink: 0 }}>
                            {t.myRoleEmoji || '🌾'}
                          </div>
                          <div style={{ minWidth: 0 }}>
                            <div className="fredoka" style={{
                              color: 'var(--text-primary)', fontSize: 14, lineHeight: 1.2,
                              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'
                            }}>
                              {t.teamName}
                            </div>
                            <div style={{
                              color: 'var(--text-muted)', fontFamily: "'Nunito', sans-serif", fontWeight: 700,
                              fontSize: 11, marginTop: 2
                            }}>
                              {t.code} {t.myRoleLabel ? `· ${t.myRoleLabel}` : ''}
                            </div>
                          </div>
                        </div>

                        {isHere && (
                          <div style={{
                            display: 'flex', alignItems: 'center', gap: 4,
                            color: '#7CBF8E', fontFamily: "'Nunito', sans-serif", fontWeight: 800,
                            fontSize: 12, flexShrink: 0
                          }}>
                            <span style={{ fontSize: 8 }}>▪</span> here
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>

                {/* Divider */}
                <div style={{ borderTop: '1.5px solid var(--border-default)', margin: '10px 0 8px' }} />

                {/* All my teams / join another */}
                <button
                  onClick={() => {
                    setTeamMenuOpen(false);
                    setLobbyCode(null);
                  }}
                  className="cozy-btn"
                  style={{
                    width: '100%', background: 'transparent', border: 'none',
                    display: 'flex', alignItems: 'center', gap: 8, padding: '6px 4px',
                    cursor: 'pointer', textAlign: 'left'
                  }}
                >
                  <span style={{ fontSize: 16 }}>🌸</span>
                  <span className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 14 }}>
                    All my teams / join another
                  </span>
                </button>
              </div>
            )}
          </div>
        ) : (
          <div className="header-lobby-badge" style={{
            display: 'flex', alignItems: 'center', gap: 6,
            background: 'var(--surface-nested)', border: '1.5px dashed var(--border-emphasis)',
            borderRadius: 14, padding: '3px 10px 3px 6px',
            fontFamily: 'Nunito', fontWeight: 800, fontSize: 11,
            color: 'var(--text-muted)', whiteSpace: 'nowrap',
          }}>
            <span style={{ fontSize: 12 }}>🌸</span>
            <span>Dashboard</span>
          </div>
        )}

        {/* Dark Mode Toggle Pill */}
        <ThemeTogglePill />
      </div>

      {/* ── CENTER: Presence cluster ──────────────────────────────────────── */}
      {lobbyCode ? <PresenceCluster players={players} /> : <div style={{ flex: 1 }} />}

      {/* ── RIGHT: Identity badge + dropdown ──────────────────────────────── */}
      <div ref={menuRef} style={{ position: 'relative', flexShrink: 0 }}>
        <button
          onClick={() => setMenuOpen(o => !o)}
          className="cozy-btn"
          style={{
            display: 'flex', alignItems: 'center', gap: 6,
            background: 'var(--surface-nested)', border: '2px solid var(--border-default)',
            borderRadius: 20, padding: '3px 10px 3px 4px',
            fontFamily: 'Nunito', fontWeight: 800, fontSize: 12,
            color: 'var(--text-primary)', cursor: 'pointer',
            boxShadow: '0 2px 0 var(--border-default)',
          }}
        >
          <window.HexFrame size={30} color={myIdentityColor} borderColor="var(--border-emphasis)" borderWidth={2}>
            <span className="fredoka" style={{ color: 'var(--text-on-light-pastel)', fontSize: 13 }}>{myDisplayName[0]?.toUpperCase()}</span>
          </window.HexFrame>
          <span className="header-player-name" style={{ maxWidth: 85, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {myDisplayName}
          </span>
          <window.LaurelCrest size={14} color="#7CBF8E" />
          <span style={{ fontSize: 10, color: 'var(--accent-orange)' }}>{menuOpen ? '▲' : '▾'}</span>
        </button>

        {menuOpen && (
          <div className="pop-in" style={{
            position: 'absolute', top: 'calc(100% + 8px)', right: 0,
            background: 'var(--surface-page)', border: '2px solid var(--border-emphasis)',
            borderRadius: 16, padding: 10, minWidth: 240,
            boxShadow: '0 10px 32px var(--border-default)', zIndex: 300,
            transformOrigin: 'top right',
          }}>
            {/* Identity summary */}
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: 8, marginBottom: 6,
              background: myIdentityColor + '40',
              border: '1.5px solid ' + myIdentityColor,
              borderRadius: 12,
            }}>
              <window.HexFrame size={36} color={myIdentityColor} borderColor="var(--border-emphasis)" borderWidth={2}>
                <span className="fredoka" style={{ color: 'var(--text-on-light-pastel)', fontSize: 16 }}>{myDisplayName[0]?.toUpperCase()}</span>
              </window.HexFrame>
              <div style={{ flex: 1, minWidth: 0 }}>
                {editName ? (
                  <input
                    autoFocus
                    value={nameDraft}
                    onChange={e => setNameDraft(e.target.value.slice(0, 16))}
                    onBlur={saveName}
                    onKeyDown={e => e.key === 'Enter' && saveName()}
                    style={{
                      width: '100%', background: 'var(--surface-page)', border: '1.5px solid var(--border-emphasis)',
                      borderRadius: 8, padding: '2px 6px',
                      fontFamily: 'Fredoka One', fontSize: 16, color: 'var(--text-primary)', outline: 'none',
                    }}
                  />
                ) : (
                  <div className="fredoka" style={{ color: 'var(--text-primary)', fontSize: 16, lineHeight: 1.1 }}>{myDisplayName}</div>
                )}
                <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 700, color: 'var(--text-muted)', marginTop: 2 }}>
                  <window.RoleIcon pos={myPosition} size={14} />
                  <span>{POSITION_LABELS[myPosition] || myPosition}</span>
                </div>
              </div>
            </div>

            {/* Color row (collapsible) */}
            {pickColor && (
              <div style={{
                display: 'flex', gap: 6, flexWrap: 'wrap',
                padding: '8px 4px', marginBottom: 6,
                background: 'var(--surface-nested)', borderRadius: 12, border: '1.5px solid var(--border-default)',
              }}>
                {IDENTITY_COLORS.map(c => (
                  <button
                    key={c}
                    onClick={() => { updatePlayerIdentity(me.id, { identityColor: c }); setPickColor(false); }}
                    style={{ background: 'transparent', border: 'none', padding: 0, cursor: 'pointer' }}
                  >
                    <window.HexFrame size={24} color={c}
                      borderColor={c === me.identityColor ? 'var(--text-primary)' : 'var(--border-default)'}
                      borderWidth={c === me.identityColor ? 2 : 1.5}
                    />
                  </button>
                ))}
              </div>
            )}

            {/* Section 1 */}
            <MenuItem icon="✏️"  label="Change name"   onClick={() => { setEditName(true); setNameDraft(me.name); }} />
            <MenuItem icon="🎨"  label="Change colour" onClick={() => setPickColor(p => !p)} />
            <MenuItem icon="🛡️"  label="Release lane"  onClick={() => { releaseLane(me.id); setMenuOpen(false); }} disabled={!iOwnALane} />

            <div style={{ borderTop: '1.5px solid var(--border-default)', margin: '6px 0' }} />

            {/* Section 2 */}
            <MenuItem icon="🐾"  label="Re-do onboarding" onClick={() => { setMenuOpen(false); onOpenOnboarding && onOpenOnboarding(); }} />
            {lobbyCode && (
              <MenuItem icon="🚪"  label="Leave lobby" tone="warn" onClick={() => { setMenuOpen(false); setShowLeaveModal(true); }} />
            )}

            <div style={{ borderTop: '1.5px solid var(--border-default)', margin: '6px 0' }} />

            <MenuItem icon="🚪"  label="Sign out" tone="warn" onClick={handleSignOut} />
          </div>
        )}
      </div>

      {/* Destructive Leave Lobby Confirmation Modal */}
      {showLeaveModal && (
        <div
          onMouseDown={e => { if (e.target === e.currentTarget) setShowLeaveModal(false); }}
          style={{
            position: 'fixed', inset: 0, zIndex: 1000,
            background: 'rgba(74, 55, 40, 0.5)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 16,
          }}
        >
          <div className="cozy-card pop-in" style={{
            width: '100%', maxWidth: 440, padding: 24,
            display: 'flex', flexDirection: 'column', gap: 14,
            textAlign: 'center', background: 'var(--surface-page)', borderRadius: 20,
            position: 'relative'
          }}>
            <div className="corner-dot" style={{ top: 9, left: 9 }} />
            <div className="corner-dot" style={{ top: 9, right: 9 }} />
            <div className="corner-dot corner-dot-bl" />
            <div className="corner-dot corner-dot-br" />

            <div style={{ marginTop: 4 }}>
              <h2 className="fredoka" style={{ color: '#D9534F', fontSize: 22, margin: 0 }}>
                Leave {teamName || 'this team'}? 🚪
              </h2>
              <p style={{ color: 'var(--text-primary)', fontWeight: 700, fontSize: 14, marginTop: 12, lineHeight: 1.5 }}>
                Are you sure you want to leave {teamName || 'this team'}? Your claimed lane and lobby membership will be removed.
              </p>
            </div>

            <div style={{ display: 'flex', justifyContent: 'center', gap: 12, marginTop: 10 }}>
              <button
                type="button"
                onClick={() => setShowLeaveModal(false)}
                className="cozy-btn"
                style={{
                  padding: '10px 18px', background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
                  borderRadius: 14, fontFamily: 'Nunito', fontWeight: 800, fontSize: 13,
                  color: 'var(--text-primary)', cursor: 'pointer'
                }}
              >
                Cancel 👋
              </button>

              <button
                type="button"
                onClick={() => {
                  leaveLobby();
                  setShowLeaveModal(false);
                }}
                className="cozy-btn"
                style={{
                  padding: '10px 18px', background: '#D9534F', border: 'none',
                  borderRadius: 14, fontFamily: 'Fredoka One, cursive', fontSize: 14,
                  color: '#FFFFFF', cursor: 'pointer', boxShadow: '0 3px 0 #A93226'
                }}
              >
                Leave team 🚪
              </button>
            </div>
          </div>
        </div>
      )}

      <ManageMembersModal isOpen={manageOpen} onClose={() => setManageOpen(false)} />
    </div>
  );
}

function MenuItem({ icon, label, onClick, disabled = false, tone = 'default' }) {
  return (
    <button
      disabled={disabled}
      onClick={onClick}
      style={{
        display: 'flex', alignItems: 'center', gap: 10,
        width: '100%', padding: '8px 10px',
        background: 'transparent', border: 'none', borderRadius: 10,
        cursor: disabled ? 'not-allowed' : 'pointer',
        fontFamily: 'Nunito', fontWeight: 700, fontSize: 13,
        color: tone === 'warn' ? 'var(--accent-orange)' : 'var(--text-primary)',
        opacity: disabled ? 0.4 : 1,
        textAlign: 'left',
        transition: 'background 0.12s',
      }}
      onMouseEnter={e => { if (!disabled) e.currentTarget.style.background = 'var(--surface-nested)'; }}
      onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}
    >
      <span style={{ fontSize: 14, width: 18, textAlign: 'center' }}>{icon}</span>
      <span style={{ flex: 1 }}>{label}</span>
    </button>
  );
}

// -----------------------------------------------------------------------------
// PresenceCluster — clean 5-slot flex row (1 hex per lane, no overlapping)
// -----------------------------------------------------------------------------
function PresenceCluster({ players }) {
  const { myUserId, claimLane, releaseLane, updatePlayerIdentity, setMyUser, sessionUserId, tempIdentity } = window.useApp();
  const POSITION_LABELS = window.POSITION_LABELS || { TOP: 'Top', JUNGLE: 'Jungle', MID: 'Mid', ADC: 'ADC', SUPPORT: 'Support' };
  const POSITION_COLORS = window.POSITION_COLORS || { TOP: '#F7DFA0', JUNGLE: '#B8E0C0', MID: '#C5B4E3', ADC: '#F2A7C3', SUPPORT: '#AED6F1' };
  const POSITIONS = window.POSITIONS || ['TOP', 'JUNGLE', 'MID', 'ADC', 'SUPPORT'];

  const authUser = window.firebase && window.firebase.auth && window.firebase.auth().currentUser;
  const authUid = authUser ? authUser.uid : null;

  const me = players.find(p => p.ownerId && p.ownerId === sessionUserId) || players.find(p => p.id === myUserId) || players[0];
  const iAmClaimed = !!players.find(p => (p.ownerId === sessionUserId || p.id === myUserId) && (p.claimed || !!p.ownerId));
  const myClaim = players.find((p) => p.ownerId === sessionUserId);
  const mySessionName = (tempIdentity && tempIdentity.displayName) || myClaim?.name || me?.name || 'You';

  const [pickerOpen, setPickerOpen] = useState(false);
  const [reclaimTarget, setReclaimTarget] = useState(null);
  const [confirmTapCount, setConfirmTapCount] = useState(0);
  const pickerRef = useRef(null);

  useEffect(() => {
    if (!pickerOpen) return;
    const handler = (e) => { if (pickerRef.current && !pickerRef.current.contains(e.target)) setPickerOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [pickerOpen]);

  const moveTo = (targetPlayer, force = false) => {
    const mySlot = players.find(p => p.ownerId && p.ownerId === sessionUserId);
    const myName = mySlot?.name || me.name;
    const myColor = mySlot?.identityColor || me.identityColor;
    if (mySlot && mySlot.id !== targetPlayer.id) releaseLane(mySlot.id);
    updatePlayerIdentity(targetPlayer.id, { name: myName, identityColor: myColor });
    claimLane(targetPlayer.id, sessionUserId, force || true);
    setMyUser(targetPlayer.id);
    setPickerOpen(false);
  };

  // Always 5 slots: claimed active hexes first, then placeholders
  const mainPlayers = (players || []).filter(p => p && !p.isSub);
  const fiveLanes = POSITIONS.map(pos => mainPlayers.find(p => p.position === pos) || players.find(p => p.position === pos) || { position: pos, claimed: false });
  const sortedLanes = fiveLanes.slice().sort((a, b) => ((b.claimed || b.ownerId) ? 1 : 0) - ((a.claimed || a.ownerId) ? 1 : 0));

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 6,
      minWidth: 0, position: 'relative',
    }} ref={pickerRef}>
      {/* CREW switch label / Lock-in button */}
      {iAmClaimed ? (
        <button
          onClick={() => setPickerOpen(o => !o)}
          title="Switch lane"
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 3,
            background: 'transparent', border: 'none', padding: '4px 4px',
            fontSize: 10, fontWeight: 800, color: 'var(--text-muted)', letterSpacing: 1,
            cursor: 'pointer', whiteSpace: 'nowrap',
            fontFamily: 'Nunito', borderRadius: 8, flexShrink: 0,
            transition: 'background 0.15s, color 0.15s',
          }}
          onMouseEnter={e => { e.currentTarget.style.background = 'var(--surface-nested)'; e.currentTarget.style.color = 'var(--accent-orange)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--text-muted)'; }}
        >
          <window.CrystalSparkle size={10} color="var(--text-muted)" /> CREW
        </button>
      ) : (
        <button
          onClick={() => setPickerOpen(o => !o)}
          className="cozy-btn"
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            background: '#B8E0C0', border: '2px solid #7CBF8E',
            borderRadius: 14, padding: '3px 8px',
            fontFamily: 'Nunito', fontWeight: 800, fontSize: 11,
            color: '#3F6B4D', cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0,
            boxShadow: '0 2px 0 #7CBF8E80',
            animation: 'lock-pulse 2s ease-in-out infinite',
          }}
        >
          <window.LaurelCrest size={13} color="#3F6B4D" />
          Lock in
        </button>
      )}

      {pickerOpen && (
        <div className="pop-in" style={{
          position: 'absolute', top: 'calc(100% + 8px)', left: 0,
          background: 'var(--surface-page)', border: '2px solid var(--border-emphasis)',
          borderRadius: 16, padding: 12, minWidth: 260,
          boxShadow: '0 12px 32px var(--border-default)', zIndex: 320,
          transformOrigin: 'top left',
        }}>
          <div style={{
            fontFamily: 'Fredoka One, cursive', color: 'var(--accent-orange)',
            fontSize: 14, marginBottom: 4,
          }}>
            Lock in your lane
          </div>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)', marginBottom: 10 }}>
            Pick an open lane — your identity moves with you.
          </div>
            {players.map(p => {
              const isMine = !!(p && (p.claimed || p.ownerId || p.uid) && (
                (authUid && (p.uid === authUid || p.ownerId === authUid)) ||
                (!authUid && sessionUserId && p.ownerId === sessionUserId)
              ));
              const lockedByOther = (p.claimed || !!p.ownerId || !!p.uid) && !isMine;
              return (
                <button
                  key={p.id}
                  onClick={() => {
                    if (isMine) return;
                    if (lockedByOther) {
                      setReclaimTarget(p);
                      setConfirmTapCount(0);
                      setPickerOpen(false);
                    } else {
                      moveTo(p);
                    }
                  }}
                  disabled={isMine}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    width: '100%', padding: '6px 10px',
                    background: isMine ? me.identityColor + '50' : (lockedByOther ? 'var(--surface-nested)' : 'var(--surface-card)'),
                    border: isMine ? `2px dashed var(--border-emphasis)` : `1.5px solid ${lockedByOther ? 'var(--border-default)' : 'var(--border-default)'}`,
                    borderRadius: 12, cursor: isMine ? 'default' : 'pointer',
                    fontFamily: 'Nunito', fontWeight: 800, fontSize: 13, color: 'var(--text-primary)',
                    textAlign: 'left', opacity: isMine ? 0.7 : 1,
                    transition: 'transform 0.12s',
                  }}
                >
                  <window.HexFrame size={28} color={POSITION_COLORS[p.position]} borderColor="var(--border-emphasis)" borderWidth={2}>
                    <window.RoleIcon pos={p.position} size={16} />
                  </window.HexFrame>
                  <span style={{ flex: 1 }}>{POSITION_LABELS[p.position]}</span>
                  {isMine && (
                    <span style={{ fontSize: 10, color: 'var(--accent-orange)', display: 'inline-flex', alignItems: 'center', gap: 3 }}>
                      <window.LaurelCrest size={11} color="#7CBF8E" /> you
                    </span>
                  )}
                  {lockedByOther && (
                    <span style={{ fontSize: 10, color: '#E89818', fontWeight: 800, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                      🔒 Reclaim ({p.name})
                    </span>
                  )}
                  {!p.claimed && (
                    <span style={{ fontSize: 10, color: '#7CBF8E', fontWeight: 800 }}>OPEN</span>
                  )}
                </button>
              );
            })}
          </div>
      )}

      {/* Reclaim confirmation modal */}
      {reclaimTarget && (
        <div
          onMouseDown={e => { if (e.target === e.currentTarget) { setReclaimTarget(null); setConfirmTapCount(0); } }}
          style={{
            position: 'fixed', inset: 0, zIndex: 1000,
            background: 'rgba(74, 55, 40, 0.5)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 16,
          }}
        >
          <div className="cozy-card pop-in" style={{
            width: '100%', maxWidth: 440, padding: 24,
            display: 'flex', flexDirection: 'column', gap: 14,
            textAlign: 'center', background: 'var(--surface-page)', borderRadius: 20,
            position: 'relative'
          }}>
            <div className="corner-dot" style={{ top: 9, left: 9 }} />
            <div className="corner-dot" style={{ top: 9, right: 9 }} />
            <div className="corner-dot corner-dot-bl" />
            <div className="corner-dot corner-dot-br" />

            <div style={{ marginTop: 4 }}>
              <h2 className="fredoka" style={{ color: reclaimTarget.online ? '#D9534F' : 'var(--accent-orange)', fontSize: 22, margin: 0 }}>
                {reclaimTarget.online ? 'Take Over Active Lane ⚠️' : 'Reclaim Lane 🔄'}
              </h2>
              <p style={{ color: 'var(--text-primary)', fontWeight: 700, fontSize: 14, marginTop: 12, lineHeight: 1.5 }}>
                {reclaimTarget.online
                  ? `${reclaimTarget.name} is currently active in this lane. Are you sure you want to take over? This may disrupt them.`
                  : `${reclaimTarget.name} hasn't been active. Claim this lane as ${mySessionName}?`}
              </p>
            </div>

            <div style={{ display: 'flex', justifyContent: 'center', gap: 12, marginTop: 10 }}>
              <window.CozyButton color="cream" onClick={() => { setReclaimTarget(null); setConfirmTapCount(0); }}>
                Cancel 👋
              </window.CozyButton>

              {!reclaimTarget.online ? (
                <window.CozyButton color="sage" onClick={() => {
                  moveTo(reclaimTarget, true);
                  setReclaimTarget(null);
                  setConfirmTapCount(0);
                }}>
                  Claim lane 🛡️
                </window.CozyButton>
              ) : (
                <window.CozyButton
                  color={confirmTapCount === 1 ? "terracotta" : "cream"}
                  style={confirmTapCount === 1 ? { background: '#E85555', color: '#FFF', fontWeight: 900 } : {}}
                  onClick={() => {
                    if (confirmTapCount === 0) {
                      setConfirmTapCount(1);
                    } else {
                      moveTo(reclaimTarget, true);
                      setReclaimTarget(null);
                      setConfirmTapCount(0);
                    }
                  }}>
                  {confirmTapCount === 1 ? "Tap again to confirm ⚠️" : "Confirm Takeover ⚠️"}
                </window.CozyButton>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Hex flex row (max 3 on mobile, 5 on desktop) */}
      <div className="presence-avatars-scroll" style={{
        display: 'flex', alignItems: 'center', gap: 6,
        flexWrap: 'nowrap', overflowX: 'auto', scrollbarWidth: 'none',
      }}>
        {sortedLanes.map((slot, index) => (
          <div key={slot.position} className={index >= 3 ? "desktop-only-hex" : ""}>
            <PresenceSlot slot={slot} />
          </div>
        ))}
      </div>
    </div>
  );
}

function PresenceSlot({ slot }) {
  const [hover, setHover] = useState(false);
  const POSITION_LABELS = window.POSITION_LABELS;
  const isClaimed = slot.claimed || !!slot.ownerId;

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        height: 34,
        position: 'relative',
        cursor: isClaimed ? 'default' : 'pointer',
        opacity: isClaimed ? 1 : 0.45,
        filter: isClaimed ? 'none' : 'grayscale(80%)',
        flexShrink: 0,
        transition: 'transform 0.18s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.18s',
      }}
    >
      <window.HexFrame
        size={34}
        color={isClaimed ? slot.identityColor : 'var(--surface-nested)'}
        borderColor={isClaimed ? 'var(--border-emphasis)' : 'var(--border-default)'}
        borderWidth={isClaimed ? 2 : 1.5}
      >
        {isClaimed ? (
          <span className="fredoka" style={{ color: 'var(--text-on-light)', fontSize: 14 }}>
            {slot.name[0]?.toUpperCase()}
          </span>
        ) : (
          <window.RoleIcon pos={slot.position} size={15} />
        )}
      </window.HexFrame>

      {/* Green presence dot anchored at bottom of claimed slot */}
      {isClaimed && (
        <div
          title={slot.online ? 'Online' : 'Offline'}
          style={{
            position: 'absolute', bottom: -1, right: -1,
            width: 10, height: 10, borderRadius: '50%',
            background: slot.online ? '#7CBF8E' : 'var(--border-default)',
            border: '2px solid var(--surface-page)',
            animation: slot.online ? 'pulse-dot 1.6s ease-out infinite' : 'none',
          }}
        />
      )}

      {/* Tooltip */}
      {hover && (
        <div style={{
          position: 'absolute', top: '100%', left: '50%',
          transform: 'translate(-50%, 8px)',
          background: 'var(--text-primary)', color: 'var(--surface-page)',
          padding: '5px 10px', borderRadius: 10,
          fontFamily: 'Nunito', fontWeight: 800, fontSize: 11,
          whiteSpace: 'nowrap', zIndex: 400,
          boxShadow: '0 6px 20px rgba(0,0,0,0.3)',
          display: 'flex', alignItems: 'center', gap: 6,
        }}>
          {isClaimed ? (
            <>
              <span>{slot.name}</span>
              <span style={{ opacity: 0.7 }}>·</span>
              <window.RoleIcon pos={slot.position} size={13} />
              <span>{POSITION_LABELS[slot.position]}</span>
            </>
          ) : (
            <span>Open {POSITION_LABELS[slot.position]} slot</span>
          )}
        </div>
      )}
    </div>
  );
}

// CSS injected once
if (typeof document !== 'undefined' && !document.getElementById('friendbar-v2-css')) {
  const style = document.createElement('style');
  style.id = 'friendbar-v2-css';
  style.textContent = `
    @keyframes pulse-dot {
      0%   { box-shadow: 0 0 0 0 #7CBF8E80; }
      70%  { box-shadow: 0 0 0 8px #7CBF8E00; }
      100% { box-shadow: 0 0 0 0 #7CBF8E00; }
    }
    @keyframes hextech-shimmer {
      0%, 100% { box-shadow: 0 0 0 0 #C5B4E300, 4px 4px 0 #C4845A25; }
      50%      { box-shadow: 0 0 0 8px #C5B4E340, 4px 4px 0 #C4845A25; }
    }
    @keyframes lock-pulse {
      0%, 100% { box-shadow: 0 2px 0 #7CBF8E80, 0 0 0 0 #7CBF8E60; }
      50%      { box-shadow: 0 2px 0 #7CBF8E80, 0 0 0 6px #7CBF8E00; }
    }
    .hex-shimmer { animation: hextech-shimmer 2.2s ease-in-out infinite; }
    .presence-avatars-scroll::-webkit-scrollbar { display: none; }
    @media (max-width: 600px) {
      .header-logo-text { display: none !important; }
      .header-lobby-badge { display: none !important; }
      .desktop-only-hex { display: none !important; }
      .header-player-name { max-width: 60px !important; }
      .presence-avatars-scroll { gap: 6px !important; }
    }
  `;
  document.head.appendChild(style);
}

function ManageMembersModal({ isOpen, onClose }) {
  const { players, sessionUserId, kickPlayer, resetLobby, showToast, POSITION_COLORS, POSITION_LABELS } = window.useApp();
  if (!isOpen) return null;

  const me = players.find(p => p.ownerId && p.ownerId === sessionUserId) || players[0];

  const handleKick = (player) => {
    if (player.ownerId && player.ownerId === sessionUserId) return;
    if (confirm(`Are you sure you want to kick ${player.name} from their lane?`)) {
      kickPlayer(player.id);
      showToast(`Kicked ${player.name} from the lobby ✕`);
    }
  };

  const handleReset = () => {
    if (confirm('Are you sure you want to reset this lobby? This will unclaim all lanes.')) {
      resetLobby();
      showToast('Lobby slots have been reset 🔄');
      onClose();
    }
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(74, 55, 40, 0.5)', zIndex: 500,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} className="cozy-card pop-in" style={{
        width: 480, maxWidth: '95%', padding: 24, background: 'var(--surface-page)',
        display: 'flex', flexDirection: 'column', gap: 16,
      }}>
        {/* Title */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: '2px solid var(--border-default)', paddingBottom: 10 }}>
          <h2 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 20, margin: 0, display: 'flex', alignItems: 'center', gap: 8 }}>
            🛠️ Manage Lobby Members
          </h2>
          <button onClick={onClose} style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            fontSize: 18, color: 'var(--text-muted)',
          }}>✕</button>
        </div>

        {/* Members Roster */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {players.map(p => {
            const playerClaimed = p.claimed || !!p.ownerId;
            const isMe = !!(playerClaimed && (p.ownerId === sessionUserId || p.id === myUserId));
            const tint = POSITION_COLORS[p.position];
            return (
              <div key={p.id} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
                borderRadius: 16, padding: '10px 14px',
              }}>
                <window.HexFrame size={36} color={playerClaimed ? p.identityColor : tint} borderColor="var(--border-emphasis)" borderWidth={2}>
                  <window.RoleIcon pos={p.position} size={18} />
                </window.HexFrame>
                
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="fredoka" style={{ color: 'var(--text-primary)', fontSize: 15, textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>
                    {playerClaimed ? p.name : <span style={{ fontStyle: 'italic', opacity: 0.65 }}>Unclaimed</span>}
                  </div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)' }}>
                    Lane: {POSITION_LABELS[p.position]} {isMe && '• (You)'}
                  </div>
                </div>

                {playerClaimed && !isMe && (
                  <button
                    onClick={() => handleKick(p)}
                    className="cozy-btn"
                    style={{
                      background: '#F9D0D0', border: '1.5px solid #E8A0A0',
                      borderRadius: 12, padding: '4px 10px',
                      fontFamily: 'Nunito', fontWeight: 800, fontSize: 11,
                      color: '#8b3a3a', cursor: 'pointer',
                      transition: 'background 0.12s',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = '#F6B4B4'}
                    onMouseLeave={e => e.currentTarget.style.background = '#F9D0D0'}
                  >
                    Kick ✕
                  </button>
                )}
              </div>
            );
          })}
        </div>

        {/* Footer & Reset Button */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, borderTop: '2px solid var(--border-default)', paddingTop: 14, marginTop: 4 }}>
          <button
            onClick={handleReset}
            className="cozy-btn"
            style={{
              width: '100%', padding: '10px 14px',
              background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
              borderRadius: 14, fontFamily: 'Nunito', fontWeight: 800, fontSize: 13,
              color: 'var(--text-primary)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              transition: 'background 0.12s',
            }}
          >
            Reset this lobby 🔄
          </button>
          
          <button
            onClick={onClose}
            className="cozy-btn"
            style={{
              width: '100%', padding: '10px 14px',
              background: 'var(--accent-orange)', border: 'none',
              borderRadius: 14, fontFamily: 'Nunito', fontWeight: 800, fontSize: 13,
              color: 'white', cursor: 'pointer',
              boxShadow: '0 3px 0 rgba(0,0,0,0.2)',
            }}
          >
            Close
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { FriendBarV2, ManageMembersModal });
