/** AURA FARMING — Etapa 19.1: preparação, iluminação e validação local da câmera */
(() => {
  'use strict';

  const baseUrl = document.querySelector('meta[name="app-base-url"]')?.content || '';
  const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';
  const root = document.querySelector('.farm-prep');
  const safeMinor = root?.dataset.safeMinor === '1';
  const safeLightingMin = Math.max(10, Number(root?.dataset.safeLightingMin || 28));
  const safeLightingMax = Math.min(100, Number(root?.dataset.safeLightingMax || 96));
  const battleId = Number(root?.dataset.battleId || 0);
  const competitionId = Number(root?.dataset.competitionId || 0);
  const controlledEventId = Number(root?.dataset.controlledEventId || 0);
  const mode = root?.dataset.mode || 'individual';
  const viralToken = root?.dataset.viralToken || '';
  const video = document.querySelector('#camera-preview');
  const placeholder = document.querySelector('#camera-placeholder');
  const status = document.querySelector('#camera-status');
  const testButton = document.querySelector('#btn-test-camera');
  const startButton = document.querySelector('#btn-start-farm');
  const lightCanvas = document.createElement('canvas');
  lightCanvas.width = 32;
  lightCanvas.height = 24;
  const lightContext = lightCanvas.getContext('2d', { willReadFrequently: true });
  let stream = null;
  let cameraReady = false;
  let lightingScore = safeMinor ? 0 : 100;
  let lightingTimer = null;

  function measureLighting() {
    if (!safeMinor || !lightContext || !video || video.readyState < 2) {
      return { score: safeMinor ? 0 : 100, ok: !safeMinor };
    }
    try {
      lightContext.drawImage(video, 0, 0, lightCanvas.width, lightCanvas.height);
      const pixels = lightContext.getImageData(0, 0, lightCanvas.width, lightCanvas.height).data;
      let total = 0;
      for (let i = 0; i < pixels.length; i += 4) {
        total += (pixels[i] * 0.2126) + (pixels[i + 1] * 0.7152) + (pixels[i + 2] * 0.0722);
      }
      lightingScore = Math.round((total / (pixels.length / 4)) / 255 * 100);
      return { score: lightingScore, ok: lightingScore >= safeLightingMin && lightingScore <= safeLightingMax };
    } catch (_) {
      lightingScore = 0;
      return { score: 0, ok: false };
    }
  }

  function renderCameraState() {
    const lighting = measureLighting();
    if (safeMinor && !lighting.ok) {
      cameraReady = false;
      status.textContent = lighting.score < safeLightingMin
        ? `AMBIENTE ESCURO • ILUMINAÇÃO ${lighting.score}%`
        : `LUZ FORTE DEMAIS • ILUMINAÇÃO ${lighting.score}%`;
      status.className = 'camera-check__status camera-check__status--error';
      startButton && (startButton.disabled = true);
      return;
    }

    cameraReady = true;
    status.textContent = safeMinor
      ? `CÂMERA E ILUMINAÇÃO PRONTAS • ${lighting.score}%`
      : 'CÂMERA PRONTA';
    status.className = 'camera-check__status camera-check__status--ok';
    testButton.textContent = '✓ CÂMERA TESTADA';
    startButton && (startButton.disabled = false);
  }

  async function openCamera() {
    if (!navigator.mediaDevices?.getUserMedia) {
      throw new Error('Seu navegador não oferece suporte à câmera.');
    }

    stopCamera();
    status.textContent = 'Solicitando acesso…';
    status.className = 'camera-check__status';

    stream = await navigator.mediaDevices.getUserMedia({
      video: {
        facingMode: 'user',
        width: { ideal: 720 },
        height: { ideal: 1280 },
      },
      audio: false,
    });

    video.srcObject = stream;
    await video.play();
    placeholder.hidden = true;

    await new Promise(resolve => setTimeout(resolve, 350));
    renderCameraState();
    lightingTimer = window.setInterval(renderCameraState, 1200);
  }

  function stopCamera() {
    if (lightingTimer) {
      clearInterval(lightingTimer);
      lightingTimer = null;
    }
    if (stream) {
      stream.getTracks().forEach(track => track.stop());
      stream = null;
    }
    cameraReady = false;
  }

  function deviceFingerprint() {
    let id = localStorage.getItem('af_match_device');
    if (!id) {
      id = (crypto.randomUUID?.() || `${Date.now()}-${Math.random().toString(16).slice(2)}`);
      localStorage.setItem('af_match_device', id);
    }
    return [id, screen.width, screen.height, navigator.platform || 'web'].join('|').slice(0, 255);
  }

  async function createMatch() {
    if (!stream) await openCamera();
    renderCameraState();
    if (!cameraReady) {
      throw new Error('Ajuste a iluminação e mantenha apenas o jogador autorizado no enquadramento.');
    }

    startButton.disabled = true;
    startButton.textContent = '⏳ PREPARANDO SESSÃO…';

    const response = await fetch(`${baseUrl}/api/v1/matches/start.php`, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrf,
      },
      body: JSON.stringify({
        fingerprint: deviceFingerprint(),
        batalha_id: battleId,
        competicao_id: competitionId,
        controlled_event_id: controlledEventId,
        modo: mode,
        viral_token: viralToken,
        camera_preflight: {
          lighting_score: lightingScore,
          lighting_ok: !safeMinor || (lightingScore >= safeLightingMin && lightingScore <= safeLightingMax),
          processed_on_device: true,
        },
      }),
    });
    const data = await response.json().catch(() => ({}));
    if (!response.ok || !data.ok || !data.partida?.sessao_id) {
      throw new Error(data.erro || 'Não foi possível criar a sessão.');
    }

    stopCamera();
    window.location.href = `${baseUrl}/pages/partida.php?s=${encodeURIComponent(data.partida.sessao_id)}`;
  }

  testButton?.addEventListener('click', async () => {
    testButton.disabled = true;
    try {
      await openCamera();
    } catch (error) {
      cameraReady = false;
      status.textContent = error.name === 'NotAllowedError' ? 'PERMISSÃO NEGADA' : 'CÂMERA INDISPONÍVEL';
      status.className = 'camera-check__status camera-check__status--error';
      placeholder.hidden = false;
      placeholder.querySelector('strong').textContent = error.message || 'Não foi possível abrir a câmera.';
      startButton && (startButton.disabled = true);
    } finally {
      testButton.disabled = false;
    }
  });

  startButton?.addEventListener('click', async () => {
    try {
      await createMatch();
    } catch (error) {
      alert(error.message || 'Não foi possível iniciar a partida.');
      startButton.disabled = !cameraReady;
      startButton.textContent = '⚡ INICIAR DESAFIO';
    }
  });

  window.addEventListener('pagehide', stopCamera);
})();
