
// EnemyScouter.jsx — Feature 8: Enemy Team Scouter
const { useState, useCallback } = React;
const { useApp } = window;

// Counter relationships: tag → countering tags
const COUNTER_MAP = {
  Assassin:  ['Tank', 'Fighter'],
  Mage:      ['Assassin', 'Fighter'],
  Marksman:  ['Assassin', 'Fighter'],
  Tank:      ['Mage', 'Marksman'],
  Fighter:   ['Tank', 'Mage'],
  Support:   ['Assassin', 'Marksman'],
};

const POSITION_ENEMY_POOLS = {
  TOP:     ['Darius', 'Garen', 'Ornn', 'Malphite', 'Fiora', 'Camille', 'Jax', 'Sett', 'Renekton', 'Yorick'],
  JUNGLE:  ['Vi', 'Warwick', 'Hecarim', 'Amumu', 'LeeSin', 'Graves', 'Viego', 'Kayn', 'Sejuani', 'Rammus'],
  MID:     ['Lux', 'Zed', 'Syndra', 'Veigar', 'Orianna', 'Yasuo', 'Ahri', 'LeBlanc', 'Fizz', 'Cassiopeia'],
  ADC:     ['MissFortune', 'Jinx', 'Caitlyn', 'Jhin', 'Ezreal', 'KaiSa', 'Draven', 'Twitch', 'Vayne', 'Kog\'Maw'],
  SUPPORT: ['Thresh', 'Blitzcrank', 'Lulu', 'Nautilus', 'Morgana', 'Leona', 'Zyra', 'Pyke', 'Soraka', 'Senna'],
};

function hashName(str) {
  let h = 5381;
  for (let i = 0; i < str.length; i++) h = ((h << 5) + h) + str.charCodeAt(i);
  return Math.abs(h);
}

function generateEnemyPool(name, position) {
  const pool = POSITION_ENEMY_POOLS[position];
  const seed = hashName(name + position);
  return [...pool]
    .sort((a, b) => hashName(name + a) - hashName(name + b))
    .slice(0, 3)
    .map((id, i) => ({
      championId: id,
      gamesPlayed: Math.floor(40 + (hashName(id + name) % 60)),
      winRate: 45 + (hashName(name + id + 'wr') % 25),
      kda: ((hashName(name + id + 'kda') % 30) / 10 + 1.5).toFixed(1),
    }));
}

function ThreatBadge({ winRate }) {
  if (winRate >= 58) return <span style={{ background: '#F9D0D0', border: '1.5px solid #E8A0A0', borderRadius: 10, fontSize: 10, fontWeight: 800, padding: '2px 8px', color: '#8b3a3a', fontFamily: 'Nunito' }}>⚠️ High threat</span>;
  if (winRate >= 52) return <span style={{ background: '#F7DFA0', border: '1.5px solid #c8ae65', borderRadius: 10, fontSize: 10, fontWeight: 800, padding: '2px 8px', color: '#6b5420', fontFamily: 'Nunito' }}>🌟 Watch out</span>;
  return <span style={{ background: '#B8E0C0', border: '1.5px solid #7CBF8E', borderRadius: 10, fontSize: 10, fontWeight: 800, padding: '2px 8px', color: '#2d6b47', fontFamily: 'Nunito' }}>✅ Manageable</span>;
}

function findCounterPicks(champData, enemyChampId, playerPool, position) {
  const enemy = champData[enemyChampId];
  if (!enemy) return [];
  const enemyTags = enemy.tags;
  const counterTags = enemyTags.flatMap(t => COUNTER_MAP[t] || []);

  return playerPool
    .filter(entry => entry.position === position)
    .map(entry => {
      const c = champData[entry.championId];
      if (!c) return null;
      const matchScore = c.tags.filter(t => counterTags.includes(t)).length;
      return { ...entry, champData: c, matchScore };
    })
    .filter(Boolean)
    .sort((a, b) => b.matchScore - a.matchScore || b.comfort - a.comfort)
    .slice(0, 3);
}

