
// PostGameNotes.jsx — Feature 12: Post-Game VOD Review Notes
const { useState, useCallback } = React;
const { useApp } = window;

const NOTE_PROMPTS = [
  { key: 'wentWell',   label: 'What went well? 🌟',         placeholder: 'e.g. Great dragon control, bot lane won convincingly…',       color: '#B8E0C0', border: '#7CBF8E', textColor: '#2d6b47' },
  { key: 'wentWrong',  label: 'What went wrong? 😬',         placeholder: 'e.g. Baron was given away, over-extended mid wave…',           color: '#F9D0E0', border: '#F2A7C3', textColor: '#8b3a5a' },
  { key: 'improve',    label: 'What can be improved? 🌱',    placeholder: 'e.g. Better communication on objective timers, TP usage…',     color: '#F7DFA0', border: '#c8ae65', textColor: '#6b5420' },
  { key: 'draftNotes', label: 'Draft observations 🍲',       placeholder: 'e.g. Their engage comp punished our immobile backline…',       color: '#C5B4E3', border: '#9e87cc', textColor: '#4a2d8b' },
  { key: 'nextSteps',  label: 'Action items for next time 🎯', placeholder: 'e.g. Practice dragon trades, review mid roam timings…',     color: '#AED6F1', border: '#5b9abf', textColor: '#1a4b6e' },
];

const OUTCOMES = [
  { value: 'win',  label: 'Win 🏆',  color: '#7CBF8E' },
  { value: 'loss', label: 'Loss 😔', color: '#F2A7C3' },
  { value: 'remake', label: 'Remake 🔄', color: '#F7DFA0' },
];

const EMPTY_NOTE = {
  id: null, date: '', opponent: '', outcome: 'loss',
  wentWell: '', wentWrong: '', improve: '', draftNotes: '', nextSteps: '',
  rating: 0, tags: [],
  // VOD upload (object URL kept only in session; we persist videoName + optional videoLink)
  videoName: '', videoLink: '',
  // Team composition picks for both sides of the draft
  teamComp:  { TOP: null, JUNGLE: null, MID: null, ADC: null, SUPPORT: null },
  enemyComp: { TOP: null, JUNGLE: null, MID: null, ADC: null, SUPPORT: null },
};

const AUTO_TAGS = [
  'Dragon control 🐉', 'Baron 🐍', 'Vision 👁️', 'Teamfights ⚔️', 'Rotations 🗺️',
  'Draft issue 🍲', 'Communication 💬', 'Mechanics 🎮', 'Macro 📍', 'Tilted 😤',
];

