
// MetaAlerts.jsx — Feature 10: Patch Meta Alerts (standalone component + used in MyPool)
// Uses a curated mock patch note dataset — Riot doesn't expose patch notes via public API
const { useState, useEffect } = React;
const { useApp } = window;

// Patch 26.17 changes — curated dataset of notable buffs/nerfs/reworks
const PATCH_NOTES = {
  version: '26.17',
  date: 'August 26, 2026',
  changes: {
    // BUFFS
    AurelionSol:   { type: 'buff', summary: 'Q mana cost and W cooldown reduced', impact: 'medium' },
    "Aurelion Sol": { type: 'buff', summary: 'Q mana cost and W cooldown reduced', impact: 'medium' },
    Chogath:       { type: 'buff', summary: 'E base damage increased', impact: 'medium' },
    "Cho'Gath":    { type: 'buff', summary: 'E base damage increased', impact: 'medium' },
    Irelia:        { type: 'buff', summary: 'Q AD ratio and R AP ratio increased', impact: 'medium' },
    Leblanc:       { type: 'buff', summary: 'Attack speed and W/R AP ratios increased', impact: 'medium' },
    LeBlanc:       { type: 'buff', summary: 'Attack speed and W/R AP ratios increased', impact: 'medium' },
    Qiyana:        { type: 'buff', summary: 'Q damage increased (monster damage reduced)', impact: 'medium' },
    Trundle:       { type: 'buff', summary: 'W attack speed increased', impact: 'medium' },
    Yasuo:         { type: 'buff', summary: 'Crit damage penalty reduced', impact: 'high' },
    Yone:          { type: 'buff', summary: 'Crit damage penalty reduced', impact: 'high' },

    // NERFS
    Graves:        { type: 'nerf', summary: 'Q damage reduced', impact: 'medium' },
    Nasus:         { type: 'nerf', summary: 'Passive lifesteal reduced', impact: 'medium' },
    Nocturne:      { type: 'nerf', summary: 'Armor and health reduced', impact: 'medium' },
    Thresh:        { type: 'nerf', summary: 'E damage reduced', impact: 'medium' },
    Vayne:         { type: 'nerf', summary: 'Base stats reworked, Q mana cost up, W damage down', impact: 'high' },
    Xerath:        { type: 'nerf', summary: 'Health and Q damage reduced', impact: 'medium' },
  }
};

// Export for use in MyPool
function getChampPatchStatus(championId) {
  return PATCH_NOTES.changes[championId] || null;
}

function PatchBadge({ championId, size = 'normal' }) {
  const status = getChampPatchStatus(championId);
  if (!status) return null;

  const styles = {
    buff:   { bg: '#B8E0C0', border: '#7CBF8E', text: '#2d6b47', icon: '⬆️' },
    nerf:   { bg: '#F9D0D0', border: '#E8A0A0', text: '#8b3a3a', icon: '⬇️' },
    adjust: { bg: '#F7DFA0', border: '#c8ae65', text: '#6b5420', icon: '↔️' },
  };
  const s = styles[status.type];
  const impactDot = { high: '🔴', medium: '🟡', low: '🟢' }[status.impact];

  if (size === 'dot') {
    return (
      <span title={`${status.type.toUpperCase()}: ${status.summary}`} style={{
        position: 'absolute', top: -4, right: -4, fontSize: 12,
        background: s.bg, border: `1.5px solid ${s.border}`,
        borderRadius: '50%', width: 18, height: 18,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        zIndex: 2, lineHeight: 1,
      }}>{s.icon}</span>
    );
  }

  return (
    <span style={{
      background: s.bg, border: `1.5px solid ${s.border}`,
      borderRadius: 10, fontSize: 10, fontWeight: 800,
      padding: '2px 6px', color: s.text,
      fontFamily: 'Nunito', display: 'inline-flex', alignItems: 'center', gap: 3,
      flexShrink: 0,
    }}>
      {s.icon} {status.type.charAt(0).toUpperCase() + status.type.slice(1)}
      {size === 'full' && <span style={{ fontSize: 9 }}>{impactDot}</span>}
    </span>
  );
}

