
// SubBench.jsx — Substitute roster / "The Bench".
//
// Subs are full player profiles (pools, patch alerts, lookups all work) that
// live in the same players array tagged isSub. Each sub can flag which lanes
// they cover (subRoles) and whether they're available/ready to step in.

const SubBenchNS = (() => {
  const { useState } = React;

  const POSITIONS = ['TOP', 'JUNGLE', 'MID', 'ADC', 'SUPPORT'];

  // ── Availability toggle (Ready ↔ Unavailable) ──────────────────────────────
  function AvailabilityToggle({ available, onToggle }) {
    return (
      <button
        onClick={onToggle}
        className="cozy-btn"
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          background: available ? 'var(--accent-green)' : 'var(--surface-nested)',
          border: `2px solid ${available ? 'var(--accent-green)' : 'var(--border-default)'}`,
          borderRadius: 16, padding: '4px 12px', cursor: 'pointer',
          fontFamily: 'Nunito', fontWeight: 800, fontSize: 12,
          color: available ? 'var(--text-primary)' : 'var(--text-muted)',
          transition: 'all 0.18s',
        }}
        title={available ? 'Tap to mark unavailable' : 'Tap to mark ready'}
      >
        <span style={{
          width: 8, height: 8, borderRadius: '50%',
          background: available ? 'var(--accent-green)' : 'var(--text-muted)',
          boxShadow: available ? '0 0 0 3px rgba(0,0,0,0.15)' : 'none',
        }} />
        {available ? 'Ready to sub ✅' : 'Unavailable 💤'}
      </button>
    );
  }

  // ── Single sub card ────────────────────────────────────────────────────────
  function SubCard({ player }) {
    const {
      champions, setTab, setActivePlayer, updatePlayerName, myUserId, sessionUserId,
      setPlayerAvailability, toggleSubRole, removePlayer, showToast,
    } = window.useApp();
    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 canRemove = player.isSub;

    const [editingName, setEditingName] = useState(false);
    const [nameDraft, setNameDraft] = useState(player.name);
    const [poolModalOpen, setPoolModalOpen] = useState(false);
    const [collapsed, setCollapsed] = useState(false);

    const subRoles = player.subRoles || [player.position];
    const available = player.available !== false;

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

    const topChamps = [...player.pool].sort((a, b) => b.comfort - a.comfort).slice(0, 3);

    const remove = () => {
      if (!window.confirm(`Remove ${player.name} from the bench?`)) return;
      removePlayer(player.id);
      showToast && showToast('Sub removed 👋');
    };

    return (
      <div
        className="cozy-card"
        style={{
          padding: 16, width: '100%', boxSizing: 'border-box',
          position: 'relative', minHeight: collapsed ? 0 : 360, background: 'var(--surface-card)',
          boxShadow: '4px 4px 0 var(--border-default)',
          opacity: available ? 1 : 0.82,
          display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
          transition: 'min-height 0.2s',
        }}
      >
        <div className="corner-dot corner-dot-bl"></div>
        <div className="corner-dot corner-dot-br"></div>

        {/* SUB badge */}
        <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}>
            <window.PawPrint size={9} color="var(--text-on-light)" />
          </window.HexFrame>
          <span>{isMine ? 'Sub · you' : 'Sub'}</span>
        </div>

        {/* Remove button */}
        {canRemove &&
        <button
          onClick={remove}
          title="Remove sub"
          style={{
            position: 'absolute', top: 8, right: 8, zIndex: 3,
            width: 24, height: 24, borderRadius: '50%',
            background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
            color: 'var(--text-muted)', cursor: 'pointer',
            fontFamily: 'Nunito', fontWeight: 800, fontSize: 12,
            lineHeight: '20px', padding: 0,
          }}
        >✕</button>
        }

        {/* Collapse / expand */}
        <button
          onClick={() => setCollapsed(c => !c)}
          title={collapsed ? 'Expand' : 'Collapse'}
          style={{
            position: 'absolute', top: 8, right: 38, zIndex: 3,
            width: 24, height: 24, borderRadius: '50%',
            background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
            color: 'var(--text-muted)', cursor: 'pointer',
            fontFamily: 'Nunito', fontWeight: 800, fontSize: 11,
            lineHeight: '20px', padding: 0,
            transform: collapsed ? 'rotate(0deg)' : 'rotate(180deg)',
            transition: 'transform 0.2s',
          }}
        >▾</button>

        {/* Name */}
        <div style={{ textAlign: 'center', marginTop: 8, marginBottom: 10 }}>
          {editingName && isMine ? (
            <input
              value={nameDraft}
              onChange={e => setNameDraft(e.target.value)}
              onBlur={saveName}
              onKeyDown={e => { if (e.key === 'Enter') saveName(); if (e.key === 'Escape') setEditingName(false); }}
              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"
              onClick={() => { if (isMine) { setEditingName(true); setNameDraft(player.name); } }}
              style={{ fontSize: 16, color: 'var(--text-primary)', cursor: isMine ? 'pointer' : 'default' }}
              title={isMine ? 'Click to rename' : undefined}
            >
              {player.name}{isMine ? ' ✏️' : ''}
            </div>
          )}
        </div>

        {/* Availability */}
        <div style={{ textAlign: 'center', marginBottom: collapsed ? 0 : 12 }}>
          {isMine ? (
            <AvailabilityToggle
              available={available}
              onToggle={() => setPlayerAvailability(player.id, !available)}
            />
          ) : (
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              background: available ? 'var(--accent-green)' : 'var(--surface-nested)',
              border: `2px solid ${available ? 'var(--accent-green)' : 'var(--border-default)'}`,
              borderRadius: 16, padding: '4px 12px',
              fontFamily: 'Nunito', fontWeight: 800, fontSize: 12,
              color: available ? 'var(--text-primary)' : 'var(--text-muted)',
            }}>
              <span style={{
                width: 8, height: 8, borderRadius: '50%',
                background: available ? 'var(--accent-green)' : 'var(--text-muted)',
              }} />
              {available ? 'Ready to sub ✅' : 'Unavailable 💤'}
            </div>
          )}
        </div>

        {/* Collapsed summary: lanes covered + champ count, nothing else */}
        {collapsed && (
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            gap: 6, flexWrap: 'wrap', marginTop: 10,
          }}>
            {subRoles.map(pos => (
              <span key={pos} style={{
                display: 'inline-flex', alignItems: 'center', gap: 3,
                background: colors[pos], border: '2px solid var(--border-emphasis)',
                borderRadius: 12, padding: '2px 7px',
                fontFamily: 'Nunito', fontWeight: 800, fontSize: 10, color: 'var(--text-on-light)',
              }}>
                <window.RoleIcon pos={pos} size={11} />
                {labels[pos]}
              </span>
            ))}
            <span style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-muted)' }}>
              · {player.pool.length} champ{player.pool.length !== 1 ? 's' : ''}
            </span>
          </div>
        )}

        {!collapsed && <>
        {/* Can sub for — role chips */}
        <div style={{ marginBottom: 12 }}>
          <div style={{
            fontSize: 10, fontWeight: 800, color: 'var(--text-muted)',
            textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6,
            textAlign: 'center',
          }}>
            🔁 Can sub for
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, justifyContent: 'center' }}>
            {POSITIONS.map(pos => {
              const on = subRoles.includes(pos);
              // Non-owners: show only the lanes this sub covers, read-only.
              if (!isMine && !on) return null;
              return (
                <button
                  key={pos}
                  onClick={() => { if (isMine) toggleSubRole(player.id, pos); }}
                  className="cozy-btn"
                  style={{
                    display: 'inline-flex', alignItems: 'center', gap: 3,
                    background: on ? colors[pos] : 'var(--surface-nested)',
                    border: `2px solid ${on ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
                    borderRadius: 14, padding: '3px 8px', cursor: isMine ? 'pointer' : 'default',
                    fontFamily: 'Nunito', fontWeight: 800, fontSize: 10.5,
                    color: on ? 'var(--text-on-light)' : 'var(--text-primary)', opacity: on ? 1 : 0.6,
                    transition: 'all 0.15s',
                  }}
                  title={isMine ? (on ? `Covers ${labels[pos]}` : `Tap to cover ${labels[pos]}`) : `Covers ${labels[pos]}`}
                >
                  <window.RoleIcon pos={pos} size={12} />
                  {labels[pos]}
                </button>
              );
            })}
          </div>
        </div>

        {/* Top champions */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 8, minHeight: 180 }}>
          {[0, 1, 2].map(i => {
            const entry = topChamps[i];
            if (!entry) {
              return (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  background: 'var(--surface-nested)', border: '1.5px dashed var(--border-default)',
                  borderRadius: 12, padding: '4px 10px', minHeight: 60,
                }}>
                  <div style={{
                    width: 52, height: 52, borderRadius: 10,
                    border: '1.5px dashed var(--border-default)', background: 'var(--surface-card)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 22, fontWeight: 700, color: 'var(--text-muted)', flexShrink: 0,
                  }}>+</div>
                  <span style={{ flex: 1, fontSize: 12, fontStyle: 'italic', color: 'var(--text-muted)', fontWeight: 700 }}>
                    Empty slot
                  </span>
                </div>
              );
            }
            const comfortLabels = ['', 'Learning', 'Comfortable', 'Confident', 'Ready'];
            const comfortColors = ['', '#7CBF8E', '#c8ae65', '#9e87cc', '#5b9abf'];
            const label = comfortLabels[entry.comfort] || 'Learning';
            const labelColor = comfortColors[entry.comfort] || '#7CBF8E';
            return (
              <div key={entry.championId} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                background: 'var(--surface-nested)', border: '1px solid var(--border-default)',
                borderRadius: 12, padding: '4px 10px',
              }}>
                <window.ChampionIcon championId={entry.championId} size={52} noAnim />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontSize: 13, fontWeight: 800, color: 'var(--text-primary)',
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginBottom: 2,
                  }}>
                    {champions[entry.championId]?.name || entry.championId}
                  </div>
                  <div style={{
                    display: 'inline-block', fontSize: 10, fontWeight: 800, color: labelColor,
                    background: labelColor + '20', border: `1px solid ${labelColor}60`,
                    borderRadius: 8, padding: '1px 6px', fontFamily: 'Nunito',
                  }}>{label}</div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Pool status */}
        <div style={{
          fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
          textAlign: 'center', marginBottom: 10, fontFamily: 'Nunito',
        }}>
          {player.pool.length} champion{player.pool.length !== 1 ? 's' : ''} in pool
        </div>

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

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

  // ── Bench section ──────────────────────────────────────────────────────────
  function SubBench() {
    const { players, addSubstitute, setActivePlayer, setTab, showToast } = window.useApp();
    const subs = players.filter(p => p.isSub);
    const readyCount = subs.filter(p => p.available !== false).length;

    const addSub = () => {
      const id = addSubstitute();
      showToast && showToast('Sub added to the bench 🌱');
      if (id != null) setActivePlayer(id);
    };

    return (
      <div style={{ marginTop: 28, marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12, flexWrap: 'wrap' }}>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 20 }}>
            🪑 The Bench
          </div>
          <window.CozyButton small color="terracotta" onClick={addSub}>
            + Add a sub 🌱
          </window.CozyButton>
          <span style={{ fontSize: 12, fontWeight: 800, color: 'var(--text-muted)' }}>
            {subs.length === 0
              ? 'no subs yet'
              : `${subs.length} sub${subs.length !== 1 ? 's' : ''} · ${readyCount} ready`}
          </span>
        </div>

        {subs.length === 0 ? (
          <div className="cozy-card" style={{ padding: 28, textAlign: 'center' }}>
            <div className="corner-dot corner-dot-bl"></div>
            <div className="corner-dot corner-dot-br"></div>
            <div className="float" style={{ display: 'inline-block', marginBottom: 8 }}>
              <window.PawPrint size={24} color="var(--accent-orange)" />
            </div>
            <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 18, marginBottom: 4 }}>
              No substitutes yet
            </div>
            <div style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 13, maxWidth: 420, margin: '0 auto 14px' }}>
              Got extra players who can step in? Add them to the bench — they get their own
              champion pool and can flag which lanes they cover 🐾
            </div>
            <window.CozyButton color="sage" onClick={addSub}>
              Add your first sub 🌱
            </window.CozyButton>
          </div>
        ) : (
          <div className="sub-cards-container">
            {subs.map(sub => (
              <div key={sub.id} className="sub-card-wrapper">
                <SubCard player={sub} />
              </div>
            ))}
          </div>
        )}
      </div>
    );
  }

  return { SubBench, SubCard };
})();

Object.assign(window, { SubBench: SubBenchNS.SubBench, SubCard: SubBenchNS.SubCard });
