
// ChampsToLearn.jsx — Feature 13: Champs to Learn tracker
const { useState, useMemo } = React;
const { useApp } = window;

const PRACTICE_STAGES = [
  { id: 'wishlist',   label: 'Just Started 🌱',  color: '#B8E0C0', border: '#7CBF8E', desc: 'Want to learn someday' },
  { id: 'studying',   label: 'Practicing 📚',     color: '#F7DFA0', border: '#c8ae65', desc: 'Watching guides / theory' },
  { id: 'practicing', label: 'Comfortable 🎮',    color: '#C5B4E3', border: '#9e87cc', desc: 'Playing in normals' },
  { id: 'ready',     label: 'Clash Ready ✅',    color: '#AED6F1', border: '#5b9abf', desc: 'Confident to pick' },
];

const PRIORITY_LABELS = { 1: 'Low', 2: 'Medium', 3: 'High' };
const PRIORITY_COLORS = { 1: '#C4845A40', 2: '#F7DFA0', 3: '#F2A7C3' };

function ChampsToLearn() {
  const { players, champions, championsLoading, POSITIONS, POSITION_EMOJIS, POSITION_COLORS, activePlayerId } = useApp();

  const [entries, setEntries] = useState(() => {
    try { return JSON.parse(localStorage.getItem('cozydraft-learn') || '[]'); } catch { return []; }
  });
  // activePlayer is always driven by the global FriendBar player switcher
  const activePlayer = activePlayerId ?? 0;
  const [activeStage, setActiveStage] = useState('all');
  const [search, setSearch] = useState('');
  const [addingFor, setAddingFor] = useState(null); // { playerId, stage }
  const [pickSearch, setPickSearch] = useState('');

  const saveEntries = (updated) => {
    setEntries(updated);
    try { localStorage.setItem('cozydraft-learn', JSON.stringify(updated)); } catch {}
  };

  const addEntry = (champId, stage, position) => {
    if (entries.find(e => e.champId === champId && e.playerId === activePlayer)) return;
    saveEntries([...entries, {
      id: Date.now(),
      champId, stage, position,
      playerId: activePlayer,
      priority: 2,
      notes: '',
      practiceCount: 0,
      addedDate: new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
    }]);
    setAddingFor(null);
    setPickSearch('');
  };

  const updateEntry = (id, updates) => {
    saveEntries(entries.map(e => e.id === id ? { ...e, ...updates } : e));
  };

  const removeEntry = (id) => saveEntries(entries.filter(e => e.id !== id));

  const incrementPractice = (id) => {
    saveEntries(entries.map(e => e.id === id ? { ...e, practiceCount: (e.practiceCount || 0) + 1 } : e));
  };

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

  const playerEntries = useMemo(() => {
    return entries.filter(e =>
      e.playerId === activePlayer &&
      (activeStage === 'all' || e.stage === activeStage) &&
      (!search || (window.matchesChampionSearch ? window.matchesChampionSearch(champions[e.champId] || { id: e.champId }, search) : (champions[e.champId]?.name || e.champId).toLowerCase().includes(search.toLowerCase())))
    );
  }, [entries, activePlayer, activeStage, search, champions]);

  const stageCount = (stage) => entries.filter(e => e.playerId === activePlayer && e.stage === stage).length;
  const totalForPlayer = entries.filter(e => e.playerId === activePlayer).length;

  const availableChamps = useMemo(() => {
    const used = new Set(entries.filter(e => e.playerId === activePlayer).map(e => e.champId));
    // Champion tag → lane role mapping (lenient — most champs can flex)
    const roleTagMap = {
      TOP:     ['Fighter', 'Tank'],
      JUNGLE:  ['Fighter', 'Tank', 'Assassin'],
      MID:     ['Mage', 'Assassin', 'Fighter'],
      ADC:     ['Marksman'],
      SUPPORT: ['Support', 'Tank', 'Mage'],
    };
    const allowedTags = roleTagMap[player.position] || [];
    return Object.values(champions)
      .filter(c => !used.has(c.id))
      .filter(c => !allowedTags.length || c.tags?.some(t => allowedTags.includes(t)))
      .filter(c => (window.matchesChampionSearch ? window.matchesChampionSearch(c, pickSearch) : (!pickSearch || c.name.toLowerCase().includes(pickSearch.toLowerCase()))))
      .sort((a, b) => a.name.localeCompare(b.name));
  }, [champions, entries, activePlayer, pickSearch, player.position]);

  if (championsLoading) return <window.LoadingSpinner />;

  return (
    <div style={{ padding: 20 }}>
      <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 28, marginBottom: 4 }}>
        Champs to Learn 🎓
      </h1>
      <p style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 14, margin: '0 0 20px 0' }}>
        Track each player's learning journey — from just started to Clash-ready!
      </p>

      {/* Player + add header */}
      <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 16, flexWrap: 'wrap' }}>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          background: POSITION_COLORS[player.position],
          border: '2px solid var(--border-default)',
          borderRadius: 12, padding: '5px 14px',
          fontSize: 13, fontWeight: 800, color: 'var(--text-on-light)',
        }}>
          {POSITION_EMOJIS[player.position]} {player.name}
          <span style={{ fontWeight: 700, color: 'var(--text-muted)', fontSize: 11 }}>· {totalForPlayer} champ{totalForPlayer !== 1 ? 's' : ''}</span>
        </span>
        <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)' }}>
          switch players via the selector ↑
        </span>
        <div style={{ flex: 1 }}></div>
        <window.CozyButton color="sage" onClick={() => setAddingFor({ playerId: activePlayer })}>
          + Add Champion
        </window.CozyButton>
      </div>

      {/* Stage filter + search */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap', alignItems: 'center' }}>
        <button onClick={() => setActiveStage('all')} className="cozy-btn" style={{
          padding: '5px 14px', border: `2px solid ${activeStage === 'all' ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
          borderRadius: 20, fontFamily: 'Nunito', fontSize: 12, fontWeight: 800,
          background: activeStage === 'all' ? 'var(--accent-orange)' : 'var(--surface-nested)',
          color: activeStage === 'all' ? 'white' : 'var(--text-primary)', cursor: 'pointer',
        }}>All ({totalForPlayer})</button>
        {PRACTICE_STAGES.map(s => (
          <button key={s.id} onClick={() => setActiveStage(s.id)} className="cozy-btn" style={{
            padding: '5px 14px',
            border: `2px solid ${activeStage === s.id ? s.border : 'var(--border-default)'}`,
            borderRadius: 20, fontFamily: 'Nunito', fontSize: 12, fontWeight: 800,
            background: activeStage === s.id ? s.color : 'var(--surface-nested)',
            color: activeStage === s.id ? 'var(--text-on-light-pastel)' : 'var(--text-primary)', cursor: 'pointer',
          }}>{s.label} ({stageCount(s.id)})</button>
        ))}
        <input value={search} onChange={e => setSearch(e.target.value)}
          placeholder="🔍 Search champs…"
          style={{
            padding: '6px 12px', border: '2px solid var(--border-default)', borderRadius: 14,
            fontFamily: 'Nunito', fontSize: 13, fontWeight: 700, color: 'var(--text-primary)',
            background: 'var(--surface-nested)', outline: 'none', width: 160,
          }} />
      </div>

      {/* Add champion picker modal */}
      {addingFor && (
        <div style={{
          position: 'fixed', inset: 0, background: 'rgba(74, 55, 40, 0.65)', zIndex: 500,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }} onClick={() => { setAddingFor(null); setPickSearch(''); }}>
          <div onClick={e => e.stopPropagation()} className="cozy-card" style={{
            maxWidth: 'min(560px, 94vw)', width: '100%', maxHeight: '80vh', padding: 20,
            display: 'flex', flexDirection: 'column', gap: 12,
            background: 'var(--surface-modal)',
          }}>
            <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 20 }}>
              Add a Champion to Learn 🎓
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 10 }}>
              <input value={pickSearch} onChange={e => setPickSearch(e.target.value)}
                placeholder="🔍 Search champions…" autoFocus
                style={{
                  padding: '8px 12px', border: '2px solid var(--border-default)', borderRadius: 12,
                  fontFamily: 'Nunito', fontSize: 14, fontWeight: 700, color: 'var(--text-primary)',
                  background: 'var(--surface-nested)', outline: 'none',
                }} />
            </div>
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(72px, 1fr))',
              gap: 8, overflowY: 'auto', maxHeight: '45vh',
            }}>
              {availableChamps.map(champ => (
                <div key={champ.id} className="champion-sticker"
                  onClick={() => addEntry(champ.id, 'wishlist', player.position)}
                  style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, cursor: 'pointer' }}>
                  <window.ChampionIcon championId={champ.id} size={56} noAnim />
                  <span style={{ fontSize: 9, fontWeight: 700, color: 'var(--text-primary)', textAlign: 'center', maxWidth: 68, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {champ.name}
                  </span>
                </div>
              ))}
            </div>
            <window.CozyButton color="cream" onClick={() => { setAddingFor(null); setPickSearch(''); }}>
              Cancel
            </window.CozyButton>
          </div>
        </div>
      )}

      {/* Entries grid */}
      {playerEntries.length === 0 ? (
        <div className="cozy-card" style={{ padding: 60, textAlign: 'center', background: 'var(--surface-card)' }}>
          <div style={{ fontSize: 52, marginBottom: 12 }}>🌱</div>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 22, marginBottom: 8 }}>
            {totalForPlayer === 0 ? `Nothing on ${player.name}'s learning list!` : 'No champs in this stage'}
          </div>
          {totalForPlayer === 0 && (
            <>
              <div style={{ color: 'var(--text-muted)', fontWeight: 700, marginBottom: 20 }}>
                Add a champion to start tracking your learning journey 🎓
              </div>
              <window.CozyButton color="sage" onClick={() => setAddingFor({ playerId: activePlayer })}>
                + Add First Champion
              </window.CozyButton>
            </>
          )}
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 14 }}>
          {playerEntries.map(entry => (
            <LearnCard key={entry.id} entry={entry} champions={champions}
              onUpdate={updateEntry} onRemove={removeEntry}
              onPractice={incrementPractice} />
          ))}
        </div>
      )}
    </div>
  );
}

