
// PlayerPoolModal.jsx — View-only modal showing a teammate's full champion pool.
//
// Trigger: a "View full pool 👁️" sticker on every teammate's PlayerCard in
// HomeScreen. The current user's own card keeps the "Edit pool 🌸" button.
//
// Pool entry shape used across the app:
//   { championId, position, comfort: 1..4, playstyle: 'onetrick'|'main'|'flex' }
//
// Sections (top → bottom) match the comfort scale used in MyPool.jsx:
//   4 Ready 🌟  ·  3 Confident 💪  ·  2 Comfortable 😊  ·  1 Learning 🌱

(() => {
  if (document.getElementById('player-pool-modal-css')) return;
  const s = document.createElement('style');
  s.id = 'player-pool-modal-css';
  s.textContent = `
    @keyframes ppm-fade-in   { from { opacity: 0; }                                       to { opacity: 1; } }
    @keyframes ppm-pop-in    { 0% { transform: scale(0.84) translateY(20px); opacity: 0; }
                               70%{ transform: scale(1.03) translateY(0);    opacity: 1; }
                               100%{transform: scale(1)    translateY(0);    opacity: 1; } }
    @keyframes ppm-hex-pulse { 0%, 100% { box-shadow: 0 0 0 0 var(--pulse, #C4845A55); }
                               50%      { box-shadow: 0 0 0 6px transparent; } }
    @keyframes ppm-bob       { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-3px); } }

    .ppm-backdrop      { animation: ppm-fade-in 0.2s ease-out; }
    .ppm-card          { animation: ppm-pop-in 0.32s cubic-bezier(0.34, 1.56, 0.64, 1); }
    .ppm-hex-pulse     { animation: ppm-hex-pulse 2.4s ease-in-out infinite; }
    .ppm-row:hover     { background: var(--border-default) !important; }
    .ppm-row:hover .ppm-champ-wrap { animation: ppm-bob 1.2s ease-in-out infinite; }
    .ppm-pill          { transition: transform 0.15s cubic-bezier(0.34, 1.56, 0.64, 1); }
    .ppm-pill:active   { transform: scale(0.92); }

    @media (max-width: 720px) {
      .ppm-card { max-width: 96vw !important; max-height: 92vh !important; }
      .ppm-header-row { flex-wrap: wrap !important; }
      .ppm-section-row { padding: 8px 10px !important; }
      .ppm-champ-size  { width: 40px !important; height: 40px !important; }
    }
  `;
  document.head.appendChild(s);
})();

