
// HomeScreen.jsx
const { useState, useRef } = React;
const { useApp } = window;

function TeamPulseZone() {
  const { teamName, updateTeamName, players, setTab, activeComp, savedComps, champions, analyzeComp, getEffectivePlayerPool } = useApp();
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(teamName);
  const inputRef = useRef(null);

  const POSITIONS = window.POSITIONS;
  const FLOWER_COLORS = window.FLOWER_COLORS;

  // Clash countdown
  const clashEvents = [
  { name: 'Demacia Cup 🏆', date: new Date('2026-01-24') },
  { name: 'Ionia Cup 🌊', date: new Date('2026-02-21') },
  { name: 'Ixtal Cup 🌿', date: new Date('2026-04-18') },
  { name: 'Noxus Cup ⚔️', date: new Date('2026-05-16') },
  { name: 'Freljord Cup ❄️', date: new Date('2026-06-20') }];

  const now = new Date();
  const nextEvent = clashEvents.find((e) => e.date >= now) || clashEvents[clashEvents.length - 1];
  const daysAway = Math.ceil((nextEvent.date - now) / (1000 * 60 * 60 * 24));

  // Readiness garden
  const gardenPlayers = POSITIONS.map((pos, i) => {
    const p = players && players[i];
    const effectivePool = (p && getEffectivePlayerPool ? getEffectivePlayerPool(p) : (p?.pool || [])) || [];
    const poolSize = effectivePool.length;
    const blooming = Boolean(p) && poolSize >= 3;
    return { player: p, pos, blooming };
  });

  const bloomCount = gardenPlayers.filter((g) => g.blooming).length;
  const compAnalysis = analyzeComp(champions, activeComp);

  const handleNameEdit = () => {
    updateTeamName(draft);
    setEditing(false);
  };

  return (
    <div className="cozy-card" style={{ padding: 24, marginBottom: 36 }}>
      {/* Team name */}
      <div style={{ textAlign: 'center', marginBottom: 16 }}>
        {editing ?
        <input
          ref={inputRef}
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onBlur={handleNameEdit}
          onKeyDown={(e) => e.key === 'Enter' && handleNameEdit()}
          autoFocus
          className="fredoka"
          style={{
            fontSize: 32, color: 'var(--accent-orange)', background: 'transparent',
            border: 'none', borderBottom: '3px solid var(--accent-orange)', outline: 'none',
            textAlign: 'center', width: '100%', fontFamily: 'Fredoka One, cursive'
          }} /> :


        <h1
          className="fredoka"
          onClick={() => {setEditing(true);setDraft(teamName);}}
          style={{ fontSize: 32, color: 'var(--accent-orange)', margin: 0, cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 8 }}
          title="Click to edit team name">
          
            {teamName} <span style={{ fontSize: 18 }}>✏️</span>
          </h1>
        }
      </div>

      {/* Clash countdown */}
      <div style={{
        background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)', borderRadius: 14,
        padding: '10px 16px', marginBottom: 16, textAlign: 'center'
      }}>
        {daysAway <= 0 ?
        <span style={{ fontWeight: 800, color: 'var(--accent-orange)', fontSize: 14 }}>
            🎉 Clash is happening RIGHT NOW! — {nextEvent.name}
          </span> :
        daysAway <= 14 ?
        <span style={{ fontWeight: 800, color: 'var(--accent-orange)', fontSize: 14 }}>
            🗓️ Next Clash in <strong>{daysAway} day{daysAway !== 1 ? 's' : ''}</strong>! — {nextEvent.name}
          </span> :

        <span style={{ fontWeight: 700, color: 'var(--accent-green)', fontSize: 14 }}>
            🌿 No rush — plenty of time · {nextEvent.name} in {daysAway} days
          </span>
        }
      </div>

      {/* Readiness Garden */}
      <div style={{ marginBottom: 12 }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-muted)', marginBottom: 8, textAlign: 'center', letterSpacing: 1 }}>
          SQUAD READINESS
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', gap: 20 }}>
          {gardenPlayers.map(({ player, pos, blooming }) =>
          <div key={pos} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}
          title={player ? player.name : pos}>
              <div style={{
              transition: 'all 0.3s',
              filter: blooming ? 'none' : 'grayscale(100%) opacity(0.4)',
              cursor: 'default',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              height: 32
            }}>
                <window.RoleIcon pos={pos} size={32} />
              </div>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-muted)' }}>
                {({ TOP: 'Top', JUNGLE: 'Jungle', MID: 'Mid', ADC: 'ADC', SUPPORT: 'Sup' })[pos] || pos}
              </div>
            </div>
          )}
        </div>
      </div>

      <div style={{ textAlign: 'center', fontSize: 13, fontWeight: 700, color: 'var(--accent-green)' }}>
        {bloomCount} of 5 lanes ready
      </div>
    </div>);

}

const COMFORT_BUCKETS = [
  { id: 1, label: 'Learning',    fill: '#B8E0C0', border: '#7CBF8E', text: '#2d6b47' },
  { id: 2, label: 'Comfortable', fill: '#F7DFA0', border: '#c8ae65', text: '#6b5420' },
  { id: 3, label: 'Confident',   fill: '#C5B4E3', border: '#9e87cc', text: '#5a3f99' },
  { id: 4, label: 'Ready',       fill: '#AED6F1', border: '#5b9abf', text: '#3d6f8f' },
];

function poolHealth(size) {
  if (size >= 10) return { icon: '🟢', label: 'Deep pool', bg: '#B8E0C0', border: '#7CBF8E', text: '#2d6b47' };
  if (size >= 5) return { icon: '🟡', label: 'Growing', bg: '#F7DFA0', border: '#c8ae65', text: '#6b5420' };
  return { icon: '🔴', label: 'Needs champs', bg: '#F9D0D0', border: '#E8A0A0', text: '#8b3a3a' };
}