function LearnCard({ entry, champions, onUpdate, onRemove, onPractice }) {
  const champData = champions[entry.champId];
  const stage = PRACTICE_STAGES.find(s => s.id === entry.stage) || PRACTICE_STAGES[0];
  const [editingNote, setEditingNote] = useState(false);
  const [noteDraft, setNoteDraft] = useState(entry.notes || '');

  return (
    <div className="cozy-card" style={{ padding: 16, background: 'var(--surface-card)' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 12 }}>
        <window.ChampionIcon championId={entry.champId} size={56} noAnim />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="fredoka" style={{ color: 'var(--text-primary)', fontSize: 16 }}>
            {champData?.name || entry.champId}
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-muted)', fontWeight: 700, marginBottom: 4 }}>
            {champData?.tags?.join(' · ')} · Added {entry.addedDate}
          </div>
          {/* Stage badge */}
          <span style={{
            background: stage.color + '80', border: `1.5px solid ${stage.border}`,
            borderRadius: 10, fontSize: 11, fontWeight: 800, padding: '2px 8px',
            color: 'var(--text-on-light-pastel)', fontFamily: 'Nunito',
          }}>{stage.label}</span>
        </div>
        <button onClick={() => onRemove(entry.id)} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontSize: 16, color: 'var(--text-muted)', flexShrink: 0,
        }} title="Remove">✕</button>
      </div>

      {/* Stage selector */}
      <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginBottom: 10 }}>
        {PRACTICE_STAGES.map(s => (
          <button key={s.id} onClick={() => onUpdate(entry.id, { stage: s.id })} className="cozy-btn" style={{
            padding: '2px 8px', border: `1.5px solid ${entry.stage === s.id ? s.border : 'var(--border-default)'}`,
            borderRadius: 10, fontSize: 10, fontWeight: 800,
            background: entry.stage === s.id ? s.color : 'transparent',
            color: entry.stage === s.id ? 'var(--text-on-light-pastel)' : 'var(--text-primary)', cursor: 'pointer', fontFamily: 'Nunito',
          }}>{s.label}</button>
        ))}
      </div>

      {/* Priority */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-muted)' }}>Priority:</span>
        {[1, 2, 3].map(p => (
          <button key={p} onClick={() => onUpdate(entry.id, { priority: p })} className="cozy-btn" style={{
            padding: '2px 10px', border: `1.5px solid ${entry.priority === p ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
            borderRadius: 10, fontSize: 11, fontWeight: 800,
            background: entry.priority === p ? PRIORITY_COLORS[p] : 'transparent',
            color: entry.priority === p && p !== 1 ? 'var(--text-on-light-pastel)' : 'var(--text-primary)', cursor: 'pointer', fontFamily: 'Nunito',
          }}>{PRIORITY_LABELS[p]}</button>
        ))}
      </div>

      {/* Practice counter */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-muted)' }}>Practice games:</span>
        <span style={{ fontSize: 18, fontWeight: 800, color: 'var(--text-primary)' }}>{entry.practiceCount || 0}</span>
        <button onClick={() => onPractice(entry.id)} className="cozy-btn" style={{
          padding: '2px 10px', background: '#B8E0C0', border: '1.5px solid #7CBF8E',
          borderRadius: 10, fontSize: 11, fontWeight: 800, color: '#2d6b47',
          cursor: 'pointer', fontFamily: 'Nunito',
        }}>+ Session</button>
        {/* Practice stars */}
        <div style={{ display: 'flex', gap: 2, marginLeft: 4 }}>
          {[1,2,3,4,5].map(s => <span key={s} style={{ fontSize: 12, color: (entry.practiceCount || 0) >= s * 3 ? '#F7DFA0' : 'var(--border-default)' }}>★</span>)}
        </div>
      </div>

      {/* Notes */}
      {editingNote ? (
        <div>
          <textarea
            value={noteDraft}
            onChange={e => setNoteDraft(e.target.value)}
            placeholder="Add learning notes, tips, combos to practice…"
            rows={3}
            style={{
              width: '100%', border: '2px solid var(--border-default)', borderRadius: 10,
              padding: '6px 10px', fontFamily: 'Nunito', fontSize: 12, fontWeight: 600,
              background: 'var(--surface-nested)', color: 'var(--text-primary)', outline: 'none', resize: 'none',
              boxSizing: 'border-box', lineHeight: 1.5,
            }}
          />
          <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
            <window.CozyButton small color="sage" onClick={() => { onUpdate(entry.id, { notes: noteDraft }); setEditingNote(false); }}>Save</window.CozyButton>
            <window.CozyButton small color="cream" onClick={() => setEditingNote(false)}>Cancel</window.CozyButton>
          </div>
        </div>
      ) : (
        <div onClick={() => { setEditingNote(true); setNoteDraft(entry.notes || ''); }}
          style={{
            fontSize: 12, color: entry.notes ? 'var(--text-primary)' : 'var(--text-muted)',
            fontWeight: entry.notes ? 600 : 700, cursor: 'pointer',
            background: 'var(--surface-nested)', border: '1.5px dashed var(--border-default)',
            borderRadius: 10, padding: '6px 10px', lineHeight: 1.5,
            minHeight: 32,
          }}>
          {entry.notes || 'Click to add notes, combos, tips… 📝'}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ChampsToLearn });
