/**
 * Create ticket/issue dialog — Issues toolbar uses "issue" type tag; Tickets uses "ticket".
 */
(function () {
  const META = {
    ticket: { id: 'ticket', label: 'ticket', bg: '#6366f1' },
    issue: { id: 'issue', label: 'issue', bg: '#0d9488' },
  };

  function basePath() {
    return document.body.getAttribute('data-base-path') || '';
  }

  function t(key) {
    if (window.CrashI18n && window.CrashI18n.t) {
      return window.CrashI18n.t(key);
    }
    return key;
  }

  function openDialog(kind) {
    const dialog = document.getElementById('ticket-create-dialog');
    const form = document.getElementById('ticket-create-form');
    const status = document.getElementById('ticket-create-status');
    const heading = document.getElementById('ticket-create-heading');
    if (!dialog || !form) return;
    const createKind = kind === 'issue' ? 'issue' : 'ticket';
    form.dataset.createKind = createKind;
    if (heading) {
      heading.textContent = t(createKind === 'issue' ? 'issues.new' : 'tickets.new');
    }
    if (status) status.textContent = '';
    form.reset();
    if (typeof dialog.showModal === 'function') {
      dialog.showModal();
    }
  }

  function init() {
    const dialog = document.getElementById('ticket-create-dialog');
    const form = document.getElementById('ticket-create-form');
    const cancelBtn = document.getElementById('ticket-create-cancel');
    const closeBtn = document.getElementById('ticket-create-close');
    const status = document.getElementById('ticket-create-status');
    if (!dialog || !form) return;

    document.querySelectorAll('.js-new-issue-btn').forEach((btn) => {
      btn.addEventListener('click', (ev) => {
        ev.preventDefault();
        openDialog('issue');
      });
    });
    document.querySelectorAll('.js-new-ticket-btn').forEach((btn) => {
      btn.addEventListener('click', (ev) => {
        ev.preventDefault();
        openDialog('ticket');
      });
    });

    function closeDialog() {
      dialog.close();
    }
    if (cancelBtn) cancelBtn.addEventListener('click', closeDialog);
    if (closeBtn) closeBtn.addEventListener('click', closeDialog);
    dialog.addEventListener('click', (ev) => {
      if (ev.target === dialog) closeDialog();
    });

    form.addEventListener('submit', (ev) => {
      ev.preventDefault();
      const titleEl = document.getElementById('ticket-create-title');
      const briefEl = document.getElementById('ticket-create-brief');
      const bodyEl = document.getElementById('ticket-create-body');
      const kind = form.dataset.createKind === 'issue' ? 'issue' : 'ticket';
      const meta = META[kind] || META.ticket;
      const payload = {
        title: titleEl && titleEl.value ? titleEl.value.trim() : '',
        brief: briefEl && briefEl.value ? briefEl.value.trim() : '',
        body: bodyEl && bodyEl.value ? bodyEl.value.trim() : '',
        tags: [
          meta,
          { id: 'open', label: 'open', bg: '#22c55e' },
        ],
      };
      if (!payload.title) return;
      if (status) status.textContent = 'Creating…';
      const xhr = new XMLHttpRequest();
      xhr.open('POST', basePath() + '/api/ticket_create.php', true);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.onload = function () {
        let data = null;
        try {
          data = JSON.parse(xhr.responseText);
        } catch {
          if (status) status.textContent = 'Invalid response';
          return;
        }
        if (!data || !data.ok) {
          if (status) status.textContent = (data && data.error) || 'Create failed';
          return;
        }
        dialog.close();
        const view = document.body.getAttribute('data-view') || '';
        if (view === 'tickets' && typeof window.__ticketsReload === 'function') {
          window.__ticketsReload();
        } else if (data.id) {
          window.location.href = basePath() + '/?view=ticket&id=' + encodeURIComponent(String(data.id));
        } else {
          window.location.href = basePath() + '/?view=tickets';
        }
      };
      xhr.onerror = function () {
        if (status) status.textContent = 'Network error';
      };
      xhr.send(JSON.stringify(payload));
    });
  }

  function onReady(fn) {
    if (window.CrashI18n && window.CrashI18n.ready) {
      window.CrashI18n.ready.then(fn);
    } else {
      fn();
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => onReady(init));
  } else {
    onReady(init);
  }
})();