function PoolHealthPill({ health }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      background: health.bg, border: `1.5px solid ${health.border}`,
      borderRadius: 20, padding: '2px 7px', fontSize: 9, fontWeight: 800,
      fontFamily: 'Nunito', color: health.text, whiteSpace: 'nowrap', flexShrink: 1,
      overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0,
    }}>
      {health.icon} {health.label}
    </span>
  );
}

function ComfortDistributionBar({ pool }) {
  const total = pool.length;
  const counts = COMFORT_BUCKETS.map(b => ({
    ...b,
    count: pool.filter(e => (e.comfort || 1) === b.id).length,
  }));
  if (total === 0) {
    return (
      <div style={{
        height: 8, borderRadius: 5, border: '1.5px dashed var(--border-default)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 8, fontWeight: 800, color: 'var(--text-muted)', fontFamily: 'Nunito',
      }}>
        No champions yet 🌱
      </div>
    );
  }
  const ABBR = { 4: 'Rdy', 3: 'Conf', 2: 'Comf', 1: 'Lrn' };
  return (
    <div>
      <div style={{
        fontSize: 8, fontWeight: 800, color: 'var(--text-muted)', marginBottom: 2,
        textAlign: 'center', textTransform: 'uppercase', letterSpacing: 0.3, fontFamily: 'Nunito',
      }}>
        Comfort spread
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 2, marginBottom: 2 }}>
        {counts.map(b => (
          <div key={b.id} title={b.label} style={{
            fontSize: 8, fontWeight: 800, color: b.count > 0 ? b.text : 'var(--text-muted)',
            textAlign: 'center', flex: 1, lineHeight: 1.1,
          }}>
            <div>{ABBR[b.id]}</div>
            <div>{b.count}</div>
          </div>
        ))}
      </div>
      <div style={{
        display: 'flex', height: 7, borderRadius: 4, overflow: 'hidden',
        border: '1px solid var(--border-default)',
      }}>
        {counts.map(b => b.count > 0 && (
          <div key={b.id} title={`${b.label}: ${b.count}`} style={{
            width: `${b.count / total * 100}%`, background: b.fill,
            borderRight: '1px solid var(--surface-card)',
          }} />
        ))}
      </div>
    </div>
  );
}

const CLASS_META = {
  Tank:     { fill: '#AED6F1', border: '#5b9abf', text: '#3d6f8f', identity: 'Frontline specialist' },
  Fighter:  { fill: '#F7DFA0', border: '#c8ae65', text: '#6b5420', identity: 'Fighter-heavy' },
  Mage:     { fill: '#C5B4E3', border: '#9e87cc', text: '#5a3f99', identity: 'Mage-heavy' },
  Assassin: { fill: '#F9D0E0', border: '#E89FC4', text: '#8b3a5a', identity: 'Assassin main' },
  Marksman: { fill: '#DCD4F0', border: '#B3A3E0', text: '#5a4d99', identity: 'Marksman focused' },
  Support:  { fill: '#B8E0DA', border: '#6bbfae', text: '#2d6b5f', identity: 'Support specialist' },
};

function classCountsFor(pool, champions) {
  const counts = { Tank: 0, Fighter: 0, Mage: 0, Assassin: 0, Marksman: 0, Support: 0 };
  pool.forEach(entry => {
    const champ = champions && champions[entry.championId];
    if (champ?.tags) champ.tags.forEach(t => { if (counts[t] !== undefined) counts[t]++; });
  });
  return counts;
}

