
// MyPool.jsx — Account-level Champion Pools editor with Role Tabs & Granular RTDB Writes
const { useState, useMemo, useRef, useEffect } = React;
const { useApp } = window;

const FILTER_TAGS = window.FILTER_TAGS || ['All', 'Tank', 'Fighter', 'Mage', 'Assassin', 'Marksman', 'Support'];
const FILTER_EMOJIS = window.FILTER_EMOJIS || { All:'🌟', Tank:'🛡️', Fighter:'💪', Mage:'🔮', Assassin:'🗡️', Marksman:'🏹', Support:'💛' };

const ROLES = [
  { id: 'TOP', label: 'Top', emoji: '⚔️', color: '#F7DFA0', roleLabel: 'Top Laner' },
  { id: 'JUNGLE', label: 'Jungle', emoji: '🌿', color: '#B8E0C0', roleLabel: 'Jungler' },
  { id: 'MID', label: 'Mid', emoji: '🔮', color: '#C5B4E3', roleLabel: 'Mid Laner' },
  { id: 'ADC', label: 'ADC', emoji: '🏹', color: '#F2A7C3', roleLabel: 'Bot Laner' },
  { id: 'SUPPORT', label: 'Support', emoji: '💛', color: '#AED6F1', roleLabel: 'Support' },
];

