import { exportTimeRange } from './model.js';

export function createExportController({
  document,
  getDuration,
  getLoop,
  getCanvasSize,
  hasAudio,
  updateResolutionLabels = () => {},
  onStart,
  onCancel = () => {},
}) {
  const element = id => document.getElementById(id);
  const modal = element('exportModal');
  const progressModal = element('exportProgressModal');
  const completeModal = element('exportCompleteModal');
  const range = element('exportRange');
  const audioToggle = element('exportIncludeAudio');
  const audioHint = element('exportAudioHint');
  const quickOptions = element('exportQuickOptions');
  const hqOptions = element('exportHQOptions');
  const tabs = [...document.querySelectorAll('.export-tab')];
  const listeners = [];
  let mode = 'quick';

  const listen = (target, type, handler) => {
    if (!target) return;
    target.addEventListener(type, handler);
    listeners.push(() => target.removeEventListener(type, handler));
  };
  const hide = () => modal?.classList.remove('show');
  const updateDuration = () => {
    const result = exportTimeRange(range?.value, getDuration(), getLoop());
    const mins = Math.floor(result.duration / 60);
    const secs = Math.floor(result.duration % 60);
    const output = element('exportDuration');
    if (output) output.textContent = `${mins}:${String(secs).padStart(2, '0')}`;
  };
  const show = () => {
    updateDuration();
    updateResolutionLabels();
    const size = getCanvasSize();
    const resolution = element('exportQuickResDisplay');
    if (resolution) resolution.textContent = `${size.width}×${size.height}`;
    if (audioHint && audioToggle) {
      if (hasAudio()) {
        audioHint.textContent = 'Audio will be included in export';
        audioToggle.disabled = false;
      } else {
        audioHint.textContent = 'No audio loaded in project';
        audioToggle.checked = false;
        audioToggle.disabled = true;
      }
    }
    modal?.classList.add('show');
  };

  listen(element('btnExportVideo'), 'click', show);
  listen(element('exportModalClose'), 'click', hide);
  listen(element('exportCancel'), 'click', hide);
  listen(element('exportCompleteClose'), 'click', () => completeModal?.classList.remove('show'));
  listen(range, 'change', () => {
    updateDuration();
    updateResolutionLabels();
  });
  for (const id of ['exportHQResolution', 'exportHQFps', 'exportHQQuality']) {
    listen(element(id), 'change', updateResolutionLabels);
  }
  listen(audioToggle, 'change', event => {
    if (audioHint) {
      audioHint.textContent = event.target.checked
        ? 'Audio will be included in export'
        : 'Export will be silent (no audio)';
    }
  });
  for (const tab of tabs) {
    listen(tab, 'click', () => {
      for (const item of tabs) item.classList.remove('active');
      tab.classList.add('active');
      mode = tab.dataset.mode;
      if (quickOptions) quickOptions.style.display = mode === 'quick' ? 'block' : 'none';
      if (hqOptions) hqOptions.style.display = mode === 'hq' ? 'block' : 'none';
    });
  }
  listen(element('exportStart'), 'click', async () => {
    hide();
    await onStart(mode);
  });
  listen(element('exportCancelProgress'), 'click', () => {
    progressModal?.classList.remove('show');
    onCancel();
  });

  return {
    show,
    hide,
    updateDuration,
    getMode: () => mode,
    destroy() {
      for (const remove of listeners.splice(0)) remove();
    },
  };
}