function ClassIdentityBar({ pool, champions }) {
  const counts = classCountsFor(pool, champions);
  const total = Object.values(counts).reduce((a, b) => a + b, 0);
  const present = CLASS_ORDER.filter(c => counts[c] > 0).sort((a, b) => counts[b] - counts[a]);

  if (total === 0 || present.length === 0) {
    return (
      <div>
        <div className="fredoka" style={{ fontSize: 14, color: 'var(--accent-orange)', marginBottom: 6, textAlign: 'center' }}>
          🌱 No class data yet
        </div>
        <div style={{
          height: 16, borderRadius: 8, border: '1.5px dashed var(--border-default)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 10, fontWeight: 800, color: 'var(--text-muted)', fontFamily: 'Nunito',
        }}>
          Build a pool to see the class mix
        </div>
      </div>
    );
  }

  const top = present[0];
  const meta = CLASS_META[top];
  const n = present.length;

  return (
    <div>
      <div className="fredoka" style={{
        fontSize: 15, color: 'var(--accent-orange)', marginBottom: 10, letterSpacing: 0.3,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, whiteSpace: 'nowrap',
      }}>
        <span>{meta.identity}</span><span style={{ opacity: 0.55, fontSize: 13 }}>{CLASS_EMOJIS[top]}</span>
      </div>
      <div style={{
        display: 'flex', flexWrap: 'wrap', justifyContent: 'center', alignItems: 'center', gap: 6, marginBottom: 4,
      }}>
        {present.map((c, i) => {
          const m = CLASS_META[c];
          const scale = n > 1 ? 1 - (i / (n - 1)) * 0.4 : 1; // 1.0 down to 0.6
          const fontSize = 12 + scale * 6;    // ~12–18px
          const padY = 4 + scale * 4;         // ~4–8px
          const padX = 8 + scale * 6;         // ~8–14px
          return (
            <div key={c} title={`${c}: ${counts[c]}`} style={{
              display: 'flex', alignItems: 'center', gap: 5,
              background: m.fill, border: `1.5px solid ${m.border}`, color: m.text,
              borderRadius: 999, padding: `${padY}px ${padX}px`,
              fontFamily: 'Nunito', fontWeight: 800, fontSize,
              lineHeight: 1,
            }}>
              <span>{CLASS_EMOJIS[c]}</span>
              <span>{CLASS_ABBR[c]} {counts[c]}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function formatFreshness(timestamp) {
  if (!timestamp) return null;
  const ts = typeof timestamp === 'number' ? timestamp : new Date(timestamp).getTime();
  if (isNaN(ts)) return null;
  const diffMs = Date.now() - ts;
  if (diffMs < 0) return 'today';
  const hours = Math.floor(diffMs / 3600000);
  if (hours < 24) return 'today';
  const days = Math.floor(hours / 24);
  if (days === 1) return '1 day ago';
  if (days < 14) return `${days} days ago`;
  const weeks = Math.floor(days / 7);
  return `${weeks} week${weeks !== 1 ? 's' : ''} ago`;
}

function TopPicksRow({ pool, champions, player, isOwnCard, onSetFocus }) {
  const seen = new Set();
  const focusPicks = [];
  if (Array.isArray(pool)) {
    for (const entry of pool) {
      if (entry && entry.championId && champions && champions[entry.championId] && (entry.isFocusPick || entry.focusPick) && !seen.has(entry.championId)) {
        seen.add(entry.championId);
        focusPicks.push(entry);
      }
    }
  }

  const picks = focusPicks.slice(0, 3);
  const ts = player?.focusPicksSetAt || focusPicks.reduce((max, e) => (e.focusSetAt && (!max || e.focusSetAt > max)) ? e.focusSetAt : max, null);
  const ago = formatFreshness(ts);

  return (
    <div style={{ marginTop: 4 }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'flex-start', gap: 6, marginBottom: 4,
      }}>
        <span style={{ fontSize: 9, fontWeight: 800, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: 0.3 }}>
          PLAYING THIS WEEK
        </span>
        {ago && (
          <span style={{ fontSize: 9, fontWeight: 700, color: 'var(--text-muted)', fontStyle: 'italic', whiteSpace: 'nowrap' }}>
            · Set {ago}
          </span>
        )}
      </div>

      {picks.length === 0 ? (
        <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-muted)', textAlign: 'left', lineHeight: 1.3 }}>
          Hasn't picked their focus for this week yet 🌱
          {isOwnCard && (
            <span
              onClick={onSetFocus}
              style={{ color: 'var(--accent-orange)', fontWeight: 800, cursor: 'pointer', marginLeft: 6, textDecoration: 'underline' }}
            >
              Set picks →
            </span>
          )}
        </div>
      ) : (
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-start', alignItems: 'center' }}>
          {picks.map(e => (
            <div key={e.championId} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }} title={champions[e.championId]?.name || e.championId}>
              <window.ChampionIcon championId={e.championId} size={44} noAnim />
              <span style={{ fontSize: 9, fontWeight: 700, color: 'var(--text-primary)', textAlign: 'center', maxWidth: 46, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {champions[e.championId]?.name || e.championId}
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

const CLASS_EMOJIS = { Tank:'🛡️', Fighter:'💪', Mage:'🔮', Assassin:'🗡️', Marksman:'🏹', Support:'💛' };
const CLASS_ABBR = { Tank:'Tank', Fighter:'Fght', Mage:'Mage', Assassin:'Assn', Marksman:'Mark', Support:'Supp' };
const CLASS_ORDER = ['Tank', 'Fighter', 'Mage', 'Assassin', 'Marksman', 'Support'];

function PoolStatsLine({ pool, champions, onAlertsClick }) {
  const getPatch = window.getChampPatchStatus;
  const statuses = pool.map(e => getPatch && getPatch(e.championId)).filter(Boolean);
  const buffs = statuses.filter(s => s.type === 'buff').length;
  const nerfs = statuses.filter(s => s.type === 'nerf').length;
  const hasAlerts = buffs > 0 || nerfs > 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 4 }}>
      <div style={{
        fontSize: 9, fontWeight: 800, color: 'var(--text-muted)',
        display: 'flex', gap: 3, alignItems: 'center',
        fontFamily: 'Nunito',
      }}>
        <span>{pool.length} champs</span>
      </div>
      {hasAlerts && (
        <span
          onClick={(e) => { e.stopPropagation(); onAlertsClick && onAlertsClick(); }}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
            borderRadius: 20, padding: '1px 8px', fontSize: 10, fontWeight: 800,
            cursor: onAlertsClick ? 'pointer' : 'default', flexShrink: 0,
          }}
        >
          {buffs > 0 && (
            <span style={{ color: 'var(--accent-green)', display: 'inline-flex', alignItems: 'center', gap: 2 }}>
              ⬆️ {buffs} buffed
            </span>
          )}
          {buffs > 0 && nerfs > 0 && <span style={{ color: 'var(--border-default)' }}>·</span>}
          {nerfs > 0 && (
            <span style={{ color: '#D14343', display: 'inline-flex', alignItems: 'center', gap: 2 }}>
              ▼ {nerfs} nerfed
            </span>
          )}
        </span>
      )}
    </div>
  );
}

function PlayerCard({ player }) {
  const { activePlayerId, myUserId, sessionUserId, lobbyCode, champions, setTab, setActivePlayer, showToast, getEffectivePlayerPool, userProfile, userProfilesByUid } = useApp();
  const emojis = window.POSITION_EMOJIS;
  const colors = window.POSITION_COLORS;
  const labels = window.POSITION_LABELS;

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

  const isMine = !!(player && (player.claimed || player.ownerId || player.uid) && (
    (authUid && (player.uid === authUid || player.ownerId === authUid)) ||
    (!authUid && sessionUserId && player.ownerId === sessionUserId)
  ));
  const isOther = (player.claimed || !!player.ownerId || !!player.uid) && !isMine;
  const isEmpty = !player.claimed && !player.ownerId && !player.uid;
  const isActive = activePlayerId !== null && player.id === activePlayerId;

  // Step 4 — Display name resolution order: Account displayName → stored player.name → role default
  const targetUid = player.uid || player.ownerId;
  const accountDisplayName = (targetUid && userProfilesByUid && userProfilesByUid[targetUid]) || (isMine ? userProfile?.displayName : null);
  const cardDisplayName = accountDisplayName || player.name || labels[player.position] || player.position || 'Player';

  // Modal open state for teammate-pool viewer.
  const [poolModalOpen, setPoolModalOpen] = useState(false);

  const effectivePool = (getEffectivePlayerPool ? getEffectivePlayerPool(player) : player.pool) || [];
  const health = poolHealth(effectivePool.length);

  const [editingName, setEditingName] = useState(false);
  const [nameDraft, setNameDraft] = useState(player.name);
  const { updatePlayerName } = useApp();

  const saveName = () => {updatePlayerName(player.id, nameDraft);setEditingName(false);};

  const copyInvite = (e) => {
    e.stopPropagation();
    const link = `cozydraft://lobby/${lobbyCode}`;
    try {navigator.clipboard.writeText(link);} catch {}
    showToast && showToast(`📋 Lobby link copied! Code: ${lobbyCode}`);
  };

  // ── EMPTY (unclaimed) variant ───────────────────────────────────────────────
  if (isEmpty) {
    return (
      <div
        style={{
          padding: 16, width: '100%', boxSizing: 'border-box',
          position: 'relative', minHeight: 450,
          background: 'var(--surface-card)',
          border: '2.5px dashed var(--border-default)',
          borderRadius: 20,
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          textAlign: 'center'
        }}>
        
        {/* Position badge */}
        <div style={{ marginBottom: 10 }}>
          <span style={{
            background: colors[player.position] + '70',
            border: '1.5px dashed var(--border-default)', borderRadius: 20,
            padding: '2px 12px', fontSize: 12, fontWeight: 800,
            fontFamily: 'Nunito', color: 'var(--text-primary)'
          }}>
            {emojis[player.position]} {player.position}
          </span>
        </div>

        {/* Ghosted hex with role icon */}
        <div style={{ marginBottom: 14, opacity: 0.5 }}>
          <window.HexFrame size={72} color="var(--surface-nested)" borderColor="var(--border-default)" borderWidth={2}>
            <window.RoleIcon pos={player.position} size={40} />
          </window.HexFrame>
        </div>

        <div className="fredoka" style={{
          color: 'var(--text-muted)', fontSize: 15, marginBottom: 6, lineHeight: 1.3,
          maxWidth: 200
        }}>Waiting for a teammate to lock in this lane…

        </div>
        <window.PawPrint size={18} color="var(--text-muted)" />

        <div style={{ flex: 1 }} />

        <button
          onClick={copyInvite}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            background: 'var(--surface-nested)', border: '2px solid var(--border-emphasis)',
            borderRadius: 14, padding: '6px 12px',
            fontFamily: 'Nunito', fontWeight: 800, fontSize: 11, color: 'var(--accent-orange)',
            cursor: 'pointer', marginTop: 10,
            boxShadow: '0 2px 0 var(--border-default)',
            transition: 'transform 0.15s'
          }}
          onMouseEnter={(e) => e.currentTarget.style.transform = 'translateY(-1px)'}
          onMouseLeave={(e) => e.currentTarget.style.transform = 'translateY(0)'}>
          
          📋 Copy lobby link to invite
        </button>
      </div>);

  }

  // ── OTHER-USER (spectating) variant ─────────────────────────────────────────
  if (isOther) {
    return (
      <div
        className="secondary-card"
        style={{
          padding: 16, width: '100%', boxSizing: 'border-box',
          position: 'relative', opacity: 0.95, minHeight: 450,
          display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 8,
          background: 'var(--surface-card)',
          boxShadow: '0 2px 0 var(--border-default)'
        }}>

        {/* Owner badge — replaces "you ✨" */}
        <div style={{
          position: 'absolute', top: -12, left: '50%', transform: 'translateX(-50%)',
          display: 'flex', alignItems: 'center', gap: 5,
          background: player.identityColor + 'F0',
          border: '2px solid ' + player.identityColor,
          borderRadius: 12, padding: '2px 10px 2px 4px',
          fontFamily: 'Nunito', fontWeight: 800, fontSize: 11, color: 'var(--text-on-light-pastel)',
          whiteSpace: 'nowrap', boxShadow: '0 2px 6px var(--border-default)', zIndex: 2
        }}>
          <window.HexFrame size={18} color={player.identityColor} borderColor="var(--border-emphasis)" borderWidth={1.5} />
          <span>{cardDisplayName}</span>
          {player.online &&
          <span style={{
            width: 6, height: 6, borderRadius: '50%',
            background: 'var(--accent-green)', display: 'inline-block'
          }} />
          }
        </div>

        {/* Top row: role badge · pool health */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 4, marginTop: 4, minWidth: 0 }}>
          <span style={{
            background: colors[player.position] || '#F7DFA0',
            border: '1.5px solid var(--border-default)', borderRadius: 20,
            padding: '2px 8px', fontSize: 10, fontWeight: 800,
            fontFamily: 'Nunito', color: 'var(--text-on-light)', flexShrink: 0, whiteSpace: 'nowrap',
          }}>
            {emojis[player.position]} {player.position}
          </span>
          <PoolHealthPill health={health} />
        </div>

        {/* Online dot · Role icon · Player name */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
          <span className={player.online ? 'pulse-online' : ''} title={player.online ? 'Online' : 'Offline'} style={{
            width: 8, height: 8, borderRadius: '50%',
            background: player.online ? 'var(--accent-green)' : 'var(--border-default)',
            display: 'inline-block', flexShrink: 0,
          }} />
          <window.RoleIcon pos={player.position} size={16} />
          <div className="fredoka" style={{ fontSize: 16, color: 'var(--text-primary)' }}>
            {cardDisplayName}
          </div>
        </div>

        <div style={{ borderTop: '1.5px dashed var(--border-default)', width: '100%' }} />

        <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
          <ClassIdentityBar pool={effectivePool} champions={champions} />
        </div>

        <div style={{ borderTop: '1.5px dashed var(--border-default)', width: '100%' }} />

        <TopPicksRow pool={effectivePool} player={player} champions={champions} isOwnCard={false} />

        <div style={{ borderTop: '1.5px dashed var(--border-default)', width: '100%' }} />

        <div>
          <PoolStatsLine pool={effectivePool} champions={champions} onAlertsClick={() => setTab('meta')} />
        </div>

        {/* View-full-pool sticker — replaces the static "Spectating" indicator */}
        <div style={{ textAlign: 'center' }}>
          <window.CozyButton
            small
            color="lavender"
            onClick={() => setPoolModalOpen(true)}
          >
            View full pool 👁️
          </window.CozyButton>
        </div>

        {poolModalOpen && window.PlayerPoolModal && (
          <window.PlayerPoolModal
            player={{ ...player, pool: effectivePool }}
            onClose={() => setPoolModalOpen(false)}
          />
        )}
      </div>);

  }

  // ── MINE (owned by current user) variant — falls through to default ────────
  return (
    <div
      className={`secondary-card ${isActive ? 'active-card' : ''}`}
      style={{
        padding: 16, width: '100%', boxSizing: 'border-box',
        position: 'relative', transition: 'all 0.3s', minHeight: 450,
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 8,
        background: 'var(--surface-card)',
        boxShadow: isActive ? '0 0 0 3px var(--border-emphasis), 0 4px 20px var(--border-default)' : '0 2px 0 var(--border-default)'
      }}>

      {/* "you ✦" identity badge — uses identity colour hex */}
      {isMine &&
      <div style={{
        position: 'absolute', top: -12, left: '50%', transform: 'translateX(-50%)',
        display: 'flex', alignItems: 'center', gap: 5,
        background: 'var(--accent-orange)', color: 'var(--surface-card)', borderRadius: 12,
        padding: '2px 10px 2px 4px',
        fontSize: 11, fontWeight: 800, fontFamily: 'Nunito',
        whiteSpace: 'nowrap', boxShadow: '0 2px 6px var(--border-default)', zIndex: 2
      }}>
          <window.HexFrame size={18} color={player.identityColor} borderColor="var(--surface-card)" borderWidth={1.5} />
          <span>you</span>
          <window.CrystalSparkle size={10} color="var(--surface-card)" />
        </div>
      }

      {/* Top row: role badge · pool health */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 4, marginTop: 4, minWidth: 0 }}>
        <span style={{
          background: colors[player.position] || '#F7DFA0',
          border: '1.5px solid var(--border-default)', borderRadius: 20,
          padding: '2px 8px', fontSize: 10, fontWeight: 800,
          fontFamily: 'Nunito', color: 'var(--text-on-light)', flexShrink: 0, whiteSpace: 'nowrap',
        }}>
          {emojis[player.position]} {player.position}
        </span>
        <PoolHealthPill health={health} />
      </div>

      {/* Online dot · Player name */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
        <span className={player.online ? 'pulse-online' : ''} title={player.online ? 'Online' : 'Offline'} style={{
          width: 8, height: 8, borderRadius: '50%',
          background: player.online ? 'var(--accent-green)' : 'var(--border-default)',
          display: 'inline-block', flexShrink: 0,
        }} />
        <window.RoleIcon pos={player.position} size={16} />
        {editingName ?
        <input
          value={nameDraft}
          onChange={(e) => setNameDraft(e.target.value)}
          onBlur={saveName}
          onKeyDown={(e) => e.key === 'Enter' && saveName()}
          autoFocus
          className="fredoka"
          style={{
            fontSize: 16, color: 'var(--text-primary)', background: 'transparent',
            border: 'none', borderBottom: '2px solid var(--border-emphasis)', outline: 'none',
            width: '100%', textAlign: 'center', fontFamily: 'Fredoka One, cursive'
          }} /> :


        <div
          className="fredoka"
          onDoubleClick={() => {setEditingName(true);setNameDraft(player.name);}}
          style={{ fontSize: 16, color: 'var(--text-primary)', cursor: 'pointer' }}
          title="Double-click to edit">
          
            {cardDisplayName}
          </div>
        }
      </div>

      <div style={{ borderTop: '1.5px dashed var(--border-default)', width: '100%' }} />

      <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        <ClassIdentityBar pool={effectivePool} champions={champions} />
      </div>

      <div style={{ borderTop: '1.5px dashed var(--border-default)', width: '100%' }} />

      <TopPicksRow pool={effectivePool} player={player} champions={champions} isOwnCard={true} onSetFocus={() => {setActivePlayer(player.id);setTab('pool');}} />

      <div style={{ borderTop: '1.5px dashed var(--border-default)', width: '100%' }} />

      <div>
        <PoolStatsLine pool={effectivePool} champions={champions} onAlertsClick={() => setTab('meta')} />
      </div>

      {/* Action buttons */}
      <div style={{ display: 'flex', gap: 8, justifyContent: 'center', flexWrap: 'wrap' }}>
        <window.CozyButton
          small
          color="sage"
          onClick={() => {setActivePlayer(player.id);setTab('pool');}}>
          Edit pool 🌸
        </window.CozyButton>
        <window.CozyButton
          small
          color="lavender"
          onClick={() => setPoolModalOpen(true)}
        >
          View your pool 👁️
        </window.CozyButton>
      </div>

      {poolModalOpen && window.PlayerPoolModal && (
        <window.PlayerPoolModal
          player={{ ...player, pool: effectivePool }}
          isSelf={true}
          onClose={() => setPoolModalOpen(false)}
        />
      )}
    </div>);

}

function QuickActions() {
  const { activeComp, savedComps, champions, analyzeComp, setTab } = useApp();
  const compAnalysis = analyzeComp(champions, activeComp);
  const getSlotChampionId = window.getSlotChampionId;
  const positions = window.POSITIONS || ['TOP', 'JUNGLE', 'MID', 'ADC', 'SUPPORT'];
  const hasComp = positions.some(pos => Boolean(getSlotChampionId ? getSlotChampionId(activeComp[pos]) : activeComp[pos]));

  return (
    <div className="quick-actions-container">
      {/* Active Comp */}
      <div className="quick-action-card">
        <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 15, marginBottom: 8 }}>🍲 Active Comp</div>
        {hasComp ?
        <>
            <div style={{ display: 'flex', gap: 4, marginBottom: 8, flexWrap: 'wrap' }}>
              {positions.map((pos) =>
            <window.ChampionIcon key={pos} championId={getSlotChampionId ? getSlotChampionId(activeComp[pos]) : activeComp[pos]} size={32} />
            )}
            </div>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--accent-green)', marginBottom: 8 }}>
              {compAnalysis?.vibe || '—'}
            </div>
            <window.CozyButton small color="cream" onClick={() => setTab('comp')}>
              Keep cooking →
            </window.CozyButton>
          </> :

        <>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', marginBottom: 8 }}>No recipe yet! Start cooking 🍳</div>
            <window.CozyButton small color="cream" onClick={() => setTab('comp')}>Build comp →</window.CozyButton>
          </>
        }
      </div>

      {/* Saved Recipes */}
      <div className="quick-action-card">
        <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 15, marginBottom: 8 }}>📦 Saved Recipes</div>
        {savedComps.length > 0 ?
        <>
            {savedComps.slice(0, 2).map((comp) =>
          <div key={comp.id} style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-primary)', marginBottom: 4 }}>
                · {comp.name || 'Unnamed comp'}
              </div>
          )}
            <div style={{ marginTop: 6 }}>
              <window.CozyButton small color="cream" onClick={() => setTab('comp')}>Recipe box →</window.CozyButton>
            </div>
          </> :

        <>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', marginBottom: 8 }}>No recipes saved yet 🌼</div>
            <window.CozyButton small color="cream" onClick={() => setTab('comp')}>Open box →</window.CozyButton>
          </>
        }
      </div>

      {/* Vibe Check */}
      <div className="quick-action-card">
        <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 15, marginBottom: 8 }}>🌟 Vibe Check</div>
        {compAnalysis ?
        <>
            <div style={{ fontSize: 12, color: 'var(--text-primary)', lineHeight: 1.4, marginBottom: 8 }}>
              Wins by {compAnalysis.winCond} 🌟
            </div>
            <window.CozyButton small color="cream" onClick={() => setTab('comp')}>Edit vibe →</window.CozyButton>
          </> :

        <>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.5, marginBottom: 8 }}>
              Add champions to your comp to see the vibe! 🔮
            </div>
            <window.CozyButton small color="cream" onClick={() => setTab('comp')}>Check vibe →</window.CozyButton>
          </>
        }
      </div>
    </div>);

}

