// Matchday Summary — view & edit match lineups, minutes, goals

function MatchForm({ initial, onSave, onCancel }) {
  const [opponent,    setOpponent]    = useState(initial?.opponent    || '');
  const [matchDate,   setMatchDate]   = useState(initial?.match_date  || '');
  const [competition, setCompetition] = useState(initial?.competition || '');
  const [homeScore,   setHomeScore]   = useState(initial?.home_score  ?? '');
  const [awayScore,   setAwayScore]   = useState(initial?.away_score  ?? '');
  const [teamLevel,   setTeamLevel]   = useState(initial?.team_level  || 'Senior');
  const [notes,       setNotes]       = useState(initial?.notes       || '');

  const submit = () => {
    if (!opponent.trim()) return;
    onSave({ opponent, matchDate, competition, homeScore: +homeScore || 0, awayScore: +awayScore || 0, teamLevel, notes });
  };

  return (
    <div className="camp-form">
      <input className="camp-input" placeholder="คู่แข่ง (เช่น Vietnam)…" value={opponent}
        onChange={e => setOpponent(e.target.value)}
        onKeyDown={e => e.key === 'Enter' && submit()} autoFocus/>
      <div className="camp-daterange-box">
        <div className="camp-dr-half">
          <span className="camp-dr-label">DATE</span>
          <input type="date" className="camp-dr-input" value={matchDate}
            onChange={e => setMatchDate(e.target.value)}/>
        </div>
        <div className="camp-dr-divider">vs</div>
        <div className="camp-dr-half" style={{flexDirection:'row', alignItems:'center', gap:4}}>
          <input type="number" className="camp-dr-input" placeholder="0" min="0" max="99" style={{width:36}}
            value={homeScore} onChange={e => setHomeScore(e.target.value)}/>
          <span className="camp-dr-label" style={{margin:'0 2px'}}>:</span>
          <input type="number" className="camp-dr-input" placeholder="0" min="0" max="99" style={{width:36}}
            value={awayScore} onChange={e => setAwayScore(e.target.value)}/>
        </div>
      </div>
      <input className="camp-input" placeholder="การแข่งขัน (AFF / AFC / Friendly)…" value={competition}
        onChange={e => setCompetition(e.target.value)}/>
      <div style={{display:'flex', gap:6}}>
        <select className="camp-input" style={{flex:1}} value={teamLevel} onChange={e => setTeamLevel(e.target.value)}>
          <option value="Senior">🏆 Senior</option>
          <option value="U23">U23</option>
          <option value="U20">U20</option>
          <option value="U17">U17</option>
        </select>
      </div>
      <input className="camp-input" placeholder="หมายเหตุ…" value={notes}
        onChange={e => setNotes(e.target.value)}/>
      <div style={{display:'flex', gap:6}}>
        <button className="btn-primary sm" style={{flex:1}} onClick={submit}>
          {initial ? 'Save changes' : 'Add match'}
        </button>
        <button className="btn-ghost sm" onClick={onCancel}>Cancel</button>
      </div>
    </div>
  );
}

