// public_html/v.centrx.eu/pwa/js/main.js

document.addEventListener('DOMContentLoaded', () => {
  console.log('[Init] Translator PWA start');

  // 1. Языки и локали
  const LANGUAGES = [
    {code:'bg',name:'Български'},{code:'hr',name:'Hrvatski'},{code:'cs',name:'Čeština'},
    {code:'da',name:'Dansk'},{code:'nl',name:'Nederlands'},{code:'en',name:'English'},
    {code:'et',name:'Eesti'},{code:'fi',name:'Suomi'},{code:'fr',name:'Français'},
    {code:'de',name:'Deutsch'},{code:'el',name:'Ελληνικά'},{code:'hu',name:'Magyar'},
    {code:'ga',name:'Gaeilge'},{code:'it',name:'Italiano'},{code:'lv',name:'Latviešu'},
    {code:'lt',name:'Lietuvių'},{code:'mt',name:'Malti'},{code:'pl',name:'Polski'},
    {code:'pt',name:'Português'},{code:'ro',name:'Română'},{code:'sk',name:'Slovenčina'},
    {code:'sl',name:'Slovenščina'},{code:'es',name:'Español'},{code:'sv',name:'Svenska'},
    {code:'ru',name:'Русский'},{code:'uk',name:'Українська'}
  ];
  const LOCALE = {
    bg:'bg-BG',hr:'hr-HR',cs:'cs-CZ',da:'da-DK',nl:'nl-NL',en:'en-US',et:'et-EE',
    fi:'fi-FI',fr:'fr-FR',de:'de-DE',el:'el-GR',hu:'hu-HU',ga:'ga-IE',it:'it-IT',
    lv:'lv-LV',lt:'lt-LT',mt:'mt-MT',pl:'pl-PL',pt:'pt-PT',ro:'ro-RO',
    sk:'sk-SK',sl:'sl-SI',es:'es-ES',sv:'sv-SE',ru:'ru-RU',uk:'uk-UA'
  };

  // 2. Рендер интерфейса
  const root = document.getElementById('root');
  root.innerHTML = `
    <div class="chat-header">
      <select id="selSource"></select>
      <button id="btnToggleTTS" class="btn-tts" title="Toggle TTS">🔊</button>
      <select id="selTarget"></select>
      <button id="btnConnect" class="btn-connect">Соединиться</button>
    </div>
    <div class="chat-window" id="chatWindow"></div>
    <div class="chat-input">
      <textarea id="txtMsg" placeholder="Введите текст…"></textarea>
      <button id="btnSend" disabled>➤</button>
    </div>
    <div class="fab-mic" id="fabMic" title="Нажмите и говорите">🎙</div>
  `;

  // 3. Кешируем элементы
  const selS       = document.getElementById('selSource');
  const selT       = document.getElementById('selTarget');
  const btnToggleTTS = document.getElementById('btnToggleTTS');
  const btnSend    = document.getElementById('btnSend');
  const txtMsg     = document.getElementById('txtMsg');
  const chatW      = document.getElementById('chatWindow');
  const fabMic     = document.getElementById('fabMic');

  // 4. Toggle TTS
  let ttsEnabled = true;
  btnToggleTTS.addEventListener('click', () => {
    ttsEnabled = !ttsEnabled;
    btnToggleTTS.textContent = ttsEnabled ? '🔊' : '🔇';
  });

  // 5. Заполняем селекты
  LANGUAGES.forEach(l => {
    selS.add(new Option(l.name, l.code));
    selT.add(new Option(l.name, l.code));
  });
  selS.value = 'ru';
  selT.value = 'en';

  // 6. Отправка текста по кнопке
  txtMsg.addEventListener('input', () => {
    btnSend.disabled = !txtMsg.value.trim();
  });
  btnSend.addEventListener('click', () => {
    const text = txtMsg.value.trim();
    if (!text) return;
    handleUserText(text);
    txtMsg.value = '';
    btnSend.disabled = true;
  });

  function appendMsg(text, cls) {
    const div = document.createElement('div');
    div.className = `chat-message ${cls}`;
    div.textContent = text;
    chatW.appendChild(div);
    div.scrollIntoView({behavior:'smooth'});
  }

  async function handleUserText(text) {
    appendMsg(text, 'driver');
    try {
      const translation = await translateOnline(text, selS.value, selT.value);
      appendMsg(translation, 'client');
      if (ttsEnabled) await speakText(translation, selT.value);
    } catch (e) {
      appendMsg(`Ошибка: ${e.message}`, 'client');
    }
  }

  // 7. REST API вызовы

  async function translateOnline(text, source, target) {
    const res = await fetch('/api/translate.php', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({text, source, target})
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error||res.statusText);
    return data.translation;
  }

  async function speakText(text, code) {
    const res = await fetch('/api/tts.php', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({text, lang: code})
    });
    if (!res.ok) throw new Error('TTS error');
    const blob = await res.blob();
    const url = URL.createObjectURL(blob);
    const a = new Audio(url);
    await a.play();
  }

  // 8. STT через MediaRecorder

  let recorder, audioChunks = [];
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    fabMic.addEventListener('mousedown', startRecording);
    fabMic.addEventListener('touchstart', startRecording);
    fabMic.addEventListener('mouseup', stopRecording);
    fabMic.addEventListener('mouseleave', stopRecording);
    fabMic.addEventListener('touchend', stopRecording);
  } else {
    fabMic.style.opacity = 0.3;
  }

  async function startRecording(e) {
    e.preventDefault();
    audioChunks = [];
    const stream = await navigator.mediaDevices.getUserMedia({audio:true});
    recorder = new MediaRecorder(stream);
    recorder.ondataavailable = ev => audioChunks.push(ev.data);
    recorder.start();
    fabMic.classList.add('recording');
    console.log('[STT] start recording');
  }

  function stopRecording(e) {
    e.preventDefault();
    if (!recorder) return;
    recorder.onstop = async () => {
      fabMic.classList.remove('recording');
      console.log('[STT] stop, sending to server');
      const blob = new Blob(audioChunks, {type:'audio/webm'});
      const fd = new FormData();
      fd.append('file', blob, 'voice.webm');
      fd.append('lang', selS.value);
      appendMsg('(распознавание…)', 'client');
      try {
        const res = await fetch('/api/stt.php', {method:'POST', body:fd});
        const data = await res.json();
        if (!res.ok) throw new Error(data.error||res.statusText);
        chatW.lastChild.textContent = data.text;  // заменяем «распознавание…»
        handleUserText(data.text);
      } catch (err) {
        chatW.lastChild.textContent = `Ошибка STT: ${err.message}`;
      }
    };
    recorder.stop();
  }

  // 9. Кнопка «Соединиться» (заготовка)
  document.getElementById('btnConnect').addEventListener('click', () => {
    const code = prompt('Введите код сессии:');
    if (!code) return;
    appendMsg(`Соединение по коду ${code}…`, 'system');
    // TODO: здесь будет WebSocket / Polling
  });

});
