/*
  APP — shared chrome for every page: settings dialog, footer API label,
  toast notifications.
*/
(function () {
  'use strict';

  function initChrome() {
    const modal = document.getElementById('settingsModal');
    const openBtn = document.getElementById('settingsBtn');
    const input = document.getElementById('apiBaseInput');

    if (openBtn && modal && input) {
      const close = () => {
        modal.hidden = true;
      };
      openBtn.addEventListener('click', () => {
        input.value = SR.config.getBase();
        modal.hidden = false;
        input.focus();
        input.select();
      });
      const closeBtn = document.getElementById('settingsClose');
      if (closeBtn) closeBtn.addEventListener('click', close);
      modal.addEventListener('click', (e) => {
        if (e.target === modal) close();
      });
      document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && !modal.hidden) close();
      });
      const saveBtn = document.getElementById('apiBaseSave');
      if (saveBtn) {
        saveBtn.addEventListener('click', () => {
          SR.config.setBase(input.value);
          location.reload();
        });
      }
      const resetBtn = document.getElementById('apiBaseReset');
      if (resetBtn) {
        resetBtn.addEventListener('click', () => {
          SR.config.clearBase();
          location.reload();
        });
      }
    }

    const label = document.getElementById('apiBaseLabel');
    if (label) {
      const base = SR.config.getBase();
      label.textContent = base;
      label.href = base;
    }
  }

  let toastTimer = null;

  function toast(message, isError) {
    let el = document.getElementById('toast');
    if (!el) {
      el = document.createElement('div');
      el.id = 'toast';
      el.className = 'toast';
      el.setAttribute('role', 'status');
      document.body.appendChild(el);
    }
    el.textContent = message;
    el.classList.toggle('toast--error', !!isError);
    el.classList.add('toast--show');
    clearTimeout(toastTimer);
    toastTimer = setTimeout(() => el.classList.remove('toast--show'), 4500);
  }

  function showError(err, fallback) {
    toast(err && err.message ? err.message : fallback || 'Something went wrong', true);
  }

  window.SR = window.SR || {};
  SR.app = { initChrome, toast, showError };
})();