const PlayerPoolModalNS = (() => {
  const { useState, useEffect, useMemo } = React;

  const COMFORT_SECTIONS = [
    { id: 4, label: 'Ready',       emoji: '🌟', accent: '#F7DFA0', border: '#c8ae65', text: '#6b5420', subtitle: 'lock-in picks' },
    { id: 3, label: 'Confident',   emoji: '💪', accent: '#C5B4E3', border: '#9e87cc', text: '#4a2d8b', subtitle: 'solid bench' },
    { id: 2, label: 'Comfortable', emoji: '😊', accent: '#F7DFA0', border: '#c8ae65', text: '#6b5420', subtitle: 'situational' },
    { id: 1, label: 'Learning',    emoji: '🌱', accent: '#B8E0C0', border: '#7CBF8E', text: '#2d6b47', subtitle: 'still cooking' },
  ];

  const PLAYSTYLE_TAGS = {
    onetrick: { label: 'One-trick 🎯', bg: '#F9D0D0', border: '#E8A0A0', text: '#8b3a3a' },
    main:     { label: 'Main 🌟',       bg: '#F7DFA0', border: '#c8ae65', text: '#6b5420' },
    flex:     { label: 'Flex 🌿',       bg: '#B8E0C0', border: '#7CBF8E', text: '#2d6b47' },
  };

  // ── Single champion row ────────────────────────────────────────────────────
  function ChampRow({ entry, champData, patch, player }) {
    const { sessionUserId, toggleFocusPick } = window.useApp();
    const colors = window.POSITION_COLORS;
    const isFlex = entry.playstyle === 'flex' || entry.isFlex === true;
    const tag = isFlex ? PLAYSTYLE_TAGS.flex : (PLAYSTYLE_TAGS[entry.playstyle] || null);
    const isFocused = Boolean(entry.isFocusPick || entry.focusPick);
    const isOwner = player ? !!(player.claimed && player.ownerId && player.ownerId === sessionUserId) : false;

    const handleToggleFocus = (e) => {
      e.stopPropagation();
      if (isOwner && toggleFocusPick) {
        toggleFocusPick(player.id, entry.championId, entry.position);
      }
    };

    // Border tint reflects patch status; sage = buff, soft red = nerf, terracotta = neutral.
    const borderColor = patch?.type === 'buff' ? 'var(--accent-green)'
                      : patch?.type === 'nerf' ? '#E8A0A0'
                      : 'var(--accent-orange)';
    const pulseColor  = patch?.type === 'buff' ? 'rgba(124, 191, 142, 0.35)'
                      : patch?.type === 'nerf' ? 'rgba(232, 160, 160, 0.35)'
                      : null;

    return (
      <div className="ppm-row" style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '8px 10px', borderRadius: 12,
        transition: 'background 0.18s',
      }}>
        {/* Hex champion frame */}
        <div
          className={`ppm-champ-wrap ppm-champ-size ${patch ? 'ppm-hex-pulse' : ''}`}
          style={{ position: 'relative', flexShrink: 0, '--pulse': pulseColor }}
        >
          <window.HexFrame size={48} color={borderColor} borderColor={borderColor} borderWidth={2.5}>
            <div style={{
              width: '78%', height: '78%', borderRadius: 8, overflow: 'hidden',
              background: 'var(--surface-card)',
            }}>
              <window.ChampionIcon
                championId={entry.championId} size={48} noAnim
                style={{ width: '100%', height: '100%', border: 'none', borderRadius: 0 }}
              />
            </div>
          </window.HexFrame>
          {/* Patch direction dot */}
          {patch && (
            <div style={{
              position: 'absolute', top: -3, right: -3,
              width: 18, height: 18, borderRadius: '50%',
              background: patch.type === 'buff' ? '#B8E0C0' : '#F9D0D0',
              border: `1.5px solid ${patch.type === 'buff' ? 'var(--accent-green)' : '#E8A0A0'}`,
              fontSize: 10, display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>{patch.type === 'buff' ? '⬆️' : '⬇️'}</div>
          )}
        </div>

        {/* Text block */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap',
            marginBottom: 3,
          }}>
            <span style={{
              fontFamily: 'Nunito', fontWeight: 800, fontSize: 14.5,
              color: 'var(--text-primary)',
            }}>
              {champData?.name || entry.championId}
            </span>
            {tag && (
              <span style={{
                background: tag.bg, border: `1.5px solid ${tag.border}`,
                borderRadius: 14, padding: '1px 8px', fontSize: 10, fontWeight: 800,
                fontFamily: 'Nunito', color: tag.text,
              }}>{tag.label}</span>
            )}
          </div>
          {patch && (
            <div style={{
              fontSize: 11.5, fontStyle: 'italic', fontWeight: 700,
              color: patch.type === 'buff' ? 'var(--accent-green)' : '#8b3a3a',
              lineHeight: 1.35,
            }}>
              {patch.type === 'buff' ? '🌿 ' : '⚠️ '}{patch.summary}
            </div>
          )}
        </div>

        {/* Star icon toggle */}
        <button
          onClick={isOwner ? handleToggleFocus : undefined}
          title={isFocused ? 'Playing this week — click to unselect' : (isOwner ? 'Mark as playing this week' : 'Playing this week')}
          style={{
            background: 'transparent', border: 'none', padding: 0,
            width: 38, height: 38, borderRadius: '50%',
            fontSize: 22, lineHeight: 1, cursor: isOwner ? 'pointer' : 'default',
            color: isFocused ? 'var(--accent-orange)' : 'var(--border-default)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0, outline: 'none', transition: 'transform 0.15s, color 0.15s',
          }}
        >{isFocused ? '⭐' : '☆'}</button>
      </div>
    );
  }

  // ── Section header ─────────────────────────────────────────────────────────
  function SectionHeader({ section, count }) {
    return (
      <div className="ppm-section-row" style={{
        display: 'flex', alignItems: 'center', gap: 8,
        background: section.accent + '55',
        border: `1.5px solid ${section.border}`,
        borderRadius: 14, padding: '6px 14px',
        margin: '14px 0 6px',
        position: 'sticky', top: 0, zIndex: 2,
      }}>
        <span className="fredoka" style={{ color: section.text, fontSize: 15 }}>
          {section.label} {section.emoji}
        </span>
        <span style={{ fontSize: 11, fontWeight: 800, color: section.text + 'CC' }}>
          · {count} champ{count !== 1 ? 's' : ''}
        </span>
        <span style={{
          marginLeft: 'auto', fontSize: 10, fontWeight: 700,
          color: section.text + 'AA', fontStyle: 'italic',
        }}>
          {section.subtitle}
        </span>
      </div>
    );
  }

  // ── Confused-poro empty illustration ───────────────────────────────────────
  function ConfusedPoro() {
    return (
      <svg viewBox="0 0 110 100" width="120" height="110">
        <ellipse cx="55" cy="62" rx="34" ry="28" fill="var(--surface-card)" stroke="var(--border-emphasis)" strokeWidth="2.5" />
        <ellipse cx="55" cy="70" rx="22" ry="14" fill="var(--surface-nested)" />
        <path d="M28 42 Q24 28 36 26 L42 40 Z" fill="var(--surface-card)" stroke="var(--border-emphasis)" strokeWidth="2.5" strokeLinejoin="round" />
        <path d="M82 42 Q86 28 74 26 L68 40 Z" fill="var(--surface-card)" stroke="var(--border-emphasis)" strokeWidth="2.5" strokeLinejoin="round" />
        <path d="M30 38 Q28 32 34 31" fill="#F2A7C3" />
        <path d="M80 38 Q82 32 76 31" fill="#F2A7C3" />
        {/* Confused eyes (one squint, one wide) */}
        <path d="M44 56 Q46 54 48 56" stroke="var(--text-primary)" strokeWidth="2" fill="none" strokeLinecap="round" />
        <circle cx="64" cy="56" r="2.6" fill="var(--text-primary)" />
        <circle cx="64.6" cy="55.3" r="0.7" fill="var(--surface-card)" />
        <ellipse cx="55" cy="64" rx="2.4" ry="1.6" fill="var(--text-primary)" />
        <path d="M52 68 Q55 70 58 68" stroke="var(--text-primary)" strokeWidth="1.5" fill="none" strokeLinecap="round" />
        {/* Question marks */}
        <text x="80" y="26" fontFamily="Fredoka One, cursive" fontSize="14" fill="#C5B4E3">?</text>
        <text x="92" y="38" fontFamily="Fredoka One, cursive" fontSize="10" fill="#F7DFA0">?</text>
        <text x="20" y="22" fontFamily="Fredoka One, cursive" fontSize="12" fill="var(--accent-green)">?</text>
        <ellipse cx="38" cy="62" rx="3" ry="2" fill="#F2A7C3" opacity="0.6" />
        <ellipse cx="72" cy="62" rx="3" ry="2" fill="#F2A7C3" opacity="0.6" />
      </svg>
    );
  }

  // ── Main modal ─────────────────────────────────────────────────────────────
  function PlayerPoolModal({ player, onClose, isSelf }) {
    const { champions, setTab, setActivePlayer, getEffectivePlayerPool, sessionUserId } = window.useApp();
    const [filterTag, setFilterTag] = useState('All');
    const getPatch = window.getChampPatchStatus;
    const archetype = window.ARCHETYPE_BY_POSITION[player.position];
    const posColor  = window.POSITION_COLORS[player.position];
    const labels    = window.POSITION_LABELS;
    const activePool = getEffectivePlayerPool ? getEffectivePlayerPool(player) : (player.pool || []);

    const authUser = window.firebase && window.firebase.auth && window.firebase.auth().currentUser;
    const authUid = authUser ? authUser.uid : null;
    const isOwnPool = isSelf !== undefined ? !!isSelf : !!(player && (player.claimed || player.ownerId || player.uid) && (
      (authUid && (player.uid === authUid || player.ownerId === authUid)) ||
      (!authUid && sessionUserId && player.ownerId === sessionUserId)
    ));

    // Close on Escape
    useEffect(() => {
      const onKey = (e) => { if (e.key === 'Escape') onClose(); };
      document.addEventListener('keydown', onKey);
      const prevOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => {
        document.removeEventListener('keydown', onKey);
        document.body.style.overflow = prevOverflow;
      };
    }, [onClose]);

    const filteredPool = useMemo(() => {
      return activePool.filter(e => {
        if (filterTag === 'All') return true;
        const champ = champions[e.championId];
        return champ && Array.isArray(champ.tags) && champ.tags.includes(filterTag);
      });
    }, [activePool, filterTag, champions]);

    // Group by comfort
    const grouped = useMemo(() => {
      const g = { 4: [], 3: [], 2: [], 1: [] };
      filteredPool.forEach(e => {
        const c = Math.max(1, Math.min(4, e.comfort || 1));
        g[c].push(e);
      });
      // Within a section, sort alphabetically by champion name for predictability.
      Object.keys(g).forEach(k => {
        g[k].sort((a, b) => {
          const an = champions[a.championId]?.name || a.championId;
          const bn = champions[b.championId]?.name || b.championId;
          return an.localeCompare(bn);
        });
      });
      return g;
    }, [filteredPool, champions]);

    const patchAlerts = useMemo(
      () => activePool.map(e => getPatch?.(e.championId)).filter(Boolean),
      [activePool, getPatch],
    );

    const totalCount    = activePool.length;
    const filteredCount = filteredPool.length;

    const jumpToPatch = () => {
      setTab('meta', { metaViewPlayerId: player.id });
      onClose();
    };

    const modalContent = (
      <div
        className="ppm-backdrop"
        onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}
        style={{
          position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
          width: '100vw', height: '100vh', zIndex: 9999,
          background: 'rgba(74, 55, 40, 0.65)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 20, boxSizing: 'border-box',
        }}
      >
        <div
          className="cozy-card ppm-card"
          onMouseDown={(e) => e.stopPropagation()}
          style={{
            width: '100%', maxWidth: 700, maxHeight: '85vh',
            padding: 22, display: 'flex', flexDirection: 'column',
            position: 'relative', background: 'var(--surface-modal)',
            boxShadow: '0 16px 48px rgba(74, 55, 40, 0.45)',
            border: '2.5px solid var(--border-emphasis)', borderRadius: 20,
          }}
        >
          <div className="corner-dot corner-dot-bl"></div>
          <div className="corner-dot corner-dot-br"></div>

          {/* Close X */}
          <button
            onClick={onClose}
            className="cozy-btn"
            style={{
              position: 'absolute', top: 14, right: 14, zIndex: 3,
              width: 32, height: 32, borderRadius: '50%',
              background: 'var(--surface-nested)', border: '2px solid var(--border-emphasis)',
              color: 'var(--accent-orange)', cursor: 'pointer',
              fontFamily: 'Nunito', fontWeight: 800, fontSize: 16,
              boxShadow: '0 2px 0 var(--border-default)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }}
            aria-label="Close"
          >✕</button>

          {/* Header */}
          <div className="ppm-header-row" style={{
            display: 'flex', alignItems: 'center', gap: 14,
            paddingTop: 6, paddingRight: 40, marginBottom: 14,
          }}>
            <window.HexFrame
              size={56}
              color={player.identityColor || posColor}
              borderColor="var(--border-emphasis)" borderWidth={2.5}
            >
              <span style={{ fontFamily: 'Fredoka One', fontSize: 22, color: 'var(--text-on-light)' }}>
                {player.name[0]}
              </span>
            </window.HexFrame>

            <div style={{ flex: 1, minWidth: 0 }}>
              <h2 className="fredoka" style={{
                color: 'var(--accent-orange)', fontSize: 24, margin: 0, lineHeight: 1.1,
                overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              }}>
                {player.name}'s pool
              </h2>
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                marginTop: 4, fontSize: 12, fontWeight: 800, color: 'var(--text-muted)',
              }}>
                <window.HexFrame size={20} color={posColor} borderColor="var(--border-emphasis)" borderWidth={1.5}>
                  <window.RoleSilhouette archetype={archetype} size={12} color="var(--text-on-light)" />
                </window.HexFrame>
                {labels[player.position]} main
                {player.online && (
                  <span style={{
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                    marginLeft: 6, color: 'var(--accent-green)',
                  }}>
                    <span style={{
                      width: 6, height: 6, borderRadius: '50%',
                      background: 'var(--accent-green)',
                    }} />
                    online
                  </span>
                )}
              </div>
            </div>

            {/* Count badge in their position color */}
            <div style={{
              background: posColor,
              border: '2px solid var(--border-default)', borderRadius: 20,
              padding: '6px 14px', flexShrink: 0,
              fontFamily: 'Nunito', fontWeight: 800, fontSize: 13,
              color: 'var(--text-primary)', display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              {totalCount} champ{totalCount !== 1 ? 's' : ''}
              <window.PawPrint size={14} color="var(--text-primary)" />
            </div>
          </div>

          {/* Patch alerts banner */}
          {patchAlerts.length > 0 && (
            <button
              onClick={jumpToPatch}
              className="cozy-btn"
              style={{
                display: 'flex', alignItems: 'center', gap: 8,
                background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
                borderRadius: 14, padding: '8px 14px', marginBottom: 12,
                fontFamily: 'Nunito', fontWeight: 800, fontSize: 12,
                color: 'var(--text-primary)', cursor: 'pointer', textAlign: 'left',
                width: '100%',
              }}
              title="Open Patch tab"
            >
              <span style={{ fontSize: 16 }}>📰</span>
              <span>
                {patchAlerts.length} patch alert{patchAlerts.length !== 1 ? 's' : ''} in {player.name}'s pool
              </span>
              <span style={{ marginLeft: 'auto', color: 'var(--accent-orange)', fontSize: 13 }}>→</span>
            </button>
          )}

          {/* Filter pills */}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 12 }}>
            {(window.FILTER_TAGS || ['All', 'Tank', 'Fighter', 'Mage', 'Assassin', 'Marksman', 'Support']).map(tag => {
              const active = filterTag === tag;
              const emoji = (window.FILTER_EMOJIS || {})[tag] || '';
              return (
                <button
                  key={tag}
                  onClick={() => setFilterTag(tag)}
                  className="cozy-btn ppm-pill"
                  style={{
                    padding: '4px 12px',
                    background: active ? 'var(--accent-orange)' : 'var(--surface-modal)',
                    color: active ? '#FFFFFF' : 'var(--text-primary)',
                    border: active ? '2.5px solid var(--border-emphasis)' : '1.5px solid var(--border-default)',
                    borderRadius: 18,
                    fontFamily: 'Nunito', fontSize: 12, fontWeight: 800,
                    cursor: 'pointer',
                    boxShadow: active ? '0 3px 0 var(--border-default)' : 'none',
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                  }}
                >
                  <span>{tag}</span>
                  <span style={{ fontSize: 11 }}>{emoji}</span>
                </button>
              );
            })}
          </div>

          {/* Scroll body */}
          <div style={{
            flex: 1, overflowY: 'auto', minHeight: 0,
            paddingRight: 6, marginRight: -6,
          }}>
            {totalCount === 0 ? (
              <div style={{ textAlign: 'center', padding: '32px 16px' }}>
                <div className="float" style={{ display: 'inline-block', marginBottom: 10 }}>
                  <ConfusedPoro />
                </div>
                <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 20, marginBottom: 6 }}>
                  No champions in {player.name}'s pool yet 🌿
                </div>
                <div style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 13 }}>
                  They haven't started cooking yet!
                </div>
              </div>
            ) : filteredCount === 0 ? (
              <div style={{ textAlign: 'center', padding: '28px 16px' }}>
                <div className="float" style={{ display: 'inline-block', marginBottom: 10 }}>
                  <ConfusedPoro />
                </div>
                <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 19, marginBottom: 4 }}>
                  No {filterTag} champs in {player.name}'s pool yet 🌿
                </div>
                <div style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 13 }}>
                  Maybe they're focused on another archetype this Clash 💛
                </div>
              </div>
            ) : (
              COMFORT_SECTIONS.map(section => {
                const rows = grouped[section.id];
                if (!rows || rows.length === 0) return null;
                return (
                  <div key={section.id}>
                    <SectionHeader section={section} count={rows.length} />
                    <div>
                      {rows.map(entry => (
                        <ChampRow
                          key={`${entry.championId}-${entry.position}`}
                          entry={entry}
                          champData={champions[entry.championId]}
                          patch={getPatch?.(entry.championId)}
                          player={player}
                        />
                      ))}
                    </div>
                  </div>
                );
              })
            )}
          </div>

          {/* Footer */}
          <div style={{
            display: 'flex', justifyContent: 'center', alignItems: 'center',
            paddingTop: 14, marginTop: 8,
            borderTop: '1.5px dashed var(--border-default)',
            gap: 10,
          }}>
            <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)' }}>
              {isOwnPool ? 'This is your pool' : `👁️ View-only — ${player.name} controls their pool`}
            </span>
            <window.CozyButton color="cream" onClick={onClose}>
              Close 👋
            </window.CozyButton>
          </div>
        </div>
      </div>
    );

    if (typeof ReactDOM !== 'undefined' && ReactDOM.createPortal) {
      return ReactDOM.createPortal(modalContent, document.body);
    }
    return modalContent;
  }

  return { PlayerPoolModal };
})();

Object.assign(window, { PlayerPoolModal: PlayerPoolModalNS.PlayerPoolModal });