function MyTeamsDashboard() {
  const {
    userProfile, sessionUserId, myUserId, players, myTeams,
    setLobbyCode, createNewLobby, setOnboarded, showToast, setTab, signOutUser
  } = useApp();

  const [joinCodeInput, setJoinCodeInput] = useState('');
  const [teamNameInput, setTeamNameInput] = useState('');

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

  const me = (players && players.find(p => p && (p.claimed || !!p.ownerId || !!p.uid) && (
    (authUid && (p.uid === authUid || p.ownerId === authUid)) ||
    (!authUid && sessionUserId && p.ownerId === sessionUserId)
  ))) || null;
  const displayName = userProfile?.displayName || me?.name || 'Player';
  const handleName = (userProfile?.username || displayName).toLowerCase().replace(/\s+/g, '');
  const identityColor = userProfile?.identityColor || me?.identityColor || '#F7DFA0';

  const canCreate = teamNameInput.trim().length >= 2;

  const handleSignOut = async () => {
    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 🌸');
  };

  const handleJoin = (e) => {
    if (e) e.preventDefault();
    const code = joinCodeInput.trim();
    if (!code || code.length < 4) {
      if (showToast) showToast('Please enter a 4-digit lobby code ⚠️');
      return;
    }
    setLobbyCode(code);
    if (showToast) showToast(`Joined lobby ${code} 🛡️`);
  };

  const handleCreateNew = async (e) => {
    if (e) e.preventDefault();
    const trimmedName = teamNameInput.trim();
    if (!trimmedName || trimmedName.length < 2) {
      if (showToast) showToast('Please enter a team name (at least 2 characters) ⚠️');
      return;
    }
    if (showToast) showToast('Creating team lobby... ✨');
    const newCode = await createNewLobby(trimmedName);
    if (newCode) {
      if (showToast) showToast(`Created "${trimmedName}" (Lobby ${newCode}) ✨`);
    } else {
      if (showToast) showToast('Failed to create lobby ⚠️');
    }
  };

  const joinedTeams = myTeams || [];

  return (
    <div style={{ maxWidth: 760, margin: '0 auto', padding: '24px 16px 40px', fontFamily: "'Nunito', sans-serif" }}>
      {/* Top Profile Bar: Profile info left, Sign out right */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 28, flexWrap: 'wrap', gap: 12
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <window.HexFrame size={42} color={identityColor} borderColor="#C4845A" borderWidth={2}>
            <span className="fredoka" style={{ color: '#4A3728', fontSize: 18 }}>
              {displayName[0]?.toUpperCase()}
            </span>
          </window.HexFrame>
          <div>
            <div className="fredoka" style={{ color: '#4A3728', fontSize: 20, lineHeight: 1.1 }}>
              {displayName}
            </div>
            <div style={{ color: '#8C6246', fontFamily: "'Nunito', sans-serif", fontSize: 12, fontWeight: 700, marginTop: 2 }}>
              @{handleName} · Signed in on this device
            </div>
          </div>
        </div>

        <button
          onClick={handleSignOut}
          className="cozy-btn"
          style={{
            padding: '6px 16px', background: '#FFFAF3', border: '1.5px solid #C4845A60',
            borderRadius: 20, fontFamily: "'Nunito', sans-serif", fontWeight: 800, fontSize: 12,
            color: '#8C6246', cursor: 'pointer', boxShadow: '0 2px 0 #C4845A20'
          }}
        >
          Sign out
        </button>
      </div>

      {/* Section Title */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
        <span style={{ fontSize: 18 }}>🌺</span>
        <h2 className="fredoka" style={{ color: '#C4845A', fontSize: 22, margin: 0 }}>
          My Teams <span style={{ fontSize: 16, opacity: 0.8 }}>({joinedTeams.length})</span>
        </h2>
      </div>

      {/* Joined Teams List or Empty State */}
      {joinedTeams.length > 0 ? (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16, marginBottom: 28 }}>
          {joinedTeams.map(t => (
            <div
              key={t.code}
              onClick={() => setLobbyCode(t.code)}
              className="cozy-card pop-in cozy-btn"
              style={{
                padding: 18, background: '#FFFAF3', borderRadius: 20,
                border: '2px solid #C4845A', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
                position: 'relative'
              }}
            >
              <div className="corner-dot" style={{ top: 8, left: 8 }} />
              <div className="corner-dot" style={{ top: 8, right: 8 }} />
              <div className="corner-dot corner-dot-bl" style={{ bottom: 8, left: 8 }} />
              <div className="corner-dot corner-dot-br" style={{ bottom: 8, right: 8 }} />

              <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
                <div style={{ fontSize: 26, flexShrink: 0 }}>
                  {t.myRoleEmoji || '🌾'}
                </div>
                <div style={{ minWidth: 0 }}>
                  <div className="fredoka" style={{ color: '#4A3728', fontSize: 17, lineHeight: 1.2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {t.teamName}
                  </div>
                  <div style={{ color: '#8C6246', fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 12, marginTop: 3 }}>
                    Lobby {t.code} {t.myRoleLabel ? `· ${t.myRoleLabel}` : '· No lane claimed'}
                  </div>
                </div>
              </div>

              <button
                className="cozy-btn fredoka"
                style={{
                  padding: '8px 14px', background: '#C4845A', border: 'none',
                  borderRadius: 12, fontSize: 13, color: '#FFF',
                  cursor: 'pointer', boxShadow: '0 2px 0 #8A4F2A', flexShrink: 0
                }}
              >
                Enter →
              </button>
            </div>
          ))}
        </div>
      ) : (
        /* Empty State Banner */
        <div className="cozy-card pop-in" style={{
          padding: '28px 20px', background: '#FFFAF3', borderRadius: 20,
          border: '2px solid #C4845A', textAlign: 'center', marginBottom: 24,
          position: 'relative'
        }}>
          <div className="corner-dot" style={{ top: 8, left: 8 }} />
          <div className="corner-dot" style={{ top: 8, right: 8 }} />
          <div className="corner-dot corner-dot-bl" style={{ bottom: 8, left: 8 }} />
          <div className="corner-dot corner-dot-br" style={{ bottom: 8, right: 8 }} />
          <div style={{ fontSize: 32, marginBottom: 6 }}>🌱</div>
          <div className="fredoka" style={{ color: '#4A3728', fontSize: 18, marginBottom: 4 }}>
            You're not on a team yet
          </div>
          <div style={{ color: '#8C6246', fontFamily: "'Nunito', sans-serif", fontSize: 13, fontWeight: 700 }}>
            Join one with a lobby code below, or start your own crew.
          </div>
        </div>
      )}

      {/* Two Side-by-Side Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 18, marginBottom: 32 }}>
        {/* Join a team */}
        <div className="cozy-card pop-in" style={{
          padding: 20, background: '#FFFAF3', borderRadius: 20,
          border: '2px solid #C4845A', display: 'flex', flexDirection: 'column',
          justifyContent: 'space-between', position: 'relative'
        }}>
          <div className="corner-dot" style={{ top: 8, left: 8 }} />
          <div className="corner-dot" style={{ top: 8, right: 8 }} />
          <div className="corner-dot corner-dot-bl" style={{ bottom: 8, left: 8 }} />
          <div className="corner-dot corner-dot-br" style={{ bottom: 8, right: 8 }} />
          <div>
            <div className="fredoka" style={{ color: '#4A3728', fontSize: 18, marginBottom: 4 }}>
              Join a team
            </div>
            <div style={{ color: '#8C6246', fontFamily: "'Nunito', sans-serif", fontSize: 12, fontWeight: 700, marginBottom: 16, lineHeight: 1.4 }}>
              Paste a lobby code or open an invite link. You stay in your other teams.
            </div>
          </div>
          <form onSubmit={handleJoin} style={{ display: 'flex', gap: 8, marginTop: 'auto' }}>
            <input
              type="text"
              value={joinCodeInput}
              onChange={e => setJoinCodeInput(e.target.value.replace(/[^0-9]/g, '').slice(0, 4))}
              placeholder="4594"
              style={{
                flex: 1, minWidth: 0, padding: '10px 14px', background: '#FFF5E6',
                border: '2px solid #C4845A', borderRadius: 12,
                fontFamily: "'Fredoka One', cursive", fontSize: 16, color: '#4A3728', outline: 'none'
              }}
            />
            <button
              type="submit"
              className="cozy-btn fredoka"
              style={{
                padding: '10px 20px', background: '#C4845A', border: 'none',
                borderRadius: 12, fontSize: 14, color: '#FFF',
                cursor: 'pointer', boxShadow: '0 2px 0 #8A4F2A'
              }}
            >
              Join
            </button>
          </form>
        </div>

        {/* Start a new crew */}
        <div className="cozy-card pop-in" style={{
          padding: 20, background: '#FFFAF3', borderRadius: 20,
          border: '2px solid #C4845A', display: 'flex', flexDirection: 'column',
          justifyContent: 'space-between', position: 'relative'
        }}>
          <div className="corner-dot" style={{ top: 8, left: 8 }} />
          <div className="corner-dot" style={{ top: 8, right: 8 }} />
          <div className="corner-dot corner-dot-bl" style={{ bottom: 8, left: 8 }} />
          <div className="corner-dot corner-dot-br" style={{ bottom: 8, right: 8 }} />
          <div>
            <div className="fredoka" style={{ color: '#4A3728', fontSize: 18, marginBottom: 4 }}>
              Start a new crew
            </div>
            <div style={{ color: '#8C6246', fontFamily: "'Nunito', sans-serif", fontSize: 12, fontWeight: 700, marginBottom: 16, lineHeight: 1.4 }}>
              You'll be captain and get a code to share.
            </div>
          </div>
          <form onSubmit={handleCreateNew} style={{ display: 'flex', gap: 8, marginTop: 'auto' }}>
            <input
              type="text"
              value={teamNameInput}
              onChange={e => setTeamNameInput(e.target.value.slice(0, 24))}
              placeholder="Cozy Crew"
              style={{
                flex: 1, minWidth: 0, padding: '10px 14px', background: '#FFF5E6',
                border: '2px solid #C4845A', borderRadius: 12,
                fontFamily: "'Fredoka One', cursive", fontSize: 16, color: '#4A3728', outline: 'none'
              }}
            />
            <button
              type="submit"
              disabled={!canCreate}
              className="cozy-btn fredoka"
              style={{
                padding: '10px 20px', background: canCreate ? '#7CBF8E' : '#D1C4B6',
                border: 'none', borderRadius: 12,
                fontSize: 14, color: '#FFF',
                cursor: canCreate ? 'pointer' : 'not-allowed',
                boxShadow: canCreate ? '0 2px 0 #4E9560' : 'none',
                opacity: canCreate ? 1 : 0.6
              }}
            >
              Create
            </button>
          </form>
        </div>
      </div>

      {/* 🌿 Personal Tools Section */}
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
          <span style={{ fontSize: 18 }}>🌿</span>
          <h3 className="fredoka" style={{ color: '#C4845A', fontSize: 20, margin: 0 }}>
            Personal Tools
          </h3>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
          <button
            onClick={() => setTab('pool')}
            className="cozy-card pop-in cozy-btn"
            style={{
              padding: '16px 18px', background: '#FFFAF3', borderRadius: 16,
              border: '2px solid #C4845A', cursor: 'pointer', textAlign: 'left',
              position: 'relative', maxWidth: 280
            }}
          >
            <div className="corner-dot" style={{ top: 6, left: 6 }} />
            <div className="corner-dot" style={{ top: 6, right: 6 }} />
            <div style={{ fontSize: 24, marginBottom: 6 }}>🌸</div>
            <div className="fredoka" style={{ color: '#4A3728', fontSize: 16 }}>
              My Champion Pool
            </div>
            <div style={{ fontSize: 12, color: '#8C6246', fontFamily: "'Nunito', sans-serif", fontWeight: 700, marginTop: 2, lineHeight: 1.3 }}>
              Edit your 5-role account pools & comfort ratings
            </div>
          </button>
        </div>
      </div>
    </div>
  );
}

function HomeScreen() {
  const { lobbyCode, players, roomNotFound, setLobbyCode, sessionUserId, myUserId, isSynced, userProfile } = useApp();

  if (!lobbyCode) {
    return <MyTeamsDashboard />;
  }

  // Step 3 — Render loading state on lobby entry until RTDB players node has returned
  if (!isSynced) {
    return (
      <div style={{ maxWidth: 440, margin: '80px auto', textAlign: 'center', padding: 36 }} className="cozy-card pop-in">
        <div style={{ fontSize: 36, marginBottom: 12 }}>🌸</div>
        <div className="fredoka" style={{ color: '#C4845A', fontSize: 20, marginBottom: 6 }}>
          Entering team lobby {lobbyCode}…
        </div>
        <div style={{ color: '#8C6246', fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 13 }}>
          Fetching real-time team state…
        </div>
      </div>
    );
  }

  if (roomNotFound) {
    return (
      <div style={{ maxWidth: 500, margin: '40px auto', textAlign: 'center', padding: 28 }} className="cozy-card pop-in">
        <div style={{ fontSize: 40, marginBottom: 12 }}>🌸</div>
        <h2 className="fredoka" style={{ color: '#D9534F', fontSize: 22, margin: '0 0 8px 0' }}>
          This team no longer exists
        </h2>
        <p style={{ color: '#8C6246', fontWeight: 700, fontSize: 14, marginBottom: 20 }}>
          The lobby code <strong>{lobbyCode}</strong> could not be found or has been deleted.
        </p>
        <button
          onClick={() => setLobbyCode(null)}
          className="cozy-btn"
          style={{
            padding: '10px 20px', background: '#C4845A', border: 'none',
            borderRadius: 12, fontFamily: 'Fredoka One', fontSize: 14, color: '#FFF',
            cursor: 'pointer', boxShadow: '0 3px 0 #8A4F2A'
          }}
        >
          Return to My Teams Dashboard →
        </button>
      </div>
    );
  }

  // Require lane selection before entering team screen
  const authUid = window.firebase && window.firebase.auth && window.firebase.auth().currentUser && window.firebase.auth().currentUser.uid;
  const myName = (userProfile?.displayName || '').toLowerCase().trim();

  const hasClaimedLane = players && players.some(p => p && (p.claimed || !!p.ownerId || !!p.uid) && (
    (p.ownerId === sessionUserId) ||
    (p.claimed && p.id === myUserId) ||
    (authUid && (p.uid === authUid || p.ownerId === authUid)) ||
    (myName && p.name && p.name.toLowerCase().trim() === myName)
  ));

  if (!hasClaimedLane && window.LaneClaimScreen) {
    return (
      <div style={{ padding: 20 }}>
        <window.LaneClaimScreen
          onDone={() => {
            // Lane selection completed; component re-renders to show main team room
          }}
          onBackToLobby={() => setLobbyCode(null)}
        />
      </div>
    );
  }

  return (
    <div style={{ padding: 20 }}>
      <TeamPulseZone />

      {/* The Crew */}
      <div style={{ marginBottom: 36 }}>
        <div className="fredoka" style={{ color: '#C4845A', fontSize: 20, marginBottom: 12 }}>
          🌸 The Crew
        </div>
        <div className="crew-cards-container">
          {players.filter((player) => !player.isSub).map((player) =>
            <div key={player.id} className="crew-card-wrapper">
              <PlayerCard player={player} />
            </div>
          )}
        </div>
      </div>

      {/* The Bench (substitutes) */}
      {window.SubBench && <window.SubBench />}

      {/* Quick Actions */}
      <div>
        <div className="fredoka" style={{ color: '#C4845A', fontSize: 20, marginBottom: 12 }}>
          ⚡ Quick Actions
        </div>
        <QuickActions />
      </div>
    </div>);

}

Object.assign(window, { HomeScreen, PlayerCard, ClassIdentityBar, ComfortDistributionBar });