function LineupEditor({ match, players, onSave }) {
  // local copy of lineup as map: playerId → {minutesPlayed, goals, assists, yellowCards, redCard}
  const [lineup, setLineup] = useState(() => {
    const m = new Map();
    for (const e of (match.lineup || [])) m.set(e.playerId, { ...e });
    return m;
  });
  const [filterPos, setFilterPos] = useState('All');
  const [search, setSearch] = useState('');
  const [dirty, setDirty] = useState(false);

  const setField = (playerId, field, val) => {
    setLineup(prev => {
      const m = new Map(prev);
      const entry = m.get(playerId) || { playerId, minutesPlayed:0, goals:0, assists:0, yellowCards:0, redCard:false };
      m.set(playerId, { ...entry, [field]: val });
      return m;
    });
    setDirty(true);
  };

  const save = () => {
    const arr = [...lineup.values()].filter(e => e.minutesPlayed > 0 || e.goals > 0);
    onSave(arr);
    setDirty(false);
  };

  const POS_FILTERS = ['All','GK','DEF','MID','FWD'];
  const visible = players.filter(p => {
    if (filterPos === 'GK'  && p.pos !== 'GK') return false;
    if (filterPos === 'DEF' && posGroup(p.pos) !== 'Defender')   return false;
    if (filterPos === 'MID' && posGroup(p.pos) !== 'Midfielder') return false;
    if (filterPos === 'FWD' && posGroup(p.pos) !== 'Forward')    return false;
    if (search) {
      const q = search.toLowerCase();
      if (![p.name, p.nick||'', p.thaiName||''].join(' ').toLowerCase().includes(q)) return false;
    }
    return true;
  });

  return (
    <div className="md-lineup">
      <div className="callup-cl-hd">
        <input className="callup-search" placeholder="Search player…" value={search}
          onChange={e => setSearch(e.target.value)}/>
        <div className="chips sm">
          {POS_FILTERS.map(f => (
            <button key={f} className={`chip ${filterPos===f?'on':''}`} onClick={() => setFilterPos(f)}>{f}</button>
          ))}
        </div>
        {dirty && (
          <button className="btn-primary sm" onClick={save}>💾 Save lineup</button>
        )}
      </div>
      <div className="md-lineup-table-wrap">
        <table className="md-lineup-table">
          <thead>
            <tr>
              <th></th>
              <th>Player</th>
              <th className="num">MIN</th>
              <th className="num">⚽ G</th>
              <th className="num">🅰 A</th>
              <th className="num">🟨</th>
              <th className="num">🟥</th>
            </tr>
          </thead>
          <tbody>
            {visible.map(p => {
              const e = lineup.get(p.id) || {};
              const played = (e.minutesPlayed || 0) > 0;
              return (
                <tr key={p.id} className={`md-lineup-row ${played?'played':''}`}>
                  <td><PosBadge pos={p.pos}/></td>
                  <td className="md-pname">
                    <PlayerPhoto playerId={p.id} name={p.name} size={28}/>
                    <span>{p.name}</span>
                    {p.nick && <span className="nm-nick">({p.nick})</span>}
                  </td>
                  <td>
                    <input type="number" className="md-stat-inp" min="0" max="120" placeholder="–"
                      value={e.minutesPlayed || ''}
                      onChange={ev => setField(p.id,'minutesPlayed', +ev.target.value||0)}/>
                  </td>
                  <td>
                    <input type="number" className="md-stat-inp" min="0" max="20" placeholder="–"
                      value={e.goals || ''}
                      onChange={ev => setField(p.id,'goals', +ev.target.value||0)}/>
                  </td>
                  <td>
                    <input type="number" className="md-stat-inp" min="0" max="20" placeholder="–"
                      value={e.assists || ''}
                      onChange={ev => setField(p.id,'assists', +ev.target.value||0)}/>
                  </td>
                  <td>
                    <input type="number" className="md-stat-inp" min="0" max="2" placeholder="–"
                      value={e.yellowCards || ''}
                      onChange={ev => setField(p.id,'yellowCards', +ev.target.value||0)}/>
                  </td>
                  <td>
                    <input type="checkbox" className="md-rc-chk"
                      checked={!!e.redCard}
                      onChange={ev => setField(p.id,'redCard', ev.target.checked)}/>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

const LEVEL_FILTERS = ['All', 'Senior', 'U23', 'U20', 'U17'];
const LEVEL_COLORS  = { Senior:'var(--accent-blue)', U23:'#7c4dbd', U20:'#c07a18', U17:'#1a8a4a' };

function LevelBadge({ level }) {
  if (!level || level === 'Senior') return null;
  return <span className="md-level-badge" style={{background: LEVEL_COLORS[level] || 'var(--fg-mute)'}}>{level}</span>;
}

function MatchdayPanel({ players, onClose, t }) {
  const [matches,     setMatches]     = useState([]);
  const [activeId,    setActiveId]    = useState(null);
  const [loading,     setLoading]     = useState(true);
  const [creating,    setCreating]    = useState(false);
  const [editingId,   setEditingId]   = useState(null);
  const [savedAt,     setSavedAt]     = useState(null);
  const [levelFilter, setLevelFilter] = useState('All');

  useEffect(() => {
    fetch('/api/matches')
      .then(r => r.ok ? r.json() : { matches: [] })
      .then(d => {
        const list = d.matches || [];
        setMatches(list);
        if (list.length) setActiveId(list[0].id);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    const k = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, [onClose]);

  const activeMatch = matches.find(m => m.id === activeId) || null;

  const persist = (match) =>
    fetch(`/api/matches/${match.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        opponent: match.opponent, competition: match.competition,
        matchDate: match.match_date, homeScore: match.home_score,
        awayScore: match.away_score, teamLevel: match.team_level,
        lineup: match.lineup, notes: match.notes,
      }),
    }).then(() => setSavedAt(new Date())).catch(console.error);

  const createMatch = ({ opponent, matchDate, competition, homeScore, awayScore, teamLevel, notes }) => {
    const tl = teamLevel || 'Senior';
    fetch('/api/matches', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ opponent, matchDate, competition, homeScore, awayScore, teamLevel: tl, lineup:[], notes }),
    }).then(r => r.json()).then(({ id }) => {
      const m = { id, opponent, match_date: matchDate, competition, home_score: homeScore, away_score: awayScore, team_level: tl, lineup:[], notes };
      setMatches(curr => [...curr, m]);
      setActiveId(id);
      setCreating(false);
      setSavedAt(new Date());
    }).catch(console.error);
  };

  const saveMatchDetails = (id, vals) => {
    const updated = { ...matches.find(m => m.id === id), opponent: vals.opponent, match_date: vals.matchDate, competition: vals.competition, home_score: vals.homeScore, away_score: vals.awayScore, team_level: vals.teamLevel || 'Senior', notes: vals.notes };
    setMatches(curr => curr.map(m => m.id === id ? updated : m));
    setEditingId(null);
    persist(updated);
  };

  const saveLineup = (matchId, lineup) => {
    const updated = { ...matches.find(m => m.id === matchId), lineup };
    setMatches(curr => curr.map(m => m.id === matchId ? updated : m));
    persist(updated);
  };

  const deleteMatch = async (id, e) => {
    e.stopPropagation();
    if (!confirm('Delete this match?')) return;
    await fetch(`/api/matches/${id}`, { method: 'DELETE' }).catch(console.error);
    setMatches(curr => curr.filter(m => m.id !== id));
    if (activeId === id) setActiveId(matches.find(m => m.id !== id)?.id || null);
  };

  const fmtDate = (d) => {
    if (!d) return null;
    const dt = new Date(d + 'T00:00:00');
    return isNaN(dt) ? d : dt.toLocaleDateString('en-GB', { day:'numeric', month:'short', year:'numeric' });
  };

  const calledCount = activeMatch?.lineup?.filter(e => e.minutesPlayed > 0).length || 0;

  const visibleMatches = levelFilter === 'All'
    ? matches
    : matches.filter(m => (m.team_level || 'Senior') === levelFilter);

  return (
    <div className="callup-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="callup-panel" style={{maxWidth:1100}}>

        {/* Header */}
        <div className="callup-hd">
          <span className="callup-hd-title">📅 Match Log</span>
          {savedAt && (
            <span className="callup-saved-badge">
              ✓ Saved {savedAt.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})}
            </span>
          )}
          <button className="btn-primary callup-done-btn" onClick={onClose}>✓ Done</button>
          <button className="icon-btn close-x" onClick={onClose}>✕</button>
        </div>

        <div className="callup-body">
          {/* Sidebar — match list */}
          <aside className="callup-sidebar">
            <div className="callup-sb-hd">
              <span>Matches</span>
              <button className="btn-ghost sm" onClick={() => { setCreating(v => !v); setEditingId(null); }}>
                {creating ? '–' : '+ New'}
              </button>
            </div>

            {/* Team level filter */}
            <div className="md-level-filter">
              {LEVEL_FILTERS.map(lv => (
                <button key={lv}
                  className={`chip sm ${levelFilter === lv ? 'on' : ''}`}
                  style={levelFilter === lv && lv !== 'All' ? {background: LEVEL_COLORS[lv], borderColor: LEVEL_COLORS[lv]} : {}}
                  onClick={() => setLevelFilter(lv)}>
                  {lv}
                </button>
              ))}
            </div>

            {creating && (
              <MatchForm onSave={createMatch} onCancel={() => setCreating(false)}/>
            )}

            {loading && <div className="callup-msg">Loading…</div>}
            {!loading && visibleMatches.length === 0 && !creating && (
              <div className="callup-msg">{levelFilter === 'All' ? 'No matches yet' : `No ${levelFilter} matches`}</div>
            )}

            {visibleMatches.map(match => (
              <div key={match.id}>
                {editingId === match.id ? (
                  <div style={{borderBottom:'1px solid var(--line)'}}>
                    <MatchForm
                      initial={match}
                      onSave={vals => saveMatchDetails(match.id, vals)}
                      onCancel={() => setEditingId(null)}/>
                  </div>
                ) : (
                  <div
                    className={`camp-item ${match.id === activeId ? 'active' : ''}`}
                    onClick={() => { setActiveId(match.id); setEditingId(null); }}>
                    <div className="camp-item-body">
                      <div className="camp-item-name">
                        <LevelBadge level={match.team_level}/>
                        {match.competition && <span className="md-comp-pill">{match.competition}</span>}
                        {' '}vs {match.opponent}
                        {(match.home_score > 0 || match.away_score > 0) && (
                          <span className="md-score-badge"> {match.home_score}–{match.away_score}</span>
                        )}
                      </div>
                      <div className="camp-item-meta">
                        {fmtDate(match.match_date) && <>{fmtDate(match.match_date)} · </>}
                        <span className="mono">{match.lineup?.filter(e=>e.minutesPlayed>0).length||0}</span> players
                        {match.notes && <> · {match.notes}</>}
                      </div>
                    </div>
                    <div className="camp-item-actions">
                      <button className="camp-del" title="Edit"
                        onClick={e => { e.stopPropagation(); setActiveId(match.id); setEditingId(match.id); }}>✎</button>
                      <button className="camp-del" title="Delete"
                        onClick={e => deleteMatch(match.id, e)}>✕</button>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </aside>

          {/* Main — lineup editor */}
          <div className="callup-checklist">
            {!activeMatch ? (
              <div className="callup-empty">Select or create a match to manage the lineup</div>
            ) : (
              <>
                <div className="callup-camp-info">
                  <div>
                    <div className="callup-cl-title">
                      {activeMatch.competition && <span className="md-comp-pill">{activeMatch.competition}</span>}
                      {' '}vs {activeMatch.opponent}
                      {(activeMatch.home_score > 0 || activeMatch.away_score > 0) && (
                        <span className="md-score-badge"> {activeMatch.home_score}–{activeMatch.away_score}</span>
                      )}
                    </div>
                    <div className="callup-cl-sub dim">
                      {fmtDate(activeMatch.match_date)}
                      {activeMatch.notes && <> · {activeMatch.notes}</>}
                    </div>
                  </div>
                  <div className="callup-cl-count mono">
                    {calledCount} played
                  </div>
                </div>

                <LineupEditor
                  key={activeMatch.id}
                  match={activeMatch}
                  players={players}
                  onSave={lineup => saveLineup(activeMatch.id, lineup)}/>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.MatchdayPanel = MatchdayPanel;
