<script>
  (function populatePrioritiseIssues() {
    const a11yRuleShortDescriptionMap = scanData?.a11yRuleShortDescriptionMap || {};
    const disabilityBadgesMap = scanData?.disabilityBadgesMap || {};
    const wcagLinks = scanData?.wcagLinks || {};
    const wcagViolations = scanData?.wcagViolations || [];
    const wcagClauses = scanData?.wcagClauses || {};
    const mustFixRules = scanItems?.mustFix?.rules || [];

    const wcagCriteriaMap = new Map();

    mustFixRules.forEach(rule => {
      const ruleId = rule.rule;
      const wcagCriteria = rule.conformance?.filter(c => c.startsWith('wcag')) || [];

      wcagCriteria.forEach(wcag => {
        const formattedWcag = formatWcagId(wcag);

        if (!wcagCriteriaMap.has(formattedWcag)) {
          const clauseKey = formattedWcag.replace('WCAG ', '');
          wcagCriteriaMap.set(formattedWcag, {
            id: formattedWcag,
            name: wcagClauses[clauseKey] || formattedWcag,
            issues: [],
            totalIssueCount: 0,
          });
        }

        const criteria = wcagCriteriaMap.get(formattedWcag);
        const displayName = a11yRuleShortDescriptionMap[ruleId] || rule.description;

        criteria.issues.push({
          ruleId: ruleId,
          description: displayName,
          originalDescription: rule.description,
          totalItems: rule.totalItems || 0,
          helpUrl: rule.helpUrl || '',
          axeImpact: rule.axeImpact || '',
          conformance: rule.conformance || [],
          pagesAffected: rule.pagesAffected || [],
        });

        criteria.totalIssueCount = criteria.issues.length || 0;
      });
    });

    const sortedCriteria = Array.from(wcagCriteriaMap.values()).sort((a, b) => {
      if (a.totalIssueCount !== b.totalIssueCount) {
        return a.totalIssueCount - b.totalIssueCount;
      }
      return a.id.localeCompare(b.id);
    });

    const failedCriteria = sortedCriteria.filter(criteria =>
      wcagViolations.some(v => formatWcagId(v) === criteria.id),
    );

    const cardElement = document.getElementById('prioritiseIssuesCard');
    if (failedCriteria.length === 0) {
      if (cardElement) {
        cardElement.style.display = 'none';
      }
      return;
    }

    const accordionContainer = document.getElementById('prioritiseIssuesAccordion');
    if (!accordionContainer) return;

    const accordionHTML = failedCriteria
      .map((criteria, index) => {
        const wcagScore = criteria.id.replace('WCAG ', '');
        const issueWord = criteria.issues.length === 1 ? 'issue' : 'issues';

        const issuesListHTML = criteria.issues
          .map(issue => {
            const disabilities = disabilityBadgesMap[issue.ruleId] || [];
            const disabilityBadges =
              disabilities.length > 0
                ? `
              <div class="priority-issue-badges">
                ${disabilities.map(disability => `<span class="disability-badge">${disability} Disability</span>`).join('')}
              </div>
            `
                : '';

            return `
              <li class="priority-issue-item" data-rule-id="${issue.ruleId}">
                <button type="button" class="priority-issue-action d-flex g-one" aria-pressed="false">
                  <div class="d-flex justify-content-between align-items-center w-90">
                      <div class="priority-issue-title">${issue.description}</div>
                      ${disabilityBadges}
                  </div>
                </button>
              </li>
            `;
          })
          .join('');

        return `
          <div class="accordion-item">
            <h3 class="accordion-header" id="heading${index}">
              <button
                class="accordion-button collapsed"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapse${index}"
                aria-expanded="false"
                aria-controls="collapse${index}"
              >
                <span class="h4 mb-0">WCAG ${wcagScore} -&nbsp;</span>
                <span class="h4 fw-normal mb-0">${criteria.issues.length} ${issueWord}</span>
                <span class="wcag-score-badge">-1 WCAG Score</span>
                <svg class="accordion-icon-collapsed" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M7.41 8.58984L12 13.1698L16.59 8.58984L18 9.99984L12 15.9998L6 9.99984L7.41 8.58984Z" fill="#5735DF"/>
                </svg>
                <svg class="accordion-icon-expanded" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M7.41 15.4102L12 10.8302L16.59 15.4102L18 14.0002L12 8.00016L6 14.0002L7.41 15.4102Z" fill="#5735DF"/>
                </svg>
              </button>
            </h3>
            <div
              id="collapse${index}"
              class="accordion-collapse collapse"
              data-bs-parent="#prioritiseIssuesAccordion"
            >
              <div class="accordion-body">
                <ul class="priority-issues-list" aria-label="Priority issues">
                  ${issuesListHTML}
                </ul>
              </div>
            </div>
          </div>
        `;
      })
      .join('');

    accordionContainer.innerHTML = accordionHTML;

    document.querySelectorAll('.priority-issue-item').forEach(item => {
      const actionButton = item.querySelector('.priority-issue-action');
      if (!actionButton) return;

      const selectIssue = function () {
        const ruleId = item.getAttribute('data-rule-id');

        document.querySelectorAll('.priority-issue-item').forEach(el => {
          el.classList.remove('active');
          const button = el.querySelector('.priority-issue-action');
          if (button) {
            button.setAttribute('aria-pressed', 'false');
          }
        });
        document.querySelectorAll('.priority-issue-title').forEach(el => {
          el.classList.remove('active');
        });

        item.classList.add('active');
        actionButton.setAttribute('aria-pressed', 'true');
        const title = item.querySelector('.priority-issue-title');
        if (title) {
          title.classList.add('active');
        }

        let selectedRule = null;
        for (const criteria of failedCriteria) {
          const issue = criteria.issues.find(i => i.ruleId === ruleId);
          if (issue) {
            selectedRule = issue;
            break;
          }
        }

        if (selectedRule && typeof window.populateIssueDetailCard === 'function') {
          window.populateIssueDetailCard(selectedRule);
        }
      };

      actionButton.addEventListener('click', selectIssue);
    });

    // Automatically open first accordion and select first issue
    if (failedCriteria.length > 0 && failedCriteria[0].issues.length > 0) {
      const firstAccordionButton = document.querySelector(
        '#prioritiseIssuesAccordion .accordion-button',
      );
      const firstAccordionCollapse = document.querySelector(
        '#prioritiseIssuesAccordion .accordion-collapse',
      );

      if (firstAccordionButton && firstAccordionCollapse) {
        firstAccordionButton.classList.remove('collapsed');
        firstAccordionButton.setAttribute('aria-expanded', 'true');
        firstAccordionCollapse.classList.add('show');
      }

      const firstIssueItem = document.querySelector('.priority-issue-item');
      if (firstIssueItem) {
        firstIssueItem.classList.add('active');
        const firstIssueButton = firstIssueItem.querySelector('.priority-issue-action');
        if (firstIssueButton) {
          firstIssueButton.setAttribute('aria-pressed', 'true');
        }
        const firstIssueTitle = firstIssueItem.querySelector('.priority-issue-title');
        if (firstIssueTitle) {
          firstIssueTitle.classList.add('active');
        }

        const firstIssue = failedCriteria[0].issues[0];

        if (typeof window.populateIssueDetailCard === 'function') {
          window.populateIssueDetailCard(firstIssue);
        }
      }
    }
  })();
</script>
