/* SINAIS FIFA — Player stats modal (dados reais do banco) */

const { useState: useS_P, useEffect: useE_P, useRef: useR_P } = React;

const PLAYER_LOADING_STEPS = [
  'Conectando ao motor estatístico…',
  'Lendo padrões ELO + λ Poisson do jogador…',
  'Compilando últimos confrontos…',
  'Calculando médias e tendências…',
];

const PLAYER_SAMPLE_SIZES = [5, 10, 15, 20];

const FormChipP = ({ result }) => (
  <span className={`form-chip f-${result.toLowerCase()}`}>{result}</span>
);

const PlayerModal = ({ player, onClose }) => {
  const [phase, setPhase] = useS_P('idle'); // idle | loading | analysis | error
  const [step, setStep]   = useS_P(0);
  const [sample, setSample] = useS_P(10);
  const [data, setData] = useS_P(null);
  const [errMsg, setErrMsg] = useS_P('');
  const stepRef = useR_P(null);

  useE_P(() => () => { if (stepRef.current) clearInterval(stepRef.current); }, []);

  const generate = async () => {
    if (!player.id) {
      setErrMsg('player sem id no banco');
      setPhase('error');
      return;
    }
    setPhase('loading');
    setStep(0);
    setErrMsg('');
    setData(null);

    stepRef.current = setInterval(() => {
      setStep(s => Math.min(s + 1, PLAYER_LOADING_STEPS.length - 1));
    }, 360);

    try {
      const res = await fetch(`/api/player/${encodeURIComponent(player.id)}?sample=${sample}`);
      if (!res.ok) {
        const detail = await res.json().catch(() => ({}));
        throw new Error(detail.detail || `HTTP ${res.status}`);
      }
      const body = await res.json();
      const elapsed = (PLAYER_LOADING_STEPS.length - 1) * 360;
      const wait = Math.max(0, 1300 - elapsed);
      setTimeout(() => {
        clearInterval(stepRef.current);
        setStep(PLAYER_LOADING_STEPS.length - 1);
        setData(body);
        setPhase('analysis');
      }, wait);
    } catch (e) {
      clearInterval(stepRef.current);
      setErrMsg(e.message || 'falha ao carregar estatísticas');
      setPhase('error');
    }
  };

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal modal-wide" onClick={e=>e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <h3>Estatísticas · {player.handle}</h3>
            <p>{player.team} · {player.games} jogos · ROI {player.roi >= 0 ? '+' : ''}{player.roi}%</p>
          </div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>

        <div className="modal-body">
          {phase === 'idle' && (
            <div className="state-card state-idle">
              <div className="player-hero">
                <div className="ph-av">{player.handle.slice(0,2).toUpperCase()}</div>
                <div className="ph-info">
                  <div className="ph-name">{player.handle}</div>
                  <div className="ph-team">{player.team}</div>
                  <div className="ph-meta">
                    <span><b>{player.wr}%</b><small>win rate</small></span>
                    <span><b>{player.roi >= 0 ? '+' : ''}{player.roi}%</b><small>roi</small></span>
                    <span><b>{player.games}</b><small>jogos</small></span>
                  </div>
                </div>
              </div>

              <div className="sample-pick">
                <div className="lbl">Base de análise · últimos N jogos</div>
                <div className="sample-row">
                  {PLAYER_SAMPLE_SIZES.map(n => (
                    <button key={n} className={`sample-btn ${sample === n ? 'on' : ''}`} onClick={() => setSample(n)}>
                      {n}
                    </button>
                  ))}
                </div>
              </div>

              <button className="btn-generate" onClick={generate}>⚡ GERAR ANÁLISE</button>
            </div>
          )}

          {phase === 'loading' && (
            <div className="state-card">
              <div className="steps-progress">
                {PLAYER_LOADING_STEPS.map((s, i) => (
                  <div key={i} className={`step-line ${i < step ? 'done' : i === step ? 'active' : ''}`}>
                    <span className="dot"/>
                    <span>{s}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {phase === 'error' && (
            <div className="state-card">
              <div style={{padding:24, textAlign:'center'}}>
                <div style={{fontSize:40, marginBottom:8}}>⚠️</div>
                <div style={{color:'#ff6b6b', marginBottom:16}}>Falha ao carregar estatísticas</div>
                <div style={{color:'var(--text-3)', fontSize:12, marginBottom:20}}>{errMsg}</div>
                <button className="btn-generate" onClick={generate}>↻ Tentar novamente</button>
              </div>
            </div>
          )}

          {phase === 'analysis' && data && (
            <>
              <div className="sample-tag">
                <span>base · últimos {sample} jogos</span>
                <button className="sample-edit" onClick={() => setPhase('idle')}>alterar</button>
              </div>

              <div className="ana-row">
                <div className="ana-cell">
                  <div className="lbl">Forma recente · últimos 10</div>
                  <div className="form-strip">
                    {data.recent.length === 0 && <span className="lbl">sem histórico</span>}
                    {data.recent.map((r, i) => <FormChipP key={i} result={r}/>)}
                  </div>
                </div>
                <div className="ana-cell">
                  <div className="lbl">ELO · momentum</div>
                  <div className="elo-row">
                    <div className="elo-side">
                      <div className="elo-v">{data.elo}</div>
                      <div className="sub">elo atual</div>
                    </div>
                    <div className={`mom ${data.momentum >= 0 ? 'up' : 'down'}`}>
                      {data.momentum >= 0 ? '↑' : '↓'} {Math.abs(data.momentum)}
                    </div>
                    <div className="elo-side">
                      <div className="elo-v">
                        {data.streak.n > 0 ? `${data.streak.n}${data.streak.type}` : '—'}
                      </div>
                      <div className="sub">streak</div>
                    </div>
                  </div>
                </div>
              </div>

              <div className="stats-grid">
                <div className="stat-cell">
                  <div className="lbl">Gols feitos/jogo</div>
                  <div className="val gold">{data.goalsFor}</div>
                </div>
                <div className="stat-cell">
                  <div className="lbl">Gols sofridos/jogo</div>
                  <div className="val">{data.goalsAgainst}</div>
                </div>
                <div className="stat-cell">
                  <div className="lbl">Clean sheets</div>
                  <div className="val">{data.cleanSheet}<small>%</small></div>
                </div>
                <div className="stat-cell">
                  <div className="lbl">BTTS</div>
                  <div className="val">{data.btts}<small>%</small></div>
                </div>
                <div className="stat-cell">
                  <div className="lbl">Over 2.5 hits</div>
                  <div className="val">{data.overHits}<small>/{data.overTotal}</small></div>
                </div>
              </div>

              <div className="ana-row" style={{marginTop:0}}>
                <div className="ana-cell">
                  <div className="lbl">WR jogando em casa</div>
                  <div className="wr-bar"><i style={{width: `${data.homeWR}%`}}/></div>
                  <div className="wr-val">{data.homeWR}%</div>
                </div>
                <div className="ana-cell">
                  <div className="lbl">WR jogando fora</div>
                  <div className="wr-bar"><i style={{width: `${data.awayWR}%`}}/></div>
                  <div className="wr-val">{data.awayWR}%</div>
                </div>
              </div>

              <div className="recent-block">
                <div className="picks-h">
                  <span>Últimos confrontos</span>
                  <small>resultado · placar</small>
                </div>
                <div className="recent-list">
                  {data.matches.length === 0 && (
                    <div style={{padding:14, color:'var(--text-3)', fontSize:12}}>sem confrontos no período</div>
                  )}
                  {data.matches.map((m, i) => (
                    <div className="recent-row" key={i}>
                      <span className={`form-chip f-${m.res.toLowerCase()}`} style={{width:22, height:22, fontSize:10}}>{m.res}</span>
                      <div className="recent-info">
                        <div className="recent-opp">
                          {m.home ? 'vs' : '@'} <b>{m.opp}</b>
                        </div>
                        <div className="recent-meta">{m.daysAgo}d atrás · {m.home ? 'casa' : 'fora'}</div>
                      </div>
                      <div className="recent-score">
                        <span className="rs-gf">{m.gf}</span>
                        <small>—</small>
                        <span className="rs-ga">{m.ga}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

window.PlayerModal = PlayerModal;