function PostGameNotes() {
  const { showToast, champions } = useApp();
  const POSITIONS = window.POSITIONS;
  const POSITION_LABELS = window.POSITION_LABELS;
  const POSITION_COLORS = window.POSITION_COLORS;

  // Session-only object URLs keyed by note id — videos themselves aren't persisted
  // across reloads (localStorage can't hold them), but the filename + an optional
  // external link survive in the saved note.
  const [videoUrls, setVideoUrls] = useState({});

  const [notes, setNotes] = useState(() => {
    try { return JSON.parse(localStorage.getItem('cozydraft-postgame') || '[]'); } catch { return []; }
  });
  const [editNote, setEditNote] = useState(null);
  const [viewNote, setViewNote] = useState(null);
  const [search, setSearch] = useState('');

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

  const handleNew = () => {
    setEditNote({
      ...EMPTY_NOTE,
      id: Date.now(),
      date: new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }),
      tags: [],
    });
    setViewNote(null);
  };

  const handleSave = useCallback(() => {
    if (!editNote) return;
    const updated = notes.find(n => n.id === editNote.id)
      ? notes.map(n => n.id === editNote.id ? editNote : n)
      : [editNote, ...notes];
    setNotes(updated);
    saveToStorage(updated);
    showToast('Notes saved! 📝✨');
    setEditNote(null);
  }, [editNote, notes, showToast]);

  const handleDelete = useCallback((id) => {
    const updated = notes.filter(n => n.id !== id);
    setNotes(updated);
    saveToStorage(updated);
    showToast('Note deleted 👋');
    if (viewNote?.id === id) setViewNote(null);
  }, [notes, viewNote, showToast]);

  const toggleTag = (tag) => {
    if (!editNote) return;
    const tags = editNote.tags.includes(tag)
      ? editNote.tags.filter(t => t !== tag)
      : [...editNote.tags, tag];
    setEditNote({ ...editNote, tags });
  };

  // -------- VOD upload --------
  const handleVideoUpload = (e) => {
    const file = e.target.files?.[0];
    if (!file || !editNote) return;
    // Revoke any previous URL for this note
    if (videoUrls[editNote.id]) URL.revokeObjectURL(videoUrls[editNote.id]);
    const url = URL.createObjectURL(file);
    setVideoUrls(prev => ({ ...prev, [editNote.id]: url }));
    setEditNote({ ...editNote, videoName: file.name });
    showToast(`📹 ${file.name} loaded for this session`);
  };

  const clearVideo = () => {
    if (!editNote) return;
    if (videoUrls[editNote.id]) {
      URL.revokeObjectURL(videoUrls[editNote.id]);
      setVideoUrls(prev => { const n = { ...prev }; delete n[editNote.id]; return n; });
    }
    setEditNote({ ...editNote, videoName: '', videoLink: '' });
  };

  // -------- Team comp picker --------
  const setCompPick = (side, pos, championId) => {
    if (!editNote) return;
    setEditNote({
      ...editNote,
      [side]: { ...editNote[side], [pos]: championId || null },
    });
  };

  // All champion options sorted alphabetically — small enough to inline a <select>.
  const championOptions = React.useMemo(() => {
    if (!champions) return [];
    return Object.values(champions)
      .map(c => ({ id: c.id, name: c.name }))
      .sort((a, b) => a.name.localeCompare(b.name));
  }, [champions]);

  // True if any comp slot has a champion picked.
  const hasComp = (comp) => comp && Object.values(comp).some(v => !!v);

  const filteredNotes = notes.filter(n =>
    !search || [n.opponent, n.date, n.wentWell, n.wentWrong, n.improve, ...(n.tags || [])]
      .some(v => v?.toLowerCase?.().includes(search.toLowerCase()))
  );

  // --- EDIT VIEW ---
  if (editNote) {
    return (
      <div style={{ padding: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
          <button onClick={() => setEditNote(null)} className="cozy-btn" style={{
            background: 'var(--surface-nested)', border: '2px solid var(--border-default)', borderRadius: 12,
            padding: '6px 14px', fontSize: 13, fontWeight: 800, color: 'var(--accent-orange)', cursor: 'pointer',
          }}>← Back</button>
          <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 24, margin: 0 }}>
            {notes.find(n => n.id === editNote.id) ? 'Edit Game Notes 📝' : 'New Game Review 📝'}
          </h1>
        </div>

        {/* Meta row */}
        <div className="cozy-card" style={{ padding: 16, marginBottom: 16 }}>
          <div className="responsive-lookup-grid">
            <div>
              <label style={{ fontSize: 12, fontWeight: 800, color: 'var(--text-muted)', display: 'block', marginBottom: 6 }}>DATE</label>
              <input value={editNote.date} onChange={e => setEditNote({ ...editNote, date: e.target.value })}
                style={{ width: '100%', padding: '8px 12px', border: '2px solid var(--border-default)', borderRadius: 12, fontFamily: 'Nunito', fontSize: 14, fontWeight: 700, background: 'var(--surface-nested)', color: 'var(--text-primary)', outline: 'none', boxSizing: 'border-box' }} />
            </div>
            <div>
              <label style={{ fontSize: 12, fontWeight: 800, color: 'var(--text-muted)', display: 'block', marginBottom: 6 }}>OPPONENT / MATCH</label>
              <input value={editNote.opponent} onChange={e => setEditNote({ ...editNote, opponent: e.target.value })}
                placeholder="e.g. Noxus Crew, Clash Semifinal…"
                style={{ width: '100%', padding: '8px 12px', border: '2px solid var(--border-default)', borderRadius: 12, fontFamily: 'Nunito', fontSize: 14, fontWeight: 700, background: 'var(--surface-nested)', color: 'var(--text-primary)', outline: 'none', boxSizing: 'border-box' }} />
            </div>
            <div>
              <label style={{ fontSize: 12, fontWeight: 800, color: 'var(--text-muted)', display: 'block', marginBottom: 6 }}>RESULT</label>
              <div style={{ display: 'flex', gap: 6 }}>
                {OUTCOMES.map(o => (
                  <button key={o.value} onClick={() => setEditNote({ ...editNote, outcome: o.value })}
                    className="cozy-btn"
                    style={{
                      padding: '8px 12px', border: `2px solid ${editNote.outcome === o.value ? o.color : 'var(--border-default)'}`,
                      borderRadius: 12, fontFamily: 'Nunito', fontSize: 13, fontWeight: 800,
                      background: editNote.outcome === o.value ? o.color : 'var(--surface-nested)', color: editNote.outcome === o.value ? 'var(--text-on-light-pastel)' : 'var(--text-primary)', cursor: 'pointer',
                    }}>{o.label}</button>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Performance rating */}
        <div className="cozy-card" style={{ padding: 16, marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 15 }}>Team Performance Rating:</span>
            <div style={{ display: 'flex', gap: 4 }}>
              {[1, 2, 3, 4, 5].map(s => (
                <span key={s} onClick={() => setEditNote({ ...editNote, rating: s })}
                  style={{ fontSize: 24, cursor: 'pointer', color: s <= editNote.rating ? '#F7DFA0' : 'var(--border-default)',
                    textShadow: s <= editNote.rating ? '0 0 6px rgba(196,132,90,0.6)' : 'none', transition: 'all 0.15s' }}>★</span>
              ))}
            </div>
            <span style={{ color: 'var(--text-muted)', fontSize: 13, fontWeight: 700 }}>
              {['', 'Very rough 😣', 'Struggles 😕', 'Okay 😐', 'Good 😊', 'Amazing! 🌟'][editNote.rating] || ''}
            </span>
          </div>
        </div>

        {/* ─── VOD upload ─── */}
        <div className="cozy-card" style={{ padding: 16, marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <span className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 15 }}>📹 Game Recording</span>
            <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)' }}>
              Upload a VOD or paste a Twitch / YouTube link
            </span>
          </div>

          <div className="responsive-two-column" style={{ alignItems: 'stretch' }}>
            {/* Upload column */}
            <div style={{
              background: 'var(--surface-nested)', border: '2px dashed var(--border-emphasis)', borderRadius: 14,
              padding: 14, display: 'flex', flexDirection: 'column', alignItems: 'center',
              justifyContent: 'center', gap: 8, textAlign: 'center', minHeight: 140,
            }}>
              {videoUrls[editNote.id] || editNote.videoName ? (
                <>
                  {videoUrls[editNote.id] && (
                    <video
                      src={videoUrls[editNote.id]}
                      controls
                      style={{ width: '100%', maxHeight: 180, borderRadius: 10, background: '#000' }}
                    />
                  )}
                  <div style={{ fontSize: 12, fontWeight: 800, color: 'var(--text-primary)', wordBreak: 'break-word' }}>
                    📼 {editNote.videoName}
                  </div>
                  {!videoUrls[editNote.id] && (
                    <div style={{ fontSize: 10, color: 'var(--text-muted)', fontWeight: 700 }}>
                      File reference saved — re-upload to play this session
                    </div>
                  )}
                  <div style={{ display: 'flex', gap: 6 }}>
                    <label className="cozy-btn" style={{
                      background: 'var(--accent-orange)', color: 'white', border: '2px solid var(--accent-orange)',
                      borderRadius: 12, padding: '4px 12px', fontFamily: 'Nunito',
                      fontSize: 12, fontWeight: 800, cursor: 'pointer',
                    }}>
                      Replace
                      <input type="file" accept="video/*" onChange={handleVideoUpload} style={{ display: 'none' }} />
                    </label>
                    <button onClick={clearVideo} className="cozy-btn" style={{
                      background: 'var(--surface-nested)', border: '2px solid #E8A0A0', borderRadius: 12,
                      padding: '4px 12px', fontFamily: 'Nunito', fontSize: 12, fontWeight: 800,
                      color: '#8b3a5a', cursor: 'pointer',
                    }}>Remove</button>
                  </div>
                </>
              ) : (
                <>
                  <div style={{ fontSize: 36 }}>📹</div>
                  <label className="cozy-btn" style={{
                    background: 'var(--accent-orange)', color: 'white', border: '2px solid var(--accent-orange)',
                    borderRadius: 14, padding: '8px 18px', fontFamily: 'Nunito',
                    fontSize: 13, fontWeight: 800, cursor: 'pointer', boxShadow: '0 3px 0 rgba(0,0,0,0.2)',
                  }}>
                    Upload game VOD
                    <input type="file" accept="video/*" onChange={handleVideoUpload} style={{ display: 'none' }} />
                  </label>
                  <div style={{ fontSize: 10, color: 'var(--text-muted)', fontWeight: 700 }}>
                    .mp4, .mov, .webm — kept in this session only
                  </div>
                </>
              )}
            </div>

            {/* External link column */}
            <div style={{
              background: 'var(--surface-nested)', border: '2px solid var(--border-default)', borderRadius: 14,
              padding: 14, display: 'flex', flexDirection: 'column', gap: 8,
            }}>
              <label style={{ fontSize: 12, fontWeight: 800, color: 'var(--text-muted)' }}>
                EXTERNAL LINK
              </label>
              <input
                value={editNote.videoLink}
                onChange={e => setEditNote({ ...editNote, videoLink: e.target.value })}
                placeholder="https://twitch.tv/videos/…  or  youtu.be/…"
                style={{
                  padding: '8px 12px', border: '2px solid var(--border-default)', borderRadius: 12,
                  fontFamily: 'Nunito', fontSize: 13, fontWeight: 700,
                  background: 'var(--surface-card)', color: 'var(--text-primary)', outline: 'none',
                }}
              />
              {editNote.videoLink && (
                <a href={editNote.videoLink} target="_blank" rel="noreferrer"
                  style={{
                    fontSize: 12, fontWeight: 800, color: '#7CBF8E', textDecoration: 'none',
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                  }}>
                  🔗 Open link in new tab
                </a>
              )}
              <div style={{ fontSize: 10, color: 'var(--text-muted)', fontWeight: 700, marginTop: 'auto' }}>
                A pasted link is the easiest way for the whole crew to rewatch later.
              </div>
            </div>
          </div>
        </div>

        {/* ─── Team composition ─── */}
        <div className="cozy-card" style={{ padding: 16, marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <span className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 15 }}>🏆 Team Composition</span>
            <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)' }}>
              Lock in the champs that were played
            </span>
          </div>

          <div className="responsive-two-column">
            <CompColumn
              side="teamComp"
              title="Our crew"
              accent="#7CBF8E"
              bg="#B8E0C020"
              picks={editNote.teamComp}
              setCompPick={setCompPick}
              championOptions={championOptions}
              POSITIONS={POSITIONS}
              POSITION_LABELS={POSITION_LABELS}
              POSITION_COLORS={POSITION_COLORS}
            />
            <CompColumn
              side="enemyComp"
              title="Enemy squad"
              accent="#F2A7C3"
              bg="#F9D0E020"
              picks={editNote.enemyComp}
              setCompPick={setCompPick}
              championOptions={championOptions}
              POSITIONS={POSITIONS}
              POSITION_LABELS={POSITION_LABELS}
              POSITION_COLORS={POSITION_COLORS}
            />
          </div>
        </div>

        {/* Note sections */}
        <div className="responsive-two-column" style={{ marginBottom: 16 }}>
          {NOTE_PROMPTS.map(p => (
            <div key={p.key} style={{
              background: p.color + '30', border: `2px solid ${p.border}`,
              borderRadius: 16, padding: 14,
            }}>
              <label className="fredoka" style={{ color: p.textColor, fontSize: 15, display: 'block', marginBottom: 8 }}>
                {p.label}
              </label>
              <textarea
                value={editNote[p.key]}
                onChange={e => setEditNote({ ...editNote, [p.key]: e.target.value })}
                placeholder={p.placeholder}
                rows={4}
                style={{
                  width: '100%', border: `1.5px solid ${p.border}60`, borderRadius: 10,
                  padding: '8px 10px', fontFamily: 'Nunito', fontSize: 13, fontWeight: 600,
                  background: 'var(--surface-card)', color: 'var(--text-primary)', outline: 'none', resize: 'vertical',
                  lineHeight: 1.5, boxSizing: 'border-box',
                }}
              />
            </div>
          ))}
        </div>

        {/* Focus tags */}
        <div className="cozy-card" style={{ padding: 14, marginBottom: 16 }}>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 15, marginBottom: 10 }}>🏷️ Focus Areas</div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {AUTO_TAGS.map(tag => (
              <button key={tag} onClick={() => toggleTag(tag)} className="cozy-btn" style={{
                padding: '4px 12px', border: `2px solid ${editNote.tags.includes(tag) ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
                borderRadius: 20, fontFamily: 'Nunito', fontSize: 12, fontWeight: 800,
                background: editNote.tags.includes(tag) ? 'var(--accent-orange)' : 'var(--surface-nested)',
                color: editNote.tags.includes(tag) ? 'var(--surface-page)' : 'var(--text-primary)', cursor: 'pointer',
              }}>{tag}</button>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', gap: 10 }}>
          <window.CozyButton color="sage" onClick={handleSave}>Save Notes 💾</window.CozyButton>
          <window.CozyButton color="cream" onClick={() => setEditNote(null)}>Cancel</window.CozyButton>
        </div>
      </div>
    );
  }

  // --- VIEW NOTE ---
  if (viewNote) {
    const note = notes.find(n => n.id === viewNote.id) || viewNote;
    const outcome = OUTCOMES.find(o => o.value === note.outcome);
    return (
      <div style={{ padding: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
          <button onClick={() => setViewNote(null)} className="cozy-btn" style={{
            background: 'var(--surface-nested)', border: '2px solid var(--border-default)', borderRadius: 12,
            padding: '6px 14px', fontSize: 13, fontWeight: 800, color: 'var(--accent-orange)', cursor: 'pointer',
          }}>← Back</button>
          <div style={{ flex: 1 }}>
            <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 24, margin: 0 }}>
              {note.opponent || 'Game Review'} — {note.date}
            </h1>
          </div>
          <span style={{ background: outcome?.color, border: '1.5px solid var(--border-default)', borderRadius: 12, padding: '4px 14px', fontSize: 13, fontWeight: 800, color: 'var(--text-on-light-pastel)', fontFamily: 'Nunito' }}>
            {outcome?.label}
          </span>
          <window.CozyButton small color="terracotta" onClick={() => setEditNote(note)}>Edit ✏️</window.CozyButton>
        </div>
        {note.rating > 0 && (
          <div style={{ marginBottom: 16 }}>
            {[1,2,3,4,5].map(s => <span key={s} style={{ fontSize: 20, color: s <= note.rating ? '#F7DFA0' : 'var(--border-default)' }}>★</span>)}
          </div>
        )}
        {note.tags?.length > 0 && (
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 16 }}>
            {note.tags.map(t => <window.Tag key={t} color="green">{t}</window.Tag>)}
          </div>
        )}

        {/* VOD playback / link */}
        {(videoUrls[note.id] || note.videoName || note.videoLink) && (
          <div className="cozy-card" style={{ padding: 14, marginBottom: 16 }}>
            <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 15, marginBottom: 8 }}>📹 Game Recording</div>
            {videoUrls[note.id] && (
              <video src={videoUrls[note.id]} controls
                style={{ width: '100%', maxHeight: 380, borderRadius: 12, background: '#000', marginBottom: 8 }} />
            )}
            <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', fontSize: 12, fontWeight: 700, color: 'var(--text-primary)' }}>
              {note.videoName && <span>📼 {note.videoName}{!videoUrls[note.id] && <span style={{ color: 'var(--text-muted)' }}> · re-upload to play</span>}</span>}
              {note.videoLink && (
                <a href={note.videoLink} target="_blank" rel="noreferrer"
                  style={{ color: '#7CBF8E', textDecoration: 'none' }}>🔗 {note.videoLink}</a>
              )}
            </div>
          </div>
        )}

        {/* Team compositions */}
        {(hasComp(note.teamComp) || hasComp(note.enemyComp)) && (
          <div className="responsive-two-column" style={{ marginBottom: 16 }}>
            {hasComp(note.teamComp)  && <CompDisplay title="Our crew"     accent="#7CBF8E" bg="#B8E0C020" picks={note.teamComp}  />}
            {hasComp(note.enemyComp) && <CompDisplay title="Enemy squad"  accent="#F2A7C3" bg="#F9D0E020" picks={note.enemyComp} />}
          </div>
        )}
        <div className="responsive-two-column">
          {NOTE_PROMPTS.map(p => note[p.key] ? (
            <div key={p.key} style={{ background: p.color + '30', border: `2px solid ${p.border}`, borderRadius: 16, padding: 16 }}>
              <div className="fredoka" style={{ color: p.textColor, fontSize: 15, marginBottom: 8 }}>{p.label}</div>
              <div style={{ fontSize: 14, color: 'var(--text-primary)', lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>{note[p.key]}</div>
            </div>
          ) : null)}
        </div>
      </div>
    );
  }

  // --- LIST VIEW ---
  return (
    <div style={{ padding: 20 }}>
      <style>{`
        @media (max-width: 600px) {
          .vod-header-row {
            flex-direction: column !important;
            align-items: flex-start !important;
            gap: 16px !important;
            margin-bottom: 16px !important;
          }
        }
      `}</style>
      <div className="vod-header-row" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
        <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 28, margin: 0 }}>
          VOD Review Notes 📺
        </h1>
        <window.CozyButton color="sage" onClick={handleNew}>+ New Review</window.CozyButton>
      </div>
      <p style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 14, margin: '0 0 20px 0' }}>
        {notes.length} game{notes.length !== 1 ? 's' : ''} reviewed — keep improving! 🌱
      </p>

      {notes.length > 0 && (
        <div style={{ marginBottom: 16 }}>
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="🔍 Search notes…"
            style={{
              padding: '8px 14px', border: '2px solid var(--border-default)', borderRadius: 14,
              fontFamily: 'Nunito', fontSize: 14, fontWeight: 700, color: 'var(--text-primary)',
              background: 'var(--surface-nested)', outline: 'none', width: 280,
            }} />
        </div>
      )}

      {filteredNotes.length === 0 ? (
        <div className="cozy-card" style={{ padding: 60, textAlign: 'center' }}>
          <div style={{ fontSize: 52, marginBottom: 12 }}>📺</div>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 24, marginBottom: 8 }}>
            {notes.length === 0 ? 'No reviews yet!' : 'No matches found'}
          </div>
          {notes.length === 0 && (
            <>
              <div style={{ color: 'var(--text-muted)', fontWeight: 700, marginBottom: 20 }}>
                Watch a VOD and write your first review to start improving as a team!
              </div>
              <window.CozyButton color="sage" onClick={handleNew}>Write First Review 📝</window.CozyButton>
            </>
          )}
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16 }}>
          {filteredNotes.map(note => {
            const outcome = OUTCOMES.find(o => o.value === note.outcome);
            const hasContent = NOTE_PROMPTS.some(p => note[p.key]);
            return (
              <div key={note.id} className="cozy-card" style={{ padding: 18, cursor: 'pointer' }}
                onClick={() => setViewNote(note)}>
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 10 }}>
                  <div>
                    <div className="fredoka" style={{ color: 'var(--text-primary)', fontSize: 17 }}>
                      {note.opponent || 'Game Review'}
                    </div>
                    <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-muted)' }}>{note.date}</div>
                  </div>
                  <span style={{ background: outcome?.color + '60', border: `1.5px solid ${outcome?.color}`, borderRadius: 10, padding: '3px 10px', fontSize: 12, fontWeight: 800, color: 'var(--text-on-light-pastel)', fontFamily: 'Nunito', flexShrink: 0 }}>
                    {outcome?.label}
                  </span>
                </div>
                {note.rating > 0 && (
                  <div style={{ marginBottom: 8 }}>
                    {[1,2,3,4,5].map(s => <span key={s} style={{ fontSize: 14, color: s <= note.rating ? '#F7DFA0' : 'var(--border-default)' }}>★</span>)}
                  </div>
                )}

                {/* Team comp strip — our crew only */}
                {hasComp(note.teamComp) && (
                  <div style={{
                    display: 'flex', alignItems: 'center', gap: 6,
                    background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
                    borderRadius: 12, padding: '6px 8px', marginBottom: 10,
                  }}>
                    <CompStrip picks={note.teamComp} accent="#7CBF8E" />
                  </div>
                )}

                {note.wentWell && (
                  <div style={{ fontSize: 12, color: '#2d6b47', fontWeight: 700, marginBottom: 4, background: '#B8E0C030', borderRadius: 8, padding: '4px 8px' }}>
                    🌟 {note.wentWell.slice(0, 80)}{note.wentWell.length > 80 ? '…' : ''}
                  </div>
                )}
                {note.wentWrong && (
                  <div style={{ fontSize: 12, color: '#8b3a5a', fontWeight: 700, marginBottom: 8, background: '#F9D0E030', borderRadius: 8, padding: '4px 8px' }}>
                    😬 {note.wentWrong.slice(0, 80)}{note.wentWrong.length > 80 ? '…' : ''}
                  </div>
                )}
                {note.tags?.length > 0 && (
                  <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginBottom: 10 }}>
                    {note.tags.slice(0, 3).map(t => <window.Tag key={t} color="green">{t}</window.Tag>)}
                    {note.tags.length > 3 && <span style={{ fontSize: 11, color: 'var(--text-muted)', fontWeight: 700, alignSelf: 'center' }}>+{note.tags.length - 3}</span>}
                  </div>
                )}
                <div style={{ display: 'flex', gap: 8 }}>
                  <window.CozyButton small color="terracotta" onClick={e => { e.stopPropagation(); setEditNote(note); }}>✏️ Edit</window.CozyButton>
                  <window.CozyButton small color="red" onClick={e => { e.stopPropagation(); handleDelete(note.id); }}>🗑️ Delete</window.CozyButton>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PostGameNotes });

// -----------------------------------------------------------------------------
// CompColumn — compact 5-lane composition editor (our side OR enemy side)
// -----------------------------------------------------------------------------
function CompColumn({ side, title, accent, bg, picks, setCompPick, championOptions, POSITIONS, POSITION_LABELS, POSITION_COLORS }) {
  return (
    <div style={{
      background: bg, border: `2px solid ${accent}`, borderRadius: 14, padding: 12,
    }}>
      <div className="fredoka" style={{ color: accent, fontSize: 14, marginBottom: 8 }}>
        {title}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {POSITIONS.map(pos => {
          const picked = picks[pos];
          return (
            <div key={pos} style={{
              display: 'flex', alignItems: 'center', gap: 8,
              background: 'var(--surface-card)', border: '1.5px solid var(--border-default)',
              borderRadius: 10, padding: '4px 8px',
            }}>
              <window.HexFrame size={28} color={POSITION_COLORS[pos]} borderColor="var(--border-emphasis)" borderWidth={2}>
                <window.RoleIcon pos={pos} size={16} />
              </window.HexFrame>
              <span style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-muted)', width: 40 }}>
                {POSITION_LABELS[pos]}
              </span>
              {picked && <window.ChampionIcon championId={picked} size={28} noAnim />}
              <select
                value={picked || ''}
                onChange={e => setCompPick(side, pos, e.target.value || null)}
                style={{
                  flex: 1, padding: '5px 8px',
                  border: '1.5px solid var(--border-default)', borderRadius: 8,
                  background: 'var(--surface-nested)', fontFamily: 'Nunito', fontSize: 12, fontWeight: 700,
                  color: 'var(--text-primary)', outline: 'none', cursor: 'pointer',
                }}
              >
                <option value="">Pick champion…</option>
                {championOptions.map(c => (
                  <option key={c.id} value={c.id}>{c.name}</option>
                ))}
              </select>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// -----------------------------------------------------------------------------
// CompDisplay — read-only render of a saved comp (used in view-note)
// -----------------------------------------------------------------------------
function CompDisplay({ title, accent, bg, picks }) {
  const POSITIONS = window.POSITIONS;
  const POSITION_LABELS = window.POSITION_LABELS;
  const POSITION_COLORS = window.POSITION_COLORS;
  const champions = window.useApp().champions;
  return (
    <div style={{
      background: bg, border: `2px solid ${accent}`, borderRadius: 14, padding: 14,
    }}>
      <div className="fredoka" style={{ color: accent, fontSize: 14, marginBottom: 8 }}>{title}</div>
      <div style={{ display: 'flex', gap: 8, justifyContent: 'space-between' }}>
        {POSITIONS.map(pos => (
          <div key={pos} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, flex: 1 }}>
            <window.HexFrame size={32} color={POSITION_COLORS[pos]} borderColor="var(--border-emphasis)" borderWidth={2}>
              <window.RoleIcon pos={pos} size={18} />
            </window.HexFrame>
            <window.ChampionIcon championId={picks?.[pos]} size={40} noAnim />
            <div style={{ fontSize: 10, fontWeight: 800, color: 'var(--text-muted)' }}>
              {picks?.[pos] ? (champions?.[picks[pos]]?.name || picks[pos]) : '—'}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { CompColumn, CompDisplay });

// -----------------------------------------------------------------------------
// CompStrip — tight 5-champ row shown on saved-review cards in the list view.
// Empty slots fall back to a dashed placeholder so the team shape is still
// readable even when only some picks are filled in.
// -----------------------------------------------------------------------------
function CompStrip({ picks, accent = 'var(--accent-orange)' }) {
  const POSITIONS = window.POSITIONS;
  const POSITION_COLORS = window.POSITION_COLORS;
  return (
    <div style={{ display: 'flex', gap: 3, alignItems: 'center', flex: 1, minWidth: 0 }}>
      {POSITIONS.map(pos => {
        const id = picks?.[pos];
        return (
          <div key={pos} style={{
            position: 'relative', flex: '0 0 auto',
          }} title={pos}>
            {id ? (
              <div style={{
                position: 'relative',
                border: `1.5px solid ${accent}`,
                borderRadius: 8,
                padding: 1, background: 'var(--surface-card)',
              }}>
                <window.ChampionIcon championId={id} size={26} noAnim style={{ borderWidth: 0 }} />
                {/* Tiny role chip on the corner */}
                <div style={{
                  position: 'absolute', bottom: -3, right: -3,
                  width: 12, height: 12, borderRadius: '50%',
                  background: POSITION_COLORS[pos],
                  border: '1.5px solid var(--surface-card)',
                }} />
              </div>
            ) : (
              <div style={{
                width: 28, height: 28, borderRadius: 8,
                border: `1.5px dashed ${accent}60`,
                background: POSITION_COLORS[pos] + '30',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <window.RoleIcon pos={pos} size={14} />
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { CompStrip });
