(function (root, factory) {
  const api = factory();
  if (typeof module === 'object' && module.exports) module.exports = api;
  else root.createIssueFilingReceipt = api;
})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
  'use strict';

  function createIssueFilingReceipt({
    root, heading, key, title, ownership, openLink, shareButton, filedButton,
    relatedButton, fileAnotherButton, doneButton, status, navigator = {}, clipboard = navigator.clipboard,
    onFileRelated = function () {},
    onFileAnother = function () {},
    onViewFiled = function () {},
  }) {
    let active = null;
    let relatedPlan = null;
    let restoreFocus = null;

    function close() {
      root.hidden = true;
      active = null;
      relatedPlan = null;
      const target = restoreFocus;
      restoreFocus = null;
      target?.focus?.();
    }

    async function share() {
      if (!active) return;
      const payload = {
        title: active.repository + '#' + active.number + ' · ' + active.title,
        text: active.title,
        url: active.url,
      };
      if (typeof navigator.share === 'function') {
        try {
          await navigator.share(payload);
          return;
        } catch (error) {
          if (error?.name === 'AbortError') return;
        }
      }
      if (typeof clipboard?.writeText !== 'function') {
        status.textContent = 'Issue link is ready in Open in Gitea.';
        return;
      }
      await clipboard.writeText(active.url);
      status.textContent = 'Issue link copied.';
    }

    function show(issue, returnTarget, reusablePlan = null) {
      active = issue;
      relatedPlan = reusablePlan;
      restoreFocus = returnTarget || null;
      key.textContent = issue.repository + '#' + issue.number;
      title.textContent = issue.title;
      ownership.textContent = issue.assignees?.length
        ? 'Assigned to @' + issue.assignees.join(', @') + '.'
        : 'Created with no owner.';
      openLink.href = issue.url;
      status.textContent = '';
      if (relatedButton) relatedButton.hidden = !relatedPlan;
      root.hidden = false;
      heading.focus();
    }

    shareButton.addEventListener('click', share);
    filedButton?.addEventListener('click', () => {
      if (!active) return;
      const issue = active;
      close();
      onViewFiled(issue);
    });
    root.addEventListener('keydown', event => {
      if (event.key !== 'Escape' || root.hidden) return;
      event.preventDefault();
      close();
    });
    doneButton.addEventListener('click', close);
    relatedButton?.addEventListener('click', () => {
      if (!relatedPlan) return;
      const plan = relatedPlan;
      close();
      onFileRelated(plan);
    });
    fileAnotherButton.addEventListener('click', () => {
      close();
      onFileAnother();
    });

    return { show, close, share };
  }

  return createIssueFilingReceipt;
});
