import {parseCSV, chooseRound, measureInsertion, accuracy} from './core.js';

const $ = id => document.getElementById(id);
const input = $('typing');
let pool = [], round = [], index = 0, previous = '';
let attempts = 0, errors = 0, completedChars = 0;
let started = null, finished = false, composing = false;

function announce(message) {
  if ($('feedback').textContent !== message) $('feedback').textContent = message;
}

function renderText() {
  const target = round[index].text;
  const value = input.value;
  const fragment = document.createDocumentFragment();
  for (let i = 0; i < target.length; i++) {
    const span = document.createElement('span');
    span.textContent = target[i];
    if (i < value.length) span.className = value[i] === target[i] ? 'correct' : 'wrong';
    else if (i === value.length) span.className = 'current';
    span.setAttribute('aria-hidden', 'true');
    fragment.append(span);
  }
  $('target').replaceChildren(fragment);
  $('target').setAttribute('aria-label', target);
  $('target').removeAttribute('aria-labelledby');
  const invalid = !target.startsWith(value);
  $('typing-window').classList.toggle('error', invalid);
  $('typing-window').classList.toggle('correct', value.length > 0 && !invalid);
  input.setAttribute('aria-invalid', String(invalid));
  announce(invalid ? 'Hiba van a szövegben. Javítsd a piros részt Backspace-szel.' : value ? 'Helyes.' : `${index + 1}. mondatpár a tízből. Gépeld le a két mondatot, közöttük egy szóközzel.`);
}

function showPair() {
  input.value = '';
  previous = '';
  renderText();
}

function begin() {
  round = chooseRound(pool);
  index = 0;
  attempts = 0;
  errors = 0;
  completedChars = 0;
  started = null;
  finished = false;
  composing = false;
  $('summary').hidden = true;
  $('load-error').hidden = true;
  $('practice').hidden = false;
  input.disabled = false;
  showPair();
  input.focus({preventScroll: true});
}

function finish() {
  finished = true;
  input.disabled = true;
  const elapsed = Math.max(1, performance.now() - started);
  const seconds = Math.floor(elapsed / 1000);
  const time = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
  const values = [
    ['Idő', time],
    ['Pontosság', accuracy(attempts, errors).toLocaleString('hu-HU') + '%'],
    ['Karakter / perc', String(Math.round(completedChars * 60000 / elapsed))],
    ['Hibás beírások', String(errors)]
  ];
  $('results').replaceChildren(...values.map(([label, value]) => {
    const div = document.createElement('div');
    const dt = document.createElement('dt');
    const dd = document.createElement('dd');
    dt.textContent = label;
    dd.textContent = value;
    div.append(dt, dd);
    return div;
  }));
  $('practice').hidden = true;
  $('summary').hidden = false;
  $('summary').focus();
}

function process() {
  if (finished || input.disabled || composing) return;
  const value = input.value.normalize('NFC');
  if (value !== input.value) input.value = value;
  if (value === previous) return;
  if (started === null && value.length) started = performance.now();
  const changes = measureInsertion(previous, value, round[index].text);
  attempts += changes.attempts;
  errors += changes.errors;
  previous = value;
  if (value === round[index].text) {
    completedChars += value.length;
    index++;
    if (index === 10) finish();
    else showPair();
  } else renderText();
}

input.addEventListener('input', process);
input.addEventListener('compositionstart', () => { composing = true; });
input.addEventListener('compositionend', () => { composing = false; process(); });
input.addEventListener('beforeinput', event => {
  if (['insertFromPaste', 'insertFromDrop', 'insertParagraph', 'insertLineBreak'].includes(event.inputType)) {
    event.preventDefault();
    announce('Gépeld be a két mondatot. Közöttük egy szóköz legyen, Enter nem szükséges.');
  }
});
for (const eventName of ['paste', 'drop']) {
  input.addEventListener(eventName, event => {
    event.preventDefault();
    announce('A gyakorláshoz gépeld be a szöveget, a beillesztés nem használható.');
  });
}

async function load() {
  input.disabled = true;
  $('load-error').hidden = true;
  $('practice').hidden = false;
  $('target').textContent = 'Mesék betöltése…';
  try {
    const response = await fetch('./mesek.csv');
    if (!response.ok) throw new Error('A mesek.csv fájl nem érhető el. Ellenőrizd, hogy az index.html mellett van-e.');
    pool = parseCSV(await response.text());
    begin();
  } catch (error) {
    $('practice').hidden = true;
    $('load-error').hidden = false;
    $('load-error-message').textContent = error.message === 'Failed to fetch'
      ? 'Az oldalt a feltöltött webcímén nyisd meg, és ellenőrizd, hogy a mesek.csv is fel van-e töltve.'
      : error.message;
  }
}
$('new-round').addEventListener('click', begin);
$('retry').addEventListener('click', load);
await load();
