import * as scene from '../../../core/scene.js';
import * as net from '../../../core/net.js';
import * as audio from '../../../core/audio.js';
import * as bus from '../../../core/bus.js';
import { t } from '../../../core/i18n.js';
import { ChessBoard } from '../canvas/board.js';
import * as engine from '../logic/engine.js';
import { lookup, renderExplorerBar } from '../logic/explorer.js';
import { classifyMove } from '../logic/classifier.js';
import { getOpeningName } from '../logic/openings.js';
import { emoji } from '../../../core/theme.js';

let board, analysisData, currentMoveIdx;

export function mountAnalysis(el, params) {
  const { pgn, moveHistory = [], finalFen } = params;
  currentMoveIdx = 0;
  analysisData = null;

  engine.create();

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:var(--bg-card);">
      <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 12px;background:var(--bg-panel);border-bottom:1px solid var(--border);">
        <button class="btn btn-secondary" id="back-btn" style="min-height:32px;padding:4px 12px;font-size:12px;">← ${t('game.back')}</button>
        <span style="font-size:14px;font-weight:700;color:var(--text-primary);">${emoji('chart', '📊', 14)} ${t('analysis.title')}</span>
        <div style="width:60px;"></div>
      </div>

      <div id="analysis-board" style="flex:1;display:flex;align-items:center;justify-content:center;padding:4px;min-height:0;"></div>

      <!-- Eval bar — vertical on the side like Lichess -->
      <div style="display:flex;align-items:center;gap:8px;padding:4px 12px;background:var(--bg-panel);">
        <div id="eval-text" style="min-width:40px;font-size:13px;font-weight:800;font-family:Inter,monospace;color:var(--text-primary);text-align:center;">0.0</div>
        <div id="eval-bar" style="flex:1;height:14px;background:#1e293b;border-radius:7px;overflow:hidden;position:relative;">
          <div id="eval-fill" style="height:100%;background:var(--text-primary);width:50%;transition:width 0.4s cubic-bezier(0.16,1,0.3,1);border-radius:7px;"></div>
        </div>
      </div>

      <!-- Analysis lines + Opening explorer -->
      <div id="analysis-lines" style="padding:6px 12px;background:var(--bg-panel);border-top:1px solid rgba(255,255,255,0.04);min-height:50px;max-height:90px;overflow-y:auto;font-size:12px;">
        <div style="color:var(--text-muted);font-size:12px;text-align:center;">${t('analysis.analyzing')}</div>
      </div>

      <!-- Timeline scrubber -->
      <div style="padding:8px 12px;background:#0a0a18;border-top:1px solid rgba(255,255,255,0.04);">
        <div id="move-display" style="text-align:center;font-family:Inter,monospace;font-size:13px;font-weight:600;color:var(--text-primary);margin-bottom:6px;">${t('analysis.start')}</div>
        <div id="scrubber-track" style="position:relative;height:32px;background:var(--bg-card);border-radius:8px;cursor:pointer;touch-action:none;user-select:none;">
          <div id="scrubber-fill" style="position:absolute;top:0;right:0;height:100%;background:linear-gradient(90deg,var(--chess-primary),var(--blue));border-radius:8px;width:0%;transition:width 0.15s;"></div>
          <div id="scrubber-thumb" style="position:absolute;top:50%;transform:translate(50%,-50%);right:0%;width:18px;height:18px;background:var(--text-primary);border-radius:50%;box-shadow:0 2px 6px rgba(0,0,0,0.4);transition:right 0.15s;"></div>
          <div id="scrubber-marks" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:space-between;padding:0 8px;pointer-events:none;"></div>
        </div>
      </div>

      <!-- Move chips -->
      <div id="analysis-moves" style="padding:6px 12px;background:#0a0a18;border-top:1px solid rgba(255,255,255,0.04);max-height:40px;overflow-x:auto;white-space:nowrap;font-family:Inter,monospace;font-size:11px;display:flex;gap:3px;align-items:center;">
      </div>
    </div>
    <style>
      .move-chip { padding:3px 7px;border-radius:5px;cursor:pointer;color:var(--text-secondary);font-size:11px;transition:background 0.1s; }
      .move-chip:hover { background:rgba(255,255,255,0.08); }
      .move-chip.active { background:var(--chess-primary);color:#fff;font-weight:600; }
    </style>
  `;

  const boardContainer = el.querySelector('#analysis-board');
  board = new ChessBoard(boardContainer, { interactive: false });
  board.setPosition(engine.fen());

  // Build move list
  const moves = [];
  if (moveHistory.length > 0) {
    moveHistory.forEach(m => moves.push(m));
  }

  renderMoveChips(el, moves);

  // Navigation
  el.querySelector('#back-btn').addEventListener('click', () => { audio.play('click'); scene.pop(); });

  // Timeline scrubber
  const track = el.querySelector('#scrubber-track');
  let isDragging = false;

  function scrubToPosition(clientX) {
    const rect = track.getBoundingClientRect();
    // RTL: right side = start (0), left side = end (moves.length)
    const ratio = 1 - Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
    const idx = Math.round(ratio * moves.length);
    goToMove(el, moves, idx);
  }

  track.addEventListener('pointerdown', (e) => {
    isDragging = true;
    track.setPointerCapture(e.pointerId);
    scrubToPosition(e.clientX);
  });
  track.addEventListener('pointermove', (e) => {
    if (isDragging) scrubToPosition(e.clientX);
  });
  track.addEventListener('pointerup', () => { isDragging = false; });
  track.addEventListener('pointercancel', () => { isDragging = false; });

  // Go to final position
  goToMove(el, moves, moves.length);
}

function renderMoveChips(el, moves) {
  const container = el.querySelector('#analysis-moves');
  let html = `<span class="move-chip active" data-idx="0">${t('analysis.start')}</span>`;
  for (let i = 0; i < moves.length; i += 2) {
    const num = Math.floor(i / 2) + 1;
    html += `<span style="color:var(--text-dim);font-size:10px;">${num}.</span>`;
    html += `<span class="move-chip" data-idx="${i + 1}">${moves[i]?.san || ''}</span>`;
    if (moves[i + 1]) {
      html += `<span class="move-chip" data-idx="${i + 2}">${moves[i + 1]?.san || ''}</span>`;
    }
  }
  container.innerHTML = html;

  container.querySelectorAll('.move-chip').forEach(chip => {
    chip.addEventListener('click', () => {
      const idx = parseInt(chip.dataset.idx);
      goToMove(el, moves, idx);
    });
  });
}

function goToMove(el, moves, idx) {
  currentMoveIdx = idx;
  engine.create();

  for (let i = 0; i < idx; i++) {
    const m = moves[i];
    if (m) engine.move(m.from, m.to, m.promotion);
  }

  board.setPosition(engine.fen());
  if (idx > 0) {
    const lastMove = moves[idx - 1];
    board.setLastMove(lastMove.from, lastMove.to);
  }

  // Update display
  const display = el.querySelector('#move-display');
  if (idx === 0) display.textContent = t('analysis.start');
  else display.textContent = `${Math.ceil(idx / 2)}. ${moves[idx - 1]?.san || ''}`;

  // Update scrubber position
  const totalMoves = moves.length || 1;
  const percent = (idx / totalMoves) * 100;
  const fill = el.querySelector('#scrubber-fill');
  const thumb = el.querySelector('#scrubber-thumb');
  if (fill) fill.style.width = percent + '%';
  if (thumb) thumb.style.right = percent + '%';

  // Update active chip
  el.querySelectorAll('.move-chip').forEach(c => c.classList.remove('active'));
  const activeChip = el.querySelector(`.move-chip[data-idx="${idx}"]`);
  if (activeChip) {
    activeChip.classList.add('active');
    activeChip.scrollIntoView({ inline: 'center', behavior: 'smooth' });
  }

  // Request analysis for this position
  analyzePosition(el, engine.fen());
}

async function analyzePosition(el, fen) {
  const linesContainer = el.querySelector('#analysis-lines');
  linesContainer.innerHTML = `<div style="color:var(--text-muted);font-size:12px;text-align:center;">${t('analysis.analyzing')}</div>`;

  // Show opening explorer if data exists
  const explorerData = lookup(fen);
  if (explorerData) {
    const explorerHtml = explorerData.slice(0, 4).map(e =>
      `<div style="display:flex;align-items:center;gap:6px;padding:2px 0;">
        <span style="font-size:12px;font-weight:600;color:var(--text-primary);min-width:35px;font-family:Inter,monospace;">${e.move}</span>
        ${renderExplorerBar(e.white, e.draw, e.black)}
        <span style="font-size:9px;color:var(--text-muted);">${e.games}</span>
      </div>`
    ).join('');
    linesContainer.innerHTML = `<div style="border-bottom:1px solid rgba(255,255,255,0.05);padding-bottom:4px;margin-bottom:4px;">
      <div style="font-size:9px;color:var(--text-muted);margin-bottom:2px;">${emoji('book', '📖', 9)} ${t('analysis.openings_book')}</div>${explorerHtml}</div>
      <div style="color:var(--text-muted);font-size:11px;text-align:center;">${t('analysis.engine_analyzing')}</div>`;
  }

  try {
    const data = await net.post('analysis.php', { fen, depth: 18, lines: 3 });
    if (data.lines && data.lines.length > 0) {
      renderAnalysisLines(el, data.lines, fen, explorerData);
      updateEvalBar(el, data.lines[0].evaluation);
    }
  } catch (e) {
    if (!explorerData) {
      linesContainer.innerHTML = `<div style="color:var(--error);font-size:12px;text-align:center;">${t('analysis.failed')}</div>`;
    }
  }
}

function renderAnalysisLines(el, lines, fen, explorerData) {
  const container = el.querySelector('#analysis-lines');

  let explorerHtml = '';
  if (explorerData) {
    explorerHtml = `<div style="border-bottom:1px solid rgba(255,255,255,0.05);padding-bottom:4px;margin-bottom:4px;">
      <div style="font-size:9px;color:var(--text-muted);margin-bottom:2px;">${emoji('book', '📖', 9)} ${t('analysis.openings_book')}</div>
      ${explorerData.slice(0, 3).map(e =>
        `<div style="display:flex;align-items:center;gap:6px;padding:1px 0;">
          <span style="font-size:11px;font-weight:600;color:var(--text-primary);min-width:32px;font-family:Inter,monospace;">${e.move}</span>
          ${renderExplorerBar(e.white, e.draw, e.black)}
          <span style="font-size:9px;color:var(--text-muted);">${e.games}</span>
        </div>`
      ).join('')}
    </div>`;
  }

  container.innerHTML = explorerHtml + lines.map((line, i) => {
    const evalStr = formatEval(line.evaluation);
    const isPositive = line.evaluation >= 0;
    const color = isPositive ? 'var(--success)' : 'var(--red-light)';
    const pv = (line.pv || '').split(' ').slice(0, 6).join(' ');

    return `
      <div style="display:flex;align-items:center;gap:8px;padding:2px 0;${i === 0 ? 'font-weight:600;' : ''}">
        <span style="font-size:12px;font-weight:700;color:${color};min-width:40px;font-family:Inter,monospace;">${evalStr}</span>
        <span style="font-size:11px;color:var(--text-secondary);font-family:Inter,monospace;overflow:hidden;text-overflow:ellipsis;">${line.move} ${pv}</span>
      </div>
    `;
  }).join('');
}

function updateEvalBar(el, evaluation) {
  const fill = el.querySelector('#eval-fill');
  const text = el.querySelector('#eval-text');
  const clamped = Math.max(-10, Math.min(10, evaluation));
  const percent = 50 + (clamped / 10) * 50;
  fill.style.width = percent + '%';

  const evalStr = formatEval(evaluation);
  text.textContent = evalStr;
  text.style.color = evaluation >= 0.5 ? 'var(--success)' : evaluation <= -0.5 ? 'var(--red-light)' : 'var(--text-primary)';
}

function formatEval(ev) {
  if (ev >= 999) return 'M+';
  if (ev <= -999) return 'M-';
  const sign = ev >= 0 ? '+' : '';
  return sign + ev.toFixed(1);
}