function MyPool() {
  const { champions, championsLoading, showToast, setTab, lobbyCode, players, sessionUserId, myUserId, getEffectivePlayerPool } = useApp();

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

  const [activeRole, setActiveRole] = useState('TOP');
  const [accountPool, setAccountPool] = useState({});
  const [showAddModal, setShowAddModal] = useState(false);
  const [filterTag, setFilterTag] = useState('All');
  const [search, setSearch] = useState('');
  const searchInputRef = useRef(null);

  // In-lobby slot and override detection
  const mySlot = (lobbyCode && players) ? (
    players.find(p => p && (p.claimed || !!p.ownerId || !!p.uid) && (
      (uid && (p.uid === uid || p.ownerId === uid)) ||
      (!uid && sessionUserId && p.ownerId === sessionUserId)
    ))
  ) : null;

  const claimedRole = mySlot && (mySlot.claimed || !!mySlot.ownerId) ? mySlot.position : null;
  const isLockedToLane = Boolean(lobbyCode && claimedRole);
  const lockedRoleObj = isLockedToLane ? ROLES.find(r => r.id === String(claimedRole).toUpperCase()) : null;
  const lockedRoleLabel = lockedRoleObj ? lockedRoleObj.label : (claimedRole || '');

  const mySlotIdx = mySlot ? players.findIndex(p => p.id === mySlot.id) : -1;
  const hasRoomOverride = Boolean(mySlot && Array.isArray(mySlot.pool) && mySlot.pool.length > 0);

  // Auto-switch to claimed role in lobby context
  useEffect(() => {
    if (lobbyCode && claimedRole) {
      const normalized = String(claimedRole).toUpperCase();
      if (ROLES.some(r => r.id === normalized)) {
        setActiveRole(normalized);
      }
    }
  }, [lobbyCode, claimedRole]);

  // 1. Load account's preferredLane from onboarding on mount (dashboard context)
  useEffect(() => {
    if (lobbyCode && claimedRole) return;
    if (!uid || !window.db) return;
    window.db.ref(`users/${uid}/preferredLane`).once('value').then(snap => {
      const lane = snap.val();
      if (lane) {
        const normalized = String(lane).toUpperCase();
        if (ROLES.some(r => r.id === normalized)) {
          setActiveRole(normalized);
        }
      }
    }).catch(() => {});
  }, [uid, lobbyCode, claimedRole]);

  // 2. Realtime listener for users/{uid}/pools/{activeRole}/champions
  useEffect(() => {
    if (!uid || !window.db) return;
    const poolRef = window.db.ref(`users/${uid}/pools/${activeRole}/champions`);
    const listener = poolRef.on('value', (snap) => {
      setAccountPool(snap.val() || {});
    });
    return () => {
      try { poolRef.off('value', listener); } catch (e) {}
    };
  }, [uid, activeRole]);

  const activeRoleObj = ROLES.find(r => r.id === activeRole) || ROLES[0];

  const poolEntries = useMemo(() => {
    return Object.entries(accountPool).map(([champId, data]) => ({
      championId: champId,
      comfort: (data && data.comfort) || 2,
      notes: (data && data.notes) || '',
      isFocusPick: Boolean(data && (data.isFocusPick || data.focusPick)),
      focusPick: Boolean(data && (data.isFocusPick || data.focusPick)),
      focusSetAt: (data && data.focusSetAt) || null,
    }));
  }, [accountPool]);

  const currentRoleFocusCount = useMemo(() => {
    return poolEntries.filter(e => e.isFocusPick || e.focusPick).length;
  }, [poolEntries]);

  const totalChamps = useMemo(() => Object.keys(champions || {}).length, [champions]);

  const champList = useMemo(() => {
    const matcher = window.matchesChampionSearch || ((c, q) => {
      if (!q || !q.trim()) return true;
      if (!c) return false;
      const rawQ = q.trim().toLowerCase();
      const rawName = String(c.name || c.id || '').toLowerCase();
      const rawId = String(c.id || '').toLowerCase();
      if (rawName.includes(rawQ) || rawId.includes(rawQ)) return true;
      const clean = s => String(s || '').toLowerCase().replace(/[^a-z0-9]/g, '');
      const cq = clean(q);
      return cq ? clean(rawName).includes(cq) || clean(rawId).includes(cq) : false;
    });

    return Object.values(champions || {})
      .filter(c => filterTag === 'All' || (c.tags && c.tags.includes(filterTag)))
      .filter(c => matcher(c, search))
      .sort((a, b) => a.name.localeCompare(b.name));
  }, [champions, filterTag, search]);

  const inPool = (champId) => Boolean(accountPool[champId]);

  // Actions for room-level override vs account pool
  const handleCreateRoomOverride = () => {
    if (!lobbyCode || !mySlot || mySlotIdx === -1 || !window.db) {
      if (showToast) showToast('Claim a lane in the lobby first to create a room override! 🌸');
      return;
    }
    const inheritedChamps = getEffectivePlayerPool ? getEffectivePlayerPool(mySlot) : poolEntries;
    window.db.ref(`rooms/${lobbyCode}/state/players/${mySlotIdx}/pool`).set(inheritedChamps);
    if (showToast) showToast(`Created independent pool override for Lobby ${lobbyCode} 🛡️`);
  };

  const handleRevertToAccountPool = () => {
    if (!lobbyCode || mySlotIdx === -1 || !window.db) return;
    window.db.ref(`rooms/${lobbyCode}/state/players/${mySlotIdx}/pool`).set(null);
    if (showToast) showToast(`Reverted to live account pool 🌸`);
  };

  // Granular per-leaf writes to account pool
  const handleAddChamp = (champ) => {
    if (!champ || !uid || !window.db) return;
    if (inPool(champ.id)) {
      if (showToast) showToast('Already in pool! 🌸');
      return;
    }
    window.db.ref(`users/${uid}/pools/${activeRole}/champions/${champ.id}`).set({ comfort: 2, notes: '' });
    if (showToast) showToast(`${champ.name} added to ${activeRoleObj.label} pool! ✨`);
  };

  const handleRemoveChamp = (champId) => {
    if (!uid || !window.db) return;
    window.db.ref(`users/${uid}/pools/${activeRole}/champions/${champId}`).remove();
    if (showToast) showToast('Champion removed from pool 🌸');
  };

  const handleToggleChamp = (champ) => {
    if (!champ || !uid || !window.db) return;
    const champId = champ.id;
    if (inPool(champId)) {
      const entry = accountPool[champId];
      const hasNotes = Boolean(entry && entry.notes && String(entry.notes).trim().length > 0);
      const isAboveDefaultComfort = Boolean(entry && entry.comfort && entry.comfort > 2);

      if (hasNotes || isAboveDefaultComfort) {
        const confirmMsg = `Are you sure you want to remove ${champ.name}? Its notes and rating will be lost.`;
        if (!window.confirm(confirmMsg)) return;
      }

      window.db.ref(`users/${uid}/pools/${activeRole}/champions/${champId}`).remove();
      if (showToast) showToast(`Removed ${champ.name} from ${activeRoleObj.label} pool 🌸`);
    } else {
      window.db.ref(`users/${uid}/pools/${activeRole}/champions/${champId}`).set({ comfort: 2, notes: '' });
      if (showToast) showToast(`${champ.name} added to ${activeRoleObj.label} pool! ✨`);
    }
  };

  const handleToggleFocus = (champId) => {
    if (!uid || !window.db) return;
    const entry = accountPool[champId];
    if (!entry) return;
    const isCurrentlyFocus = Boolean(entry.isFocusPick || entry.focusPick);
    if (!isCurrentlyFocus && currentRoleFocusCount >= 3) {
      if (showToast) showToast('3 picks max — unstar one to swap 🌸');
      return;
    }
    const champRef = window.db.ref(`users/${uid}/pools/${activeRole}/champions/${champId}`);
    const nowTs = Date.now();
    champRef.child('isFocusPick').set(!isCurrentlyFocus);
    champRef.child('focusPick').set(!isCurrentlyFocus);
    champRef.child('focusSetAt').set(nowTs);
    if (showToast) showToast(!isCurrentlyFocus ? 'Starred as focus pick for this week! ⭐' : 'Unstarred focus pick 🌸');
  };

  const handleUpdateComfort = (champId, comfortVal) => {
    if (!uid || !window.db) return;
    window.db.ref(`users/${uid}/pools/${activeRole}/champions/${champId}/comfort`).set(comfortVal);
  };

  const handleUpdateNotes = (champId, notesStr) => {
    if (!uid || !window.db) return;
    window.db.ref(`users/${uid}/pools/${activeRole}/champions/${champId}/notes`).set(notesStr);
  };

  const countText = `${poolEntries.length} of ${totalChamps} champions`;

  if (championsLoading) return <window.LoadingSpinner />;

  return (
    <div style={{ padding: 20, maxWidth: 900, margin: '0 auto' }}>
      {/* Role Tabs Header */}
      <div style={{ marginBottom: 16 }}>
        <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 28, margin: '0 0 12px 0' }}>
          🌸 My Champion Pools
        </h1>

        {/* 5 Role Tabs: Top / Jungle / Mid / ADC / Support */}
        <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4 }}>
          {ROLES.map(role => {
            const isActive = activeRole === role.id;
            const isDisabled = isLockedToLane && role.id !== String(claimedRole).toUpperCase();
            return (
              <button
                key={role.id}
                disabled={isDisabled}
                onClick={() => {
                  if (!isDisabled) setActiveRole(role.id);
                }}
                title={isDisabled ? `You're locked into ${lockedRoleLabel} for this lobby` : undefined}
                className="cozy-btn"
                style={{
                  display: 'flex', alignItems: 'center', gap: 6,
                  padding: '8px 16px', borderRadius: 16,
                  background: isActive ? role.color : 'var(--surface-nested)',
                  border: `2px solid ${isActive ? 'var(--text-on-light-pastel)' : 'var(--border-default)'}`,
                  fontFamily: 'Fredoka One, cursive', fontSize: 14,
                  color: isActive ? 'var(--text-on-light-pastel)' : 'var(--text-primary)',
                  cursor: isDisabled ? 'not-allowed' : 'pointer',
                  opacity: isDisabled ? 0.45 : 1,
                  boxShadow: isActive ? '0 3px 0 var(--border-default)' : 'none',
                  transition: 'all 0.15s', whiteSpace: 'nowrap'
                }}
              >
                <span>{role.emoji}</span>
                <span>{role.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Lobby Override / Inheritance Banner */}
      {lobbyCode && mySlot && (
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 10, padding: '10px 14px', marginBottom: 16,
          background: hasRoomOverride ? 'var(--surface-nested)' : 'var(--surface-card)',
          border: `1.5px solid ${hasRoomOverride ? 'var(--accent-orange)' : 'var(--accent-green)'}`,
          borderRadius: 14, flexWrap: 'wrap'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 700, color: 'var(--text-primary)' }}>
            <span>{hasRoomOverride ? '🛡️' : '🌸'}</span>
            <span>
              {hasRoomOverride
                ? `Independent team pool override active for Lobby ${lobbyCode}`
                : `Inheriting live from your account-level ${mySlot.position || activeRole} pool`}
            </span>
          </div>

          {hasRoomOverride ? (
            <button
              onClick={handleRevertToAccountPool}
              className="cozy-btn"
              style={{
                padding: '6px 12px', background: 'var(--surface-card)', border: '1.5px solid var(--border-emphasis)',
                borderRadius: 10, fontFamily: 'Fredoka One, cursive', fontSize: 12,
                color: 'var(--accent-orange)', cursor: 'pointer'
              }}
            >
              🌸 Use my account pool instead
            </button>
          ) : (
            <button
              onClick={handleCreateRoomOverride}
              className="cozy-btn"
              style={{
                padding: '6px 12px', background: 'var(--accent-orange)', border: 'none',
                borderRadius: 10, fontFamily: 'Fredoka One, cursive', fontSize: 12,
                color: '#FFF', cursor: 'pointer', boxShadow: '0 2px 0 rgba(0,0,0,0.2)'
              }}
            >
              🛡️ Make a pool just for this lobby
            </button>
          )}
        </div>
      )}

      {/* Pool editor card */}
      <div className="cozy-card" style={{ padding: 18, position: 'relative', background: 'var(--surface-card)' }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          flexWrap: 'wrap', gap: 10, marginBottom: 16, width: '100%', boxSizing: 'border-box',
        }}>
          <div>
            <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 20, lineHeight: 1.3 }}>
              {activeRoleObj.emoji} {activeRoleObj.roleLabel} Pool
              <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-muted)', marginLeft: 8 }}>
                ({poolEntries.length})
              </span>
            </div>
            {!lobbyCode && (
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-secondary)', marginTop: 2 }}>
                Your account pool — used in every lobby unless you make one just for that team.
              </div>
            )}
          </div>

          <button
            onClick={() => setShowAddModal(true)}
            className="cozy-btn"
            style={{
              marginLeft: 'auto',
              display: 'inline-flex', alignItems: 'center', gap: 5,
              background: 'var(--accent-orange)', color: 'white',
              border: 'none', borderRadius: 14,
              padding: '8px 16px', fontSize: 13, fontWeight: 800,
              fontFamily: 'Fredoka One, cursive', cursor: 'pointer',
              boxShadow: '0 2px 0 rgba(0,0,0,0.2)', whiteSpace: 'nowrap',
            }}
          >
            + Add champion
          </button>
        </div>

        {/* Pool entries */}
        {poolEntries.length === 0 ? (
          <div style={{
            textAlign: 'center', padding: '40px 16px',
            color: 'var(--text-muted)', fontSize: 14, fontWeight: 700,
          }}>
            <div style={{ fontSize: 40, marginBottom: 8 }}>🌱</div>
            No champions in your {activeRoleObj.label} pool yet!<br />
            <button
              onClick={() => setShowAddModal(true)}
              className="cozy-btn"
              style={{
                marginTop: 14, display: 'inline-flex', alignItems: 'center', gap: 6,
                background: 'var(--surface-nested)', border: '2px solid var(--border-emphasis)',
                borderRadius: 14, padding: '8px 16px',
                fontFamily: 'Fredoka One, cursive', fontSize: 13, color: 'var(--accent-orange)',
                cursor: 'pointer',
              }}
            >
              + Add champion to {activeRoleObj.label} pool
            </button>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {poolEntries.map(entry => (
              <AccountPoolEntry
                key={entry.championId}
                entry={entry}
                champions={champions}
                currentRoleFocusCount={currentRoleFocusCount}
                onToggleFocus={handleToggleFocus}
                onUpdateComfort={handleUpdateComfort}
                onUpdateNotes={handleUpdateNotes}
                onRemove={handleRemoveChamp}
              />
            ))}
          </div>
        )}
      </div>

      {/* Champion Picker Modal */}
      {showAddModal && (
        <div
          onClick={() => setShowAddModal(false)}
          style={{
            position: 'fixed', inset: 0,
            background: 'rgba(74, 55, 40, 0.65)', backdropFilter: 'blur(3px)',
            zIndex: 1000, display: 'flex', alignItems: 'center',
            justifyContent: 'center', padding: 16,
          }}
        >
          <div
            onClick={e => e.stopPropagation()}
            className="cozy-card pop-in"
            style={{
              width: '100%', maxWidth: 520, maxHeight: '85vh',
              display: 'flex', flexDirection: 'column', padding: 18,
              background: 'var(--surface-modal)', boxSizing: 'border-box',
            }}
          >
            {/* Modal Header */}
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              marginBottom: 12, borderBottom: '1.5px solid var(--border-default)', paddingBottom: 10,
            }}>
              <div>
                <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 18 }}>
                  🔍 Add to {activeRoleObj.label} Pool
                </div>
                <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)', marginTop: 2 }}>
                  {activeRoleObj.emoji} {activeRoleObj.roleLabel} Pool · {countText}
                </div>
              </div>
              <button
                onClick={() => setShowAddModal(false)}
                className="cozy-btn"
                style={{
                  background: 'var(--surface-nested)', border: '2px solid var(--border-default)',
                  borderRadius: '50%', width: 30, height: 30,
                  fontSize: 14, fontWeight: 800, color: 'var(--accent-orange)',
                  cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}
              >
                ✕
              </button>
            </div>

            {/* Search */}
            <input
              ref={searchInputRef}
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Search champions…"
              style={{
                width: '100%', padding: '8px 12px',
                border: '2px solid var(--border-default)', borderRadius: 12,
                fontFamily: 'Nunito', fontSize: 13, fontWeight: 600,
                background: 'var(--surface-nested)', color: 'var(--text-primary)', outline: 'none',
                boxSizing: 'border-box', marginBottom: 10,
              }}
            />

            {/* Filter chips */}
            <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginBottom: 12 }}>
              {FILTER_TAGS.map(tag => (
                <button key={tag} onClick={() => setFilterTag(tag)} className="cozy-btn" style={{
                  background: filterTag === tag ? 'var(--accent-orange)' : 'var(--surface-nested)',
                  color: filterTag === tag ? 'white' : 'var(--text-primary)',
                  border: '2px solid var(--border-default)', borderRadius: 16,
                  padding: '3px 10px', fontSize: 11, fontWeight: 800,
                  fontFamily: 'Nunito', cursor: 'pointer',
                }}>
                  {FILTER_EMOJIS[tag]} {tag}
                </button>
              ))}
            </div>

            {/* Champion icon grid */}
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(56px, 1fr))',
              gap: 8, overflowY: 'auto', flex: 1, minHeight: 0, paddingRight: 4, paddingBottom: 4,
              WebkitOverflowScrolling: 'touch',
            }}>
              {champList.map(champ => {
                const added = inPool(champ.id);
                return (
                  <div
                    key={champ.id}
                    onClick={() => handleToggleChamp(champ)}
                    title={champ.name + (added ? ' (click to remove)' : ' (click to add)')}
                    style={{
                      display: 'flex', flexDirection: 'column', alignItems: 'center',
                      gap: 3, cursor: 'pointer',
                      opacity: added ? 0.35 : 1,
                      transition: 'all 0.2s cubic-bezier(0.34, 1.56, 0.64, 1)',
                      position: 'relative',
                    }}
                    className="champion-sticker"
                  >
                    <window.ChampionIcon championId={champ.id} size={50} noAnim />
                    <span style={{
                      fontSize: 10, fontWeight: 700, color: 'var(--text-primary)',
                      textAlign: 'center', lineHeight: 1.2,
                      maxWidth: 56, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }}>{champ.name}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function AccountPoolEntry({ entry, champions, currentRoleFocusCount, onToggleFocus, onUpdateComfort, onUpdateNotes, onRemove }) {
  const [hover, setHover] = useState(false);
  const champData = champions[entry.championId];
  const isFocus = Boolean(entry.isFocusPick || entry.focusPick);
  const disableStar = !isFocus && currentRoleFocusCount >= 3;

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', flexDirection: 'column', gap: 6,
        background: 'var(--surface-nested)', border: `1.5px solid ${isFocus ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
        borderRadius: 14, padding: '10px 12px', transition: 'all 0.2s',
        boxShadow: isFocus ? '0 2px 8px var(--border-default)' : (hover ? '0 2px 8px var(--border-default)' : 'none'),
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <window.ChampionIcon championId={entry.championId} size={44} noAnim />

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6, marginBottom: 4 }}>
            <div style={{ fontWeight: 800, fontSize: 14, color: 'var(--text-primary)' }}>
              {champData?.name || entry.championId}
            </div>

            {/* Star Focus Pick Toggle */}
            <button
              onClick={() => onToggleFocus(entry.championId)}
              disabled={disableStar}
              title={disableStar ? "3 picks max — unstar one to swap" : (isFocus ? "Unstar focus pick ⭐" : "Star as focus pick ⭐")}
              style={{
                background: isFocus ? 'var(--accent-orange)' : 'var(--surface-nested)',
                color: isFocus ? '#FFF' : 'var(--text-primary)',
                border: `1.5px solid ${isFocus ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
                borderRadius: 12, fontSize: 11, fontWeight: 800, padding: '2px 8px',
                fontFamily: 'Nunito', cursor: disableStar ? 'not-allowed' : 'pointer',
                opacity: disableStar ? 0.45 : 1,
                transition: 'all 0.15s', display: 'inline-flex', alignItems: 'center', gap: 4,
              }}
            >
              <span>{isFocus ? '⭐' : '☆'}</span>
              <span>{isFocus ? 'Focus' : 'Focus'}</span>
            </button>
          </div>

          {/* Comfort level chips */}
          <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {[
              { id: 1, label: 'Learning', color: '#B8E0C0', border: '#7CBF8E' },
              { id: 2, label: 'Comfortable', color: '#F7DFA0', border: '#c8ae65' },
              { id: 3, label: 'Confident', color: '#C5B4E3', border: '#9e87cc' },
              { id: 4, label: 'Ready', color: '#AED6F1', border: '#5b9abf' },
            ].map(level => (
              <button
                key={level.id}
                onClick={() => onUpdateComfort(entry.championId, level.id)}
                style={{
                  background: entry.comfort === level.id ? level.color : 'transparent',
                  border: `1.5px solid ${entry.comfort === level.id ? level.border : 'var(--border-default)'}`,
                  borderRadius: 10, fontSize: 9, fontWeight: 800, padding: '2px 7px',
                  fontFamily: 'Nunito', color: entry.comfort === level.id ? 'var(--text-on-light)' : 'var(--text-muted)',
                  cursor: 'pointer', transition: 'all 0.15s',
                }}
              >{level.label}</button>
            ))}
          </div>
        </div>

        {hover && (
          <button
            onClick={() => onRemove(entry.championId)}
            title="Remove champion from account pool"
            style={{
              background: '#F9D0D0', border: '1.5px solid #E8A0A0',
              borderRadius: 10, fontSize: 12, fontWeight: 800, padding: '4px 8px',
              fontFamily: 'Nunito', color: '#8b3a3a', cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 4, flexShrink: 0,
            }}
          >🗑️</button>
        )}
      </div>

      {/* Champion Note input */}
      <input
        type="text"
        value={entry.notes || ''}
        onChange={e => onUpdateNotes(entry.championId, e.target.value)}
        placeholder="Add personal notes for this champ (e.g. matchups, builds)…"
        style={{
          width: '100%', padding: '5px 9px', background: 'var(--surface-card)',
          border: '1.5px solid var(--border-default)', borderRadius: 8,
          fontFamily: 'Nunito', fontSize: 11, fontWeight: 600, color: 'var(--text-primary)', outline: 'none',
          boxSizing: 'border-box'
        }}
      />
    </div>
  );
}

Object.assign(window, { MyPool, AccountPoolEntry });
