import type { PopupState } from '../shared/types';

// Plan 01-12 Wave 4: operator-facing copy now flows from
// chrome.i18n.getMessage(<key>) reads against _locales/{en,ru}/messages.json.
// A `|| <fallback>` literal is kept at each call site so unit-test contexts
// without a chrome.i18n stub degrade to readable Russian-ish text rather
// than empty strings (Chrome's chrome.i18n.getMessage returns '' for
// unknown keys per RESEARCH Pitfall 4).

// Элементы UI
const saveButton = document.getElementById('saveButton') as HTMLButtonElement;
const statusMessage = document.getElementById('statusMessage') as HTMLDivElement;

// Состояние
// Plan 01-09: under the SAVE-only popup charter, the popup ONLY opens
// when setPopup was switched to the html path (which happens in REC and
// ERROR modes — see src/background/index.ts setRecordingMode/setErrorMode).
// In OFF mode setPopup('') causes the toolbar click to fire onClicked
// directly and skip the popup entirely. Therefore, when the popup
// loads, we KNOW recording is active (or just errored) — initialize
// hasPermissions to true so the SAVE button is enabled immediately.
let popupState: PopupState = {
  isRecording: true,
  hasPermissions: true,
  status: 'idle'
};

// Логирование
// IN-02-companion: align with the IN-02 fix to Logger/ContentLogger —
// `unknown[]` is the strict-mode-friendly signature for variadic
// console wrappers. console.log accepts unknown values natively.
function log(...args: unknown[]) {
  console.log('[Popup]', ...args);
}

/**
 * Safe wrapper around chrome.i18n.getMessage with explicit fallback.
 * Returns the fallback when chrome.i18n is undefined (unit-test contexts
 * without a stub) OR when the key is missing in the resolved locale.
 */
function i18n(key: string, fallback: string): string {
  const text = chrome?.i18n?.getMessage?.(key) ?? '';
  return text.length > 0 ? text : fallback;
}

/**
 * Populate every element carrying a data-mks-key attribute with the
 * resolved i18n string. Called once at init() for static-copy elements
 * (info-text, etc.); dynamic copy (button text) is set per-state in
 * updateUI().
 */
function populateMksKeys(): void {
  document.querySelectorAll<HTMLElement>('[data-mks-key]').forEach((el) => {
    const key = el.dataset.mksKey;
    if (key) el.textContent = i18n(key, el.textContent ?? '');
  });
}

// Обновление UI
function updateUI() {
  log('Updating UI:', popupState);

  // Текст кнопки
  const buttonText = saveButton.querySelector('.button-text') as HTMLSpanElement;

  switch (popupState.status) {
    case 'idle':
      buttonText.textContent = i18n('popupSaveCta', 'Сохранить отчёт об ошибке');
      saveButton.className = 'save-button';
      saveButton.disabled = !popupState.hasPermissions;
      break;

    case 'saving':
      buttonText.textContent = i18n('popupSaving', 'Сохраняю...');
      saveButton.className = 'save-button saving';
      saveButton.disabled = true;
      break;

    case 'done':
      buttonText.textContent = i18n('popupSaveDoneShort', 'Готово! ✓');
      saveButton.className = 'save-button done';
      saveButton.disabled = true;
      break;
  }

  // Сообщение о статусе
  // Plan 01-09: SAVE-only charter — the popup is ONLY accessible when
  // recording is active (REC mode setPopup) or in ERROR (operator may
  // still attempt SAVE). The empty-state copy points operators back to
  // the toolbar icon for starting a NEW session.
  if (!popupState.hasPermissions && popupState.status === 'idle') {
    statusMessage.textContent = i18n('popupEmptyState', 'Откройте запись через иконку расширения');
    statusMessage.className = 'status-message error';
  } else {
    statusMessage.textContent = '';
    statusMessage.className = 'status-message';
  }
}

// Plan 01-09: removed checkPermissions / requestPermissions auto-start
// path. The popup is now SAVE-only — the toolbar onClicked handler in
// the SW owns recording start. See src/background/index.ts
// chrome.action.onClicked.addListener for the new start flow.

// Сохранение архива
async function saveArchive() {
  popupState.status = 'saving';
  updateUI();

  try {
    log('Starting archive save...');

    const response = await chrome.runtime.sendMessage({
      type: 'SAVE_ARCHIVE'
    });

    log('Save response:', response);

    if (response.success) {
      popupState.status = 'done';
      statusMessage.textContent = i18n('popupSaveDone', 'Архив успешно сохранён!');
      statusMessage.className = 'status-message success';

      // Возвращаемся в idle через 3 секунды
      setTimeout(() => {
        popupState.status = 'idle';
        statusMessage.textContent = '';
        updateUI();
      }, 3000);

    } else {
      throw new Error(response.error || 'Unknown error');
    }

  } catch (error) {
    log('Error saving archive:', error);
    popupState.status = 'idle';
    statusMessage.textContent = 'Ошибка сохранения: ' + (error as Error).message;
    statusMessage.className = 'status-message error';
    updateUI();
  }
}

// Инициализация
function init() {
  log('Popup initializing');

  // Привязка событий
  saveButton.addEventListener('click', saveArchive);

  // Populate data-mks-key static elements (info-text etc.) on init.
  populateMksKeys();

  // Plan 01-09: SAVE-only popup — no permission round-trip on open. The
  // popup is only reachable when recording is active (background SW sets
  // setPopup to this html in REC/ERROR modes; OFF mode uses setPopup('')
  // which makes the toolbar click fire onClicked instead). hasPermissions
  // defaults to true so SAVE is enabled immediately.
  updateUI();

  log('Popup initialized');
}

// Запуск при загрузке
document.addEventListener('DOMContentLoaded', init);