function EnemyScouter() {
  const { players, champions, POSITIONS, POSITION_EMOJIS } = useApp();
  const [enemyInputs, setEnemyInputs] = useState({ TOP: '', JUNGLE: '', MID: '', ADC: '', SUPPORT: '' });
  const [enemyData, setEnemyData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [activePos, setActivePos] = useState('TOP');

  const allFilled = POSITIONS.every(p => enemyInputs[p].trim());

  const handleScout = useCallback(async () => {
    setLoading(true);
    setEnemyData(null);
    await new Promise(r => setTimeout(r, 800 + Math.random() * 500));
    const data = {};
    POSITIONS.forEach(pos => {
      const name = enemyInputs[pos].trim() || `Enemy${pos}`;
      data[pos] = {
        summonerName: name,
        topChamps: generateEnemyPool(name, pos),
      };
    });
    setEnemyData(data);
    setLoading(false);
  }, [enemyInputs, POSITIONS]);

  const activePosPlayer = players.find(p => p.position === activePos);

  return (
    <div style={{ padding: 20 }}>
      <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 28, marginBottom: 4 }}>
        Enemy Scouter 🕵️
      </h1>
      <p style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 14, margin: '0 0 20px 0' }}>
        Enter opponents' Riot IDs to scout their picks and find counter-picks from your pool
      </p>

      {/* Input grid */}
      <div className="cozy-card" style={{ padding: 20, marginBottom: 20 }}>
        <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 18, marginBottom: 14 }}>
          👥 Enemy Team IDs
        </div>
        <div className="responsive-five-input-grid" style={{ marginBottom: 16 }}>
          {POSITIONS.map(pos => (
            <div key={pos}>
              <label style={{
                fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
                display: 'block', marginBottom: 6,
              }}>
                {POSITION_EMOJIS[pos]} {pos}
              </label>
              <input
                value={enemyInputs[pos]}
                onChange={e => setEnemyInputs(prev => ({ ...prev, [pos]: e.target.value }))}
                placeholder="RiotID#TAG"
                style={{
                  width: '100%', padding: '8px 10px',
                  border: '2px solid var(--border-default)', borderRadius: 12,
                  fontFamily: 'Nunito', fontSize: 12, fontWeight: 700,
                  background: 'var(--surface-nested)', color: 'var(--text-primary)', outline: 'none',
                  boxSizing: 'border-box',
                }}
              />
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <window.CozyButton color="terracotta" onClick={handleScout} disabled={loading}>
            {loading ? '🌀 Scouting…' : '🕵️ Scout Enemy Team'}
          </window.CozyButton>
          {!allFilled && (
            <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-muted)' }}>
              Fill all 5 for a full scout, or scout partial teams too!
            </span>
          )}
        </div>
      </div>

      {loading && (
        <div className="cozy-card" style={{ padding: 40, textAlign: 'center' }}>
          <div className="float" style={{ fontSize: 44, marginBottom: 12 }}>🕵️</div>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 20 }}>Peeking at their profile…</div>
        </div>
      )}

      {enemyData && !loading && (
        <div className="responsive-two-column">
          {/* Position nav */}
          <div style={{ display: 'flex', flexDirection: 'row', flexWrap: 'wrap', gap: 8, alignContent: 'flex-start' }}>
            {POSITIONS.map(pos => {
              const d = enemyData[pos];
              const topChamp = d.topChamps[0];
              return (
                <button
                  key={pos}
                  onClick={() => setActivePos(pos)}
                  className="cozy-btn"
                  style={{
                    display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
                    background: activePos === pos ? 'var(--accent-orange)' : 'var(--surface-card)',
                    border: `2px solid ${activePos === pos ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
                    borderRadius: 14, cursor: 'pointer', textAlign: 'left',
                  }}
                >
                  <window.ChampionIcon championId={topChamp?.championId} size={36} noAnim />
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 800, color: activePos === pos ? 'var(--surface-nested)' : 'var(--text-muted)' }}>{pos}</div>
                    <div style={{ fontSize: 12, fontWeight: 800, color: activePos === pos ? 'var(--surface-nested)' : 'var(--text-primary)' }}>
                      {d.summonerName.slice(0, 10)}
                    </div>
                  </div>
                </button>
              );
            })}
          </div>

          {/* Detail pane */}
          <div>
            {enemyData[activePos] && (
              <EnemyDetail
                pos={activePos}
                data={enemyData[activePos]}
                player={activePosPlayer}
                champions={champions}
              />
            )}
          </div>
        </div>
      )}
    </div>
  );
}

function EnemyDetail({ pos, data, player, champions }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Most played */}
      <div className="cozy-card" style={{ padding: 16 }}>
        <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 16, marginBottom: 12 }}>
          📊 {data.summonerName}'s Most Played
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {data.topChamps.map((m, i) => {
            const cd = champions[m.championId];
            return (
              <div key={m.championId} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
                borderRadius: 12, padding: '8px 12px',
              }}>
                <span style={{ fontSize: 12, fontWeight: 800, color: 'var(--text-muted)', width: 20 }}>#{i+1}</span>
                <window.ChampionIcon championId={m.championId} size={44} noAnim />
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 800, fontSize: 14, color: 'var(--text-primary)' }}>
                    {cd?.name || m.championId}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--text-muted)', fontWeight: 700 }}>
                    {m.gamesPlayed} games · {m.kda} KDA
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontWeight: 800, fontSize: 14, color: m.winRate >= 55 ? '#E85555' : m.winRate >= 50 ? 'var(--accent-orange)' : '#7CBF8E' }}>
                    {m.winRate}% WR
                  </div>
                  <ThreatBadge winRate={m.winRate} />
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Counter-picks from pool */}
      <div className="cozy-card" style={{ padding: 16 }}>
        <div className="fredoka" style={{ color: '#7CBF8E', fontSize: 16, marginBottom: 4 }}>
          🎯 Counter-Pick Suggestions
        </div>
        <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-muted)', marginBottom: 12 }}>
          From {player?.name || pos}'s pool — sorted by matchup strength
        </div>
        {player && player.pool.filter(e => e.position === pos).length > 0 ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {findCounterPicks(champions, data.topChamps[0]?.championId, player.pool, pos).map(entry => (
              <div key={entry.championId} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                background: entry.matchScore > 0 ? 'rgba(184, 224, 192, 0.15)' : 'var(--surface-nested)',
                border: `1.5px solid ${entry.matchScore > 0 ? '#7CBF8E' : 'var(--border-default)'}`,
                borderRadius: 12, padding: '8px 12px',
              }}>
                <window.ChampionIcon championId={entry.championId} size={44} noAnim />
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 800, fontSize: 14, color: 'var(--text-primary)' }}>
                    {entry.champData?.name || entry.championId}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--text-muted)', fontWeight: 700 }}>
                    {entry.champData?.tags?.join(' · ')}
                  </div>
                </div>
                {entry.matchScore > 0 ? (
                  <window.Tag color="green">Strong counter 🎯</window.Tag>
                ) : (
                  <window.Tag color="pink">Neutral matchup</window.Tag>
                )}
              </div>
            ))}
            {findCounterPicks(champions, data.topChamps[0]?.championId, player.pool, pos).length === 0 && (
              <div style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 13, padding: 12 }}>
                No counter picks found. Add more champions to {player.name}'s {pos} pool! 🌱
              </div>
            )}
          </div>
        ) : (
          <div style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 13, padding: 12 }}>
            {player?.name || pos} has no {pos} champions in pool yet. Head to My Pool to add some! 🌸
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { EnemyScouter });