function MetaAlerts() {
  const { players, champions, activePlayerId, metaViewPlayerId, POSITIONS, POSITION_EMOJIS, getEffectivePlayerPool } = useApp();
  const [activePlayer, setActivePlayer] = useState(metaViewPlayerId ?? activePlayerId ?? players[0]?.id ?? 0);
  const [filter, setFilter] = useState('all'); // all | buff | nerf | adjust

  // Follow metaViewPlayerId or activePlayerId for view pre-filtering
  useEffect(() => {
    if (metaViewPlayerId != null) {
      setActivePlayer(metaViewPlayerId);
    } else if (activePlayerId != null) {
      setActivePlayer(activePlayerId);
    }
  }, [metaViewPlayerId, activePlayerId]);

  const player = players.find(p => p.id === activePlayer) || players[0];
  const posColors = window.POSITION_COLORS;

  const getPool = (p) => (getEffectivePlayerPool ? getEffectivePlayerPool(p) : (p?.pool || []));
  const activePool = getPool(player);

  // Find all pool entries with patch changes
  const flagged = activePool
    .map(entry => {
      const status = getChampPatchStatus(entry.championId);
      return status ? { ...entry, status } : null;
    })
    .filter(Boolean)
    .filter(e => filter === 'all' || e.status.type === filter)
    .sort((a, b) => {
      const impactOrder = { high: 0, medium: 1, low: 2 };
      return impactOrder[a.status.impact] - impactOrder[b.status.impact];
    });

  const buffCount   = activePool.filter(e => getChampPatchStatus(e.championId)?.type === 'buff').length;
  const nerfCount   = activePool.filter(e => getChampPatchStatus(e.championId)?.type === 'nerf').length;
  const adjustCount = activePool.filter(e => getChampPatchStatus(e.championId)?.type === 'adjust').length;

  return (
    <div style={{ padding: 20 }}>
      <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 28, marginBottom: 4 }}>
        Patch Meta Alerts 📰
      </h1>
      <p style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 14, margin: '0 0 20px 0' }}>
        Champions in your pool affected by Patch {PATCH_NOTES.version} ({PATCH_NOTES.date})
      </p>

      {/* Player tabs */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 16, flexWrap: 'wrap' }}>
        {players.map(p => {
          const pPool   = getPool(p);
          const pBuffs  = pPool.filter(e => getChampPatchStatus(e.championId)?.type === 'buff').length;
          const pNerfs  = pPool.filter(e => getChampPatchStatus(e.championId)?.type === 'nerf').length;
          return (
            <button key={p.id} onClick={() => setActivePlayer(p.id)} className="cozy-btn" style={{
              padding: '6px 14px', border: `2px solid ${p.id === activePlayer ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
              borderRadius: 14, fontFamily: 'Nunito', fontSize: 13, fontWeight: 800,
              background: p.id === activePlayer ? posColors[p.position] : 'var(--surface-nested)',
              color: p.id === activePlayer ? 'var(--text-on-light-pastel)' : 'var(--text-primary)', cursor: 'pointer',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              {POSITION_EMOJIS[p.position]} {p.name}
              {pBuffs  > 0 && <span style={{ background: '#B8E0C0', color: 'var(--text-on-light-pastel)', borderRadius: 8, fontSize: 10, padding: '1px 5px' }}>⬆️{pBuffs}</span>}
              {pNerfs  > 0 && <span style={{ background: '#F9D0D0', color: 'var(--text-on-light-pastel)', borderRadius: 8, fontSize: 10, padding: '1px 5px' }}>⬇️{pNerfs}</span>}
            </button>
          );
        })}
      </div>

      {/* Summary row */}
      <div className="responsive-three-column" style={{ marginBottom: 20 }}>
        {[
          { label: 'Buffed', count: buffCount, bg: '#B8E0C0', border: '#7CBF8E', icon: '⬆️', type: 'buff' },
          { label: 'Nerfed', count: nerfCount, bg: '#F9D0D0', border: '#E8A0A0', icon: '⬇️', type: 'nerf' },
          { label: 'Adjusted', count: adjustCount, bg: '#F7DFA0', border: '#c8ae65', icon: '↔️', type: 'adjust' },
        ].map(s => (
          <div key={s.type}
            onClick={() => setFilter(filter === s.type ? 'all' : s.type)}
            style={{
              background: filter === s.type ? s.bg : s.bg + '50',
              border: `2px solid ${s.border}`,
              borderRadius: 16, padding: '14px 16px', cursor: 'pointer',
              transition: 'all 0.2s',
              boxShadow: filter === s.type ? `0 4px 0 ${s.border}` : 'none',
            }}>
            <div style={{ fontSize: 28, marginBottom: 4 }}>{s.icon}</div>
            <div className="fredoka" style={{ fontSize: 28, color: 'var(--text-on-light-pastel)' }}>{s.count}</div>
            <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--text-on-light-pastel)' }}>{s.label} this patch</div>
          </div>
        ))}
      </div>

      {/* Flagged champs */}
      {flagged.length === 0 ? (
        <div className="cozy-card" style={{ padding: 40, textAlign: 'center' }}>
          <div style={{ fontSize: 48, marginBottom: 12 }}>🌿</div>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 22, marginBottom: 8 }}>
            {activePool.length === 0
              ? 'No champions in pool yet!'
              : filter === 'all' ? 'No pool changes this patch! 🎉' : `No ${filter}s in ${player.name}'s pool`}
          </div>
          <div style={{ color: 'var(--text-muted)', fontWeight: 700 }}>
            {activePool.length === 0
              ? 'Add champions in My Pool 🌸 first'
              : 'Your pool is untouched — nice! Keep an eye out next patch.'}
          </div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {flagged.map(entry => {
            const cd = champions[entry.championId];
            const statusStyles = {
              buff:   { bg: '#B8E0C015', border: '#7CBF8E', badgeBg: '#B8E0C0', badgeText: '#2d6b47' },
              nerf:   { bg: '#F9D0D015', border: '#E8A0A0', badgeBg: '#F9D0D0', badgeText: '#8b3a3a' },
              adjust: { bg: '#F7DFA015', border: '#c8ae65', badgeBg: '#F7DFA0', badgeText: '#6b5420' },
            }[entry.status.type];
            const impactLabel = { high: '🔴 High impact', medium: '🟡 Medium impact', low: '🟢 Low impact' }[entry.status.impact];

            return (
              <div key={entry.championId + entry.position} style={{
                display: 'flex', alignItems: 'center', gap: 14,
                background: statusStyles.bg, border: `2px solid ${statusStyles.border}`,
                borderRadius: 16, padding: '12px 16px',
              }}>
                <div style={{ position: 'relative', flexShrink: 0 }}>
                  <window.ChampionIcon championId={entry.championId} size={56} noAnim />
                  <PatchBadge championId={entry.championId} size="dot" />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                    <span className="fredoka" style={{ fontSize: 16, color: 'var(--text-primary)' }}>{cd?.name || entry.championId}</span>
                    <PatchBadge championId={entry.championId} size="full" />
                    <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)' }}>{impactLabel}</span>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-primary)' }}>
                    {entry.status.summary}
                  </div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)', marginTop: 2 }}>
                    In {POSITION_EMOJIS[entry.position]} {entry.position} pool · {cd?.tags?.join(' · ')}
                  </div>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  {entry.status.type === 'buff' && entry.status.impact === 'high' && (
                    <div style={{ fontSize: 12, fontWeight: 800, color: '#2d6b47' }}>Prioritize! 🌟</div>
                  )}
                  {entry.status.type === 'nerf' && entry.status.impact === 'high' && (
                    <div style={{ fontSize: 12, fontWeight: 800, color: '#8b3a3a' }}>Consider alternatives 🔄</div>
                  )}
                  <window.StarRating value={entry.comfort} size={14} />
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { MetaAlerts, PatchBadge, getChampPatchStatus });
