/* SINAIS FIFA — Análise H2H modal (idle → loading → analysis) */

const { useState: useS_M, useEffect: useE_M, useRef: useR_M } = React;

const LOADING_STEPS = [
  'Conectando ao motor estatístico…',
  'Lendo padrões ELO + λ Poisson dos jogadores…',
  'Decifrando histórico de confronto direto…',
  'Calculando edge e odds justas…',
  'Validando análise para entrega…',
];

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

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

const SignalModal = ({ match, onClose }) => {
  const [phase, setPhase] = useS_M('idle'); // idle | loading | analysis | error
  const [step, setStep]   = useS_M(0);
  const [sample, setSample] = useS_M(10);
  const [analysis, setAnalysis] = useS_M(null);
  const [errMsg, setErrMsg] = useS_M('');
  const stepRef = useR_M(null);

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

  const generate = async () => {
    setPhase('loading');
    setStep(0);
    setErrMsg('');
    setAnalysis(null);

    // animação dos passos roda enquanto a API responde
    stepRef.current = setInterval(() => {
      setStep(s => Math.min(s + 1, LOADING_STEPS.length - 1));
    }, 380);

    try {
      const res = await fetch(`/api/analysis/${match.id}?sample=${sample}`);
      if (!res.ok) {
        const detail = await res.json().catch(() => ({}));
        throw new Error(detail.detail || `HTTP ${res.status}`);
      }
      const data = await res.json();
      // garante o tempo mínimo da animação (≈1.5s) pra não piscar
      const elapsed = (LOADING_STEPS.length - 1) * 380;
      const wait = Math.max(0, 1500 - elapsed);
      setTimeout(() => {
        clearInterval(stepRef.current);
        setStep(LOADING_STEPS.length - 1);
        setAnalysis(data);
        setPhase('analysis');
      }, wait);
    } catch (e) {
      clearInterval(stepRef.current);
      setErrMsg(e.message || 'falha ao gerar análise');
      setPhase('error');
    }
  };

  // URL real do jogo (do banco) > fallback do AFFIL
  const gameUrl = (analysis && analysis.url) || match.url || `${AFFIL.gameUrlBase}${match.id}`;

  // streak: a API retorna side='home'|'away'; resolvemos pro objeto match
  const streakObj = analysis && analysis.streak
    ? (analysis.streak.side === 'home' ? match.home : match.away)
    : null;

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal modal-wide" onClick={e=>e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <h3>Análise H2H · {match.home.handle} vs {match.away.handle}</h3>
            <p>{match.league} · kickoff {match.t} BRT</p>
          </div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>

        <div className="modal-body">
          {phase === 'idle' && (
            <div className="state-card state-idle">
              <div className="match-hero" style={{margin:0}}>
                <div className="h-side">
                  <div className="h-av">{match.home.handle.slice(0,2).toUpperCase()}</div>
                  <div className="h-name">{match.home.handle}</div>
                  <div className="h-team">{match.home.team}</div>
                </div>
                <div className="h-vs">VS</div>
                <div className="h-side">
                  <div className="h-av">{match.away.handle.slice(0,2).toUpperCase()}</div>
                  <div className="h-name">{match.away.handle}</div>
                  <div className="h-team">{match.away.team}</div>
                </div>
              </div>

              <div className="sample-pick">
                <div className="lbl">Base de análise · últimos N jogos</div>
                <div className="sample-row">
                  {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 className="queue-meta" style={{marginTop:10, textAlign:'center'}}>
                EV estimado <b>+{(match.ev || 0).toFixed(1)}%</b> · Conf {match.conf}%
              </div>
            </div>
          )}

          {phase === 'loading' && (
            <div className="state-card">
              <div className="steps-progress">
                {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 gerar análise</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' && analysis && (
            <>
              {/* Sample size pill */}
              <div className="sample-tag">
                <span>base · últimos {sample} jogos · conf {analysis.confidence}%</span>
                <button className="sample-edit" onClick={() => setPhase('idle')}>alterar</button>
              </div>

              {/* Recent form — both players */}
              <div className="ana-row">
                <div className="ana-cell">
                  <div className="lbl">{match.home.handle} · forma recente</div>
                  <div className="form-strip">
                    {analysis.recentHome.length === 0 && <span className="lbl">sem histórico</span>}
                    {analysis.recentHome.map((r, i) => <FormChip key={i} result={r}/>)}
                  </div>
                </div>
                <div className="ana-cell">
                  <div className="lbl">{match.away.handle} · forma recente</div>
                  <div className="form-strip">
                    {analysis.recentAway.length === 0 && <span className="lbl">sem histórico</span>}
                    {analysis.recentAway.map((r, i) => <FormChip key={i} result={r}/>)}
                  </div>
                </div>
              </div>

              {/* H2H direct + ELO */}
              <div className="ana-row">
                <div className="ana-cell">
                  <div className="lbl">H2H direto · {analysis.h2h.n} confrontos</div>
                  {analysis.h2h.n === 0 ? (
                    <div className="h2h-legend"><span>sem confronto direto registrado</span></div>
                  ) : (
                    <>
                      <div className="h2h-bar">
                        <div className="h2h-w" style={{flex: analysis.h2h.w}}/>
                        <div className="h2h-d" style={{flex: analysis.h2h.d}}/>
                        <div className="h2h-l" style={{flex: analysis.h2h.l}}/>
                      </div>
                      <div className="h2h-legend">
                        <span><i className="dot-w"/>{analysis.h2h.w}V</span>
                        <span><i className="dot-d"/>{analysis.h2h.d}E</span>
                        <span><i className="dot-l"/>{analysis.h2h.l}D</span>
                      </div>
                    </>
                  )}
                </div>
                <div className="ana-cell">
                  <div className="lbl">ELO · momentum</div>
                  <div className="elo-row">
                    <div className="elo-side">
                      <div className="elo-v">{analysis.eloHome}</div>
                      <div className="sub">{match.home.handle}</div>
                    </div>
                    <div className={`mom ${analysis.momentum >= 0 ? 'up' : 'down'}`}>
                      {analysis.momentum >= 0 ? '↑' : '↓'} {Math.abs(analysis.momentum)}
                    </div>
                    <div className="elo-side">
                      <div className="elo-v">{analysis.eloAway}</div>
                      <div className="sub">{match.away.handle}</div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Stats grid */}
              <div className="stats-grid">
                <div className="stat-cell">
                  <div className="lbl">Gols esperados (λ)</div>
                  <div className="val gold">{analysis.avgGoals}</div>
                </div>
                <div className="stat-cell">
                  <div className="lbl">BTTS prob</div>
                  <div className="val">{analysis.btts}<small>%</small></div>
                </div>
                <div className="stat-cell">
                  <div className="lbl">Over 2.5 hits</div>
                  <div className="val">{analysis.overHits}<small>/{analysis.overTotal}</small></div>
                </div>
                <div className="stat-cell">
                  <div className="lbl">WR casa · fora</div>
                  <div className="val small-val">{analysis.homeWR}% · {analysis.awayWR}%</div>
                </div>
                <div className="stat-cell streak">
                  <div className="lbl">Streak ativa</div>
                  <div className="val">
                    {analysis.streak.n > 0 ? (
                      <>
                        <span className={`streak-badge ${analysis.streak.type === 'V' ? 'up' : 'down'}`}>
                          {analysis.streak.n}{analysis.streak.type}
                        </span>
                        <small style={{marginLeft:6}}>{streakObj?.handle}</small>
                      </>
                    ) : <small>—</small>}
                  </div>
                </div>
              </div>

              {/* Recommended picks (ranked) */}
              <div className="picks-block">
                <div className="picks-h">
                  <span>Picks recomendados</span>
                  <small>ranqueados por edge — motor estatístico real</small>
                </div>
                {analysis.picks.length === 0 && (
                  <div style={{padding:14, color:'var(--text-3)', fontSize:12}}>nenhum pick com edge positivo</div>
                )}
                {analysis.picks.map((p, i) => (
                  <div className={`pick-row ${i === 0 ? 'top' : ''}`} key={i}>
                    <div className="pick-rank">#{i+1}</div>
                    <div className="pick-info">
                      <div className="pick-type">{p.type}</div>
                      <div className="pick-meta">
                        odd mín. <b>{p.minOdd}</b> · justa {p.fairOdd}
                        {p.marketOdd && <> · GoldeBet <b>{p.marketOdd}</b></>}
                        {' '}· prob {p.prob}%
                      </div>
                    </div>
                    <div className={`pick-edge ${p.edge >= 6 ? 'hot' : ''}`}>
                      +{p.edge}<small>%</small>
                    </div>
                  </div>
                ))}
              </div>

              <a className="cta-stake" href={gameUrl} target="_blank" rel="noreferrer">
                Ir para o jogo →
              </a>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

window.SignalModal = SignalModal;
