(function(){
  // ── Verify (Settings tab) ──
  var btn = document.getElementById('webability-acwg-verify');
  var statusBox = document.getElementById('wa-verify-status');
  var statusMsg = statusBox ? statusBox.querySelector('.wa-verify-msg') : null;

  async function runVerify(){
    if(statusMsg) statusMsg.textContent = 'Checking…';
    if(statusBox) statusBox.className = 'wa-verify-status';
    try {
      var u = new URL(WEBABILITY_ACWG_VERIFY.ajax);
      u.searchParams.set('action','webability_acwg_verify');
      u.searchParams.set('nonce', WEBABILITY_ACWG_VERIFY.nonce);
      var r = await fetch(u.toString(), { credentials:'same-origin' });
      var j = await r.json();
      if(j.ok){
        if(statusMsg) statusMsg.textContent = '✅ Domain verified';
        if(statusBox) statusBox.className = 'wa-verify-status wa-verify-success';
      } else {
        if(statusMsg) statusMsg.textContent = '❌ Not detected — register at webability.io';
        if(statusBox) statusBox.className = 'wa-verify-status wa-verify-error';
      }
    } catch(err){
      if(statusMsg) statusMsg.textContent = '❌ Error — please try again';
      if(statusBox) statusBox.className = 'wa-verify-status wa-verify-error';
    }
  }

  if(btn){
    btn.addEventListener('click', function(e){ e.preventDefault(); runVerify(); });
    // Auto-verify only if not already verified
    if(!WEBABILITY_ACWG_VERIFY.verified) runVerify();
  }

  // ── Widget Design tab: live preview ──
  var designForm = document.getElementById('wa-design-form');
  if(designForm){
    var previewBtn = document.getElementById('wa-preview-btn');

    function updatePreview(){
      var pos = designForm.querySelector('input[name$="[position]"]:checked');
      if(pos && previewBtn) previewBtn.setAttribute('data-position', pos.value);

      var size = designForm.querySelector('input[name$="[trigger_size]"]:checked');
      if(size && previewBtn){
        var dim = size.value === 'small' ? 36 : size.value === 'large' ? 52 : 44;
        var icon = previewBtn.querySelector('.dashicons') || previewBtn.querySelector('svg') || previewBtn.querySelector('img');
        if(icon){ icon.style.fontSize = dim + 'px'; icon.style.width = dim + 'px'; icon.style.height = dim + 'px'; }
      }

      var iconType = designForm.querySelector('input[name$="[icon_type]"]:checked');
      var triggerInfo = document.getElementById('wa-custom-trigger-info');
      if(iconType && previewBtn){
        previewBtn.setAttribute('data-icon-type', iconType.value);
        if(iconType.value === 'hidden'){
          previewBtn.style.display = 'none';
          if(triggerInfo) triggerInfo.style.display = 'block';
        } else {
          previewBtn.style.display = '';
          if(triggerInfo) triggerInfo.style.display = 'none';
        }
      }
    }

    designForm.querySelectorAll('input[type="radio"]').forEach(function(input){
      input.addEventListener('change', function(){
        var group = this.closest('.wa-position-grid, .wa-color-swatches, .wa-size-options, .wa-icon-type-options');
        if(group){
          var activeClass = group.classList.contains('wa-position-grid') ? 'wa-position-active'
            : group.classList.contains('wa-color-swatches') ? 'wa-color-active'
            : group.classList.contains('wa-icon-type-options') ? 'wa-icon-type-active'
            : 'wa-size-active';
          group.querySelectorAll('label').forEach(function(l){ l.classList.remove(activeClass); });
          this.closest('label').classList.add(activeClass);
        }
        updatePreview();
      });
    });

    var colorInput = designForm.querySelector('.wa-color-input');
    if(colorInput){
      colorInput.addEventListener('input', function(){
        designForm.querySelectorAll('.wa-color-swatch').forEach(function(s){
          s.classList.remove('wa-color-active');
          var r = s.querySelector('input[type="radio"]');
          if(r) r.checked = false;
        });
        var existing = designForm.querySelector('input[name$="[widget_color]"]:checked');
        if(existing) existing.checked = false;
        // Color saved for widget output but preview uses branded SVG
      });
    }

    updatePreview();
  }

  // ── Statement Generator tab ──
  var genBtn = document.getElementById('wa-generate-stmt');
  if(genBtn){
    // Toggle optional fields
    var toggleBtn = document.getElementById('wa-toggle-optional');
    var optFields = document.getElementById('wa-optional-fields');
    var toggleArrow = document.getElementById('wa-toggle-arrow');
    if(toggleBtn && optFields){
      toggleBtn.style.cursor = 'pointer';
      toggleBtn.addEventListener('click', function(){
        var shown = optFields.style.display !== 'none';
        optFields.style.display = shown ? 'none' : 'block';
        if(toggleArrow) toggleArrow.innerHTML = shown ? '&#9660;' : '&#9650;';
      });
    }

    // Format tabs
    var currentFormat = 'html';
    var formatTabs = document.getElementById('wa-format-tabs');
    if(formatTabs){
      formatTabs.querySelectorAll('.wa-format-tab').forEach(function(tab){
        tab.addEventListener('click', function(){
          formatTabs.querySelectorAll('.wa-format-tab').forEach(function(t){ t.classList.remove('wa-format-active'); });
          this.classList.add('wa-format-active');
          currentFormat = this.getAttribute('data-format');
        });
      });
    }

    // Store generated markdown for format conversion
    var generatedMarkdown = '';

    genBtn.addEventListener('click', function(){
      var company = document.getElementById('wa-stmt-company').value.trim();
      var url = document.getElementById('wa-stmt-url').value.trim();
      var email = document.getElementById('wa-stmt-email').value.trim();
      var industryEl = document.getElementById('wa-stmt-industry');
      var industry = industryEl ? industryEl.value : '';
      var standardText = 'WCAG 2.2 AA';
      var language = 'English';

      // Optional fields
      var brandName = (document.getElementById('wa-stmt-brand-name') || {}).value || '';
      var brandUrl = (document.getElementById('wa-stmt-brand-url') || {}).value || '';
      var phone = (document.getElementById('wa-stmt-phone') || {}).value || '';
      var visitorAddr = (document.getElementById('wa-stmt-visitor-address') || {}).value || '';
      var postalAddr = (document.getElementById('wa-stmt-postal-address') || {}).value || '';
      var formUrl = (document.getElementById('wa-stmt-form-url') || {}).value || '';

      // Validate required fields
      var requiredFields = [
        {id:'wa-stmt-company', v:company},
        {id:'wa-stmt-url', v:url},
        {id:'wa-stmt-email', v:email},
        {id:'wa-stmt-industry', v:industry}
      ];
      var hasError = false;
      requiredFields.forEach(function(f){
        var el = document.getElementById(f.id);
        if(!f.v){ el.style.borderColor = '#d63638'; hasError = true; }
        else { el.style.borderColor = ''; }
      });
      if(hasError) return;

      var date = new Date().toLocaleDateString('en-US', {year:'numeric', month:'long', day:'numeric'});
      var nextReviewDate = new Date(Date.now() + 365*24*60*60*1000).toLocaleDateString('en-US', {year:'numeric', month:'long', day:'numeric'});

      // Build organizational measures
      var orgMeasures = [
        'Include accessibility as part of our mission statement and core values',
        'Include accessibility throughout our internal policies and procedures',
        'Integrate accessibility into our procurement practices and vendor requirements',
        'Appoint an accessibility officer and/or ombudsperson with dedicated responsibilities',
        'Provide continual accessibility training for our staff, including developers, designers, and content creators',
        'Assign clear accessibility goals and responsibilities across departments',
        'Employ formal accessibility quality assurance methods and testing protocols'
      ];

      var techMeasures = [
        'Regular accessibility audits using automated and manual testing tools',
        'Implementation of WCAG 2.1 AA guidelines across all digital properties',
        'User testing with people with disabilities to validate real-world accessibility',
        'Continuous monitoring and improvement of accessibility features'
      ];

      // Automated testing list
      var automatedList = [
        'Regular automated accessibility scanning using WebAbility\'s accessibility testing platform',
        'Integration with development workflow for continuous accessibility monitoring',
        'Monthly comprehensive accessibility audits'
      ];

      // Response time
      var responseTime = 'We try to respond to accessibility feedback within 2-3 business days and resolve reported issues within 5-10 business days, depending on complexity.';

      // Compliance list
      var complianceStandards = [
        'Section 508 of the Rehabilitation Act',
        'Americans with Disabilities Act (ADA)',
        'EN 301 549 European Standard'
      ];

      // Build contact items
      var contactItems = [];
      if(phone.trim()) contactItems.push({label: 'Phone', value: phone.trim()});
      contactItems.push({label: 'E-mail', value: email, href: 'mailto:' + email});
      if(formUrl.trim()) contactItems.push({label: 'Online Form', value: formUrl.trim(), href: formUrl.trim()});
      if(visitorAddr.trim()) contactItems.push({label: 'Visitor Address', value: visitorAddr.trim()});
      if(postalAddr.trim()) contactItems.push({label: 'Postal Address', value: postalAddr.trim()});

      // Build the statement as DOM (safe, no innerHTML with user data)
      var output = document.getElementById('wa-stmt-output');
      output.textContent = '';

      // Title
      appendEl(output, 'h2', 'Accessibility Statement for ' + company);
      var dateP = document.createElement('p');
      var dateEm = document.createElement('em');
      dateEm.textContent = 'Last updated: ' + date;
      dateP.appendChild(dateEm);
      output.appendChild(dateP);

      // 1. General
      appendEl(output, 'h2', 'General');
      var p1 = document.createElement('p');
      appendBold(p1, company);
      p1.appendChild(document.createTextNode(' is committed to ensuring digital accessibility for people with disabilities. We are continually improving the user experience for everyone, and applying the relevant accessibility standards to create an inclusive digital environment.'));
      output.appendChild(p1);

      var p1b = document.createElement('p');
      p1b.appendChild(document.createTextNode('At '));
      appendBold(p1b, company);
      p1b.appendChild(document.createTextNode(', we believe that digital accessibility is not just a legal requirement but a fundamental human right. We strive to ensure that our website '));
      appendBold(p1b, url);
      p1b.appendChild(document.createTextNode(' is accessible to all users, regardless of their abilities or the assistive technologies they use.'));
      output.appendChild(p1b);

      // 2. Measures to support accessibility
      appendEl(output, 'h2', 'Measures to support accessibility');
      var p2 = document.createElement('p');
      appendBold(p2, company);
      p2.appendChild(document.createTextNode(' takes the following comprehensive measures to ensure accessibility of '));
      appendBold(p2, url);
      p2.appendChild(document.createTextNode(':'));
      output.appendChild(p2);

      appendEl(output, 'h3', 'Organizational Measures');
      appendList(output, orgMeasures);

      appendEl(output, 'h3', 'Technical Measures');
      appendList(output, techMeasures);

      // 3. Conformance status
      appendEl(output, 'h2', 'Conformance status');
      appendEl(output, 'p', 'The Web Content Accessibility Guidelines (WCAG) define requirements for designers and developers to improve accessibility for people with disabilities. It defines three levels of conformance: Level A, Level AA, and Level AAA.');
      var p3 = document.createElement('p');
      appendBold(p3, url);
      p3.appendChild(document.createTextNode(' is fully conformant with ' + standardText + '. Fully conformant means that the content fully meets the accessibility standard without any exceptions.'));
      output.appendChild(p3);

      appendEl(output, 'p', 'This website also complies with:');
      appendList(output, complianceStandards);

      // 4. Technical specifications
      appendEl(output, 'h2', 'Technical specifications');
      var p4 = document.createElement('p');
      appendBold(p4, url);
      p4.appendChild(document.createTextNode(' relies on the following technologies to work with the particular combination of web browser and any assistive technologies or plugins installed on your computer:'));
      output.appendChild(p4);

      appendList(output, [
        'HTML5: Semantic markup for proper document structure',
        'WAI-ARIA: Advanced accessibility attributes for complex interactions',
        'CSS3: Responsive design and accessibility-friendly styling',
        'JavaScript: Progressive enhancement for accessibility features'
      ]);

      appendEl(output, 'p', 'These technologies are relied upon for conformance with the accessibility standards used. Our website is built with progressive enhancement principles, ensuring core functionality remains available even if JavaScript is disabled.');

      // 5. Assessment approach
      appendEl(output, 'h2', 'Assessment approach');
      var p5 = document.createElement('p');
      appendBold(p5, company);
      p5.appendChild(document.createTextNode(' assessed the accessibility of '));
      appendBold(p5, url);
      p5.appendChild(document.createTextNode(' by the following approaches:'));
      output.appendChild(p5);

      appendEl(output, 'h3', 'Automated Testing');
      appendList(output, automatedList);

      appendEl(output, 'h3', 'Manual Testing');
      appendList(output, [
        'Expert accessibility reviews by certified accessibility professionals',
        'Keyboard navigation testing across all interactive elements',
        'Screen reader testing with NVDA, JAWS, VoiceOver, and TalkBack',
        'Color contrast verification meeting WCAG AA standards'
      ]);

      appendEl(output, 'h3', 'User Testing');
      appendList(output, [
        'Usability testing with people with disabilities',
        'Feedback collection from users of assistive technologies',
        'Regular accessibility user experience studies'
      ]);

      // 6. WebAbility Accessibility Widget
      var widgetTitle = brandName.trim() ? brandName.trim() + ' Accessibility Widget' : 'WebAbility Accessibility Widget';
      appendEl(output, 'h2', widgetTitle);
      var p6 = document.createElement('p');
      p6.appendChild(document.createTextNode('This website is equipped with '));
      var widgetLink = document.createElement('a');
      widgetLink.href = brandUrl.trim() || 'https://webability.io';
      widgetLink.textContent = brandName.trim() ? brandName.trim() + '\'s accessibility widget' : 'WebAbility\'s accessibility widget';
      p6.appendChild(widgetLink);
      p6.appendChild(document.createTextNode(' to provide additional assistive features that go beyond standard web accessibility requirements:'));
      output.appendChild(p6);

      // Profiles
      appendEl(output, 'h3', 'Accessibility profiles for people with disabilities');
      appendEl(output, 'p', 'Our accessibility widget includes specialized profiles designed for different types of disabilities:');
      appendList(output, [
        'Seizure Safe Profile: Eliminates flashes and reduces color that could trigger seizures',
        'Vision Impaired Profile: Enhances the website\'s visuals for users with visual impairments',
        'ADHD Friendly Profile: Reduces distractions and improves focus for users with ADHD',
        'Cognitive Disability Profile: Provides additional reading and focusing assistance',
        'Keyboard Navigation Profile: Optimizes the website for keyboard-only navigation',
        'Blind Users Profile: Optimizes the website for screen-reader compatibility'
      ]);

      // Features
      appendEl(output, 'h3', 'Additional accessibility features');
      appendEl(output, 'p', 'Additional accessibility features available through our widget:');
      appendList(output, [
        'Text Adjustments: Font size increases up to 200%, font family changes to readable fonts',
        'Color & Contrast: High contrast mode, color adjustments for colorblind users',
        'Content Highlighting: Link highlighting, button emphasis, and content structure emphasis',
        'Navigation Aids: Reading guides, rulers, and content magnification',
        'Motor Impairments: Focus indicators enhancement, click area enlargement',
        'Animation Controls: Pause animations, reduce motion for vestibular disorders'
      ]);

      // 7. Feedback
      appendEl(output, 'h2', 'Feedback');
      var p7 = document.createElement('p');
      p7.appendChild(document.createTextNode('We welcome your feedback on the accessibility of '));
      appendBold(p7, url);
      p7.appendChild(document.createTextNode('. Please let us know if you encounter accessibility barriers on our website:'));
      output.appendChild(p7);

      appendEl(output, 'p', 'Accessibility Contact Information:');
      var contactUl = document.createElement('ul');
      contactItems.forEach(function(item){
        var li = document.createElement('li');
        appendBold(li, item.label + ': ');
        if(item.href){
          var a = document.createElement('a');
          a.href = item.href;
          a.textContent = item.value;
          li.appendChild(a);
        } else {
          li.appendChild(document.createTextNode(item.value));
        }
        contactUl.appendChild(li);
      });
      output.appendChild(contactUl);

      var p7b = document.createElement('p');
      appendBold(p7b, 'Response Time: ');
      p7b.appendChild(document.createTextNode(responseTime));
      output.appendChild(p7b);

      // 8. Compatibility
      appendEl(output, 'h2', 'Compatibility with browsers and assistive technology');
      var p8 = document.createElement('p');
      appendBold(p8, url);
      p8.appendChild(document.createTextNode(' is designed to be compatible with the following assistive technologies:'));
      output.appendChild(p8);

      appendEl(output, 'h3', 'Screen Readers');
      appendList(output, [
        'NVDA (Windows) \u2014 Fully supported with regular testing',
        'JAWS (Windows) \u2014 Comprehensive compatibility and optimization',
        'VoiceOver (macOS/iOS) \u2014 Native Apple screen reader support',
        'TalkBack (Android) \u2014 Mobile accessibility optimization',
        'Dragon NaturallySpeaking \u2014 Voice recognition software compatibility'
      ]);

      appendEl(output, 'h3', 'Browsers');
      appendList(output, [
        'Recent versions of major browsers including Chrome, Firefox, Safari, and Edge',
        'Mobile browsers on iOS Safari and Android Chrome',
        'Browser zoom up to 200% without horizontal scrolling',
        'High contrast mode support across all browsers'
      ]);

      appendEl(output, 'h3', 'Other Assistive Technology');
      appendList(output, [
        'Voice recognition software (Dragon, Windows Speech Recognition)',
        'Switch navigation devices and software',
        'Eye-tracking systems and head mouse devices',
        'Alternative keyboards and input devices',
        'Magnification software (ZoomText, MAGic)'
      ]);

      // 9. Known limitations
      appendEl(output, 'h2', 'Known limitations and alternatives');
      var p9 = document.createElement('p');
      p9.appendChild(document.createTextNode('Despite our best efforts to ensure accessibility of '));
      appendBold(p9, url);
      p9.appendChild(document.createTextNode(', there may be some limitations. Below is a description of known limitations, and potential solutions. Please contact us if you observe an issue not listed below.'));
      output.appendChild(p9);

      var p9b = document.createElement('p');
      appendBold(p9b, 'Known limitations for ');
      var p9b2 = document.createElement('strong');
      p9b2.textContent = url + ':';
      p9b.appendChild(p9b2);
      output.appendChild(p9b);

      var limOl = document.createElement('ol');
      var lims = [
        {t: 'Third-party Content:', d: ' Some embedded content from third-party providers (social media widgets, videos, maps) may not be fully accessible. We work with vendors to ensure accessibility compliance.'},
        {t: 'Legacy PDF Documents:', d: ' Some older PDF documents may not be fully accessible. We are systematically reviewing and updating these documents to meet accessibility standards.'},
        {t: 'Live Content:', d: ' Real-time content such as live chat or dynamic updates may have accessibility limitations. We provide alternative methods to access this information.'}
      ];
      lims.forEach(function(lim){
        var li = document.createElement('li');
        appendBold(li, lim.t);
        li.appendChild(document.createTextNode(lim.d));
        limOl.appendChild(li);
      });
      output.appendChild(limOl);

      appendEl(output, 'p', 'What we\'re doing:');
      appendList(output, [
        'Continuous accessibility improvements and updates',
        'Regular third-party vendor accessibility reviews',
        'Proactive identification and resolution of accessibility barriers',
        'User feedback integration into our development process'
      ]);

      // 10. Compliance assessment
      appendEl(output, 'h2', 'Assessment of current compliance');
      var p10 = document.createElement('p');
      p10.appendChild(document.createTextNode('This statement was created on ' + date + ' using WebAbility\'s AI Statement Generator and manual accessibility assessment tools. The website was last reviewed for accessibility compliance on ' + date + '.'));
      output.appendChild(p10);

      appendEl(output, 'p', 'Accessibility Standards Compliance:');
      appendList(output, [
        standardText + ': \u2705 Fully Compliant',
        'Section 508: \u2705 Compliant',
        'ADA Title III: \u2705 Compliant',
        'EN 301 549: \u2705 Compliant'
      ]);

      // 11. Formal approval
      appendEl(output, 'h2', 'Formal approval of this accessibility statement');
      appendEl(output, 'p', 'This Accessibility Statement is approved by:');
      var approvalP = document.createElement('p');
      appendBold(approvalP, company);
      approvalP.appendChild(document.createElement('br'));
      appendBold(approvalP, 'Accessibility Officer');
      approvalP.appendChild(document.createElement('br'));
      approvalP.appendChild(document.createTextNode('Email: ' + email));
      approvalP.appendChild(document.createElement('br'));
      approvalP.appendChild(document.createTextNode('Date: ' + date));
      output.appendChild(approvalP);

      output.appendChild(document.createElement('hr'));

      // 12. About this statement
      appendEl(output, 'h3', 'About This Statement');
      var p12 = document.createElement('p');
      var em12 = document.createElement('em');
      em12.textContent = 'This accessibility statement was generated using WebAbility\'s Professional AI-powered accessibility statement generator on ' + date + '. This statement reflects our current accessibility features and our ongoing commitment to digital inclusion.';
      p12.appendChild(em12);
      output.appendChild(p12);

      appendEl(output, 'p', 'Statement Details:');
      appendList(output, [
        'Industry: ' + (industry || 'General Business'),
        'Language: ' + language,
        'Compliance Level: ' + standardText,
        'Next Review Date: ' + nextReviewDate
      ]);

      var poweredP = document.createElement('p');
      appendBold(poweredP, 'Powered by ');
      var poweredLink = document.createElement('a');
      poweredLink.href = brandUrl.trim() || 'https://webability.io';
      poweredLink.textContent = brandName.trim() || 'WebAbility';
      var poweredStrong = document.createElement('strong');
      poweredStrong.appendChild(poweredLink);
      poweredP.appendChild(poweredStrong);
      var poweredBold2 = document.createElement('strong');
      poweredBold2.textContent = ' \u2014 Making the web accessible for everyone.';
      poweredP.appendChild(poweredBold2);
      output.appendChild(poweredP);

      // Show actions and format tabs
      var actions = document.getElementById('wa-stmt-actions');
      if(actions) actions.style.display = 'flex';
      if(formatTabs) formatTabs.style.display = 'flex';
    });

    // Show a full, readable error/notice near the statement actions. The button
    // label truncates, so the real reason must live in its own element.
    function waShowStmtMsg(text, isError){
      var box = document.getElementById('wa-stmt-msg');
      if(!box){ return; }
      box.textContent = text;
      box.className = 'wa-stmt-msg ' + (isError ? 'wa-stmt-msg-error' : 'wa-stmt-msg-ok');
      box.style.display = 'block';
    }
    function waClearStmtMsg(){
      var box = document.getElementById('wa-stmt-msg');
      if(box){ box.style.display = 'none'; box.textContent = ''; }
    }

    // Report a statement-save failure to GlitchTip so we see these fleet-wide
    // instead of waiting for a customer to report them. NO statement content or
    // PII is sent — only a failure type, HTTP status, and a short response snippet.
    function waReportSaveFailure(failureType, detail){
      try {
        var cfg = (window.WEBABILITY_ACWG_VERIFY && WEBABILITY_ACWG_VERIFY.report) || {};
        if(!cfg.enabled || !cfg.url){ return; }
        var hex = '0123456789abcdef', eid = '';
        for(var i=0;i<32;i++){ eid += hex[(Math.random()*16)|0]; }
        var body = {
          event_id: eid,
          timestamp: new Date().toISOString(),
          platform: 'javascript',
          level: 'warning',
          logger: 'webability-wp-plugin',
          release: cfg.release,
          message: 'statement_save_failed: ' + failureType,
          tags: {
            plugin_version: WEBABILITY_ACWG_VERIFY.plugin_version,
            site_host: WEBABILITY_ACWG_VERIFY.site_host,
            wp_failure_type: failureType,
            http_status: detail && typeof detail.status !== 'undefined' ? String(detail.status) : 'n/a'
          },
          extra: detail || {}
        };
        fetch(cfg.url, { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body), keepalive:true })
          .catch(function(){ /* reporting must never throw */ });
      } catch(e){ /* never break the UI over reporting */ }
    }

    // Publish as Page
    var saveBtn = document.getElementById('wa-save-stmt');
    if(saveBtn){
      // Pull a fresh nonce from admin-ajax.php (which is never page-cached) so a
      // stale/expired nonce \u2014 the common cause of statement_save_failed: bad_nonce
      // when a caching plugin serves the admin page stale \u2014 can be healed without
      // a manual reload (reloading a cached page just returns the same dead nonce).
      // Resolves to the new nonce string, or null on failure.
      function waRefreshNonce(){
        var fd = new FormData();
        fd.append('action', 'webability_acwg_refresh_nonce');
        return fetch(WEBABILITY_ACWG_VERIFY.ajax, { method:'POST', body: fd, credentials:'same-origin' })
          .then(function(r){ return r.json(); })
          .then(function(j){
            if(j && j.success && j.data && j.data.nonce){
              WEBABILITY_ACWG_VERIFY.nonce = j.data.nonce;
              return j.data.nonce;
            }
            return null;
          })
          .catch(function(){ return null; });
      }

      function waShowSaveError(res){
        saveBtn.disabled = false;
        saveBtn.textContent = 'Publish as Page';
        var msg, failureType;
        if(res.j && res.j.data && res.j.data.msg){
          msg = res.j.data.msg;                                  // real server reason (incl. expired-nonce JSON)
          failureType = (res.j.data.code === 'bad_nonce') ? 'bad_nonce' : 'server_error';
        } else if(res.raw === '-1' || res.raw === '0'){
          // admin-ajax died without our JSON \u2014 typically an invalid/expired nonce.
          msg = 'Your session expired \u2014 please reload this page and try again.';
          failureType = 'admin_ajax_dead';
        } else {
          // Non-JSON body (e.g. a security plugin / WAF / host firewall HTML
          // error page). A raw 403 lands here too \u2014 reloading won't help.
          msg = 'Save failed (HTTP ' + res.status + '). A security or caching plugin may be blocking the request \u2014 try pausing it and saving again.';
          failureType = 'http_' + res.status;
        }
        waShowStmtMsg(msg, true);
        waReportSaveFailure(failureType, { status: res.status, snippet: (res.raw || '').slice(0, 300) });
      }

      function waPerformSave(isRetry){
        var output = document.getElementById('wa-stmt-output');
        if(!output.querySelector('h2')) return;

        waClearStmtMsg();
        saveBtn.disabled = true;
        saveBtn.textContent = 'Publishing\u2026';

        var fd = new FormData();
        fd.append('action', 'webability_acwg_save_statement');
        fd.append('nonce', WEBABILITY_ACWG_VERIFY.nonce);
        fd.append('statement', output.innerHTML);

        fetch(WEBABILITY_ACWG_VERIFY.ajax, { method:'POST', body: fd, credentials:'same-origin' })
          .then(function(r){
            // Read as text first so a non-JSON response (WAF/security-plugin HTML
            // error page, or admin-ajax "-1"/"0") doesn't get swallowed by .catch.
            return r.text().then(function(t){
              var j = null;
              try { j = JSON.parse(t); } catch(e){ /* non-JSON body */ }
              return { ok: r.ok, status: r.status, j: j, raw: t };
            });
          })
          .then(function(res){
            if(res.j && res.j.success){
              saveBtn.textContent = 'Published!';
              waShowStmtMsg('Statement published as a page.', false);
              if(res.j.data && res.j.data.url){
                setTimeout(function(){
                  saveBtn.textContent = 'View Page';
                  saveBtn.disabled = false;
                  saveBtn.onclick = function(){ window.open(res.j.data.url, '_blank'); };
                }, 1500);
              }
              return;
            }

            // A stale/expired nonce reports as our JSON {code:'bad_nonce'} (403)
            // or, if admin-ajax rejected it before our handler, a raw "-1"/"0".
            var isNonceFailure =
              (res.j && res.j.data && res.j.data.code === 'bad_nonce') ||
              res.raw === '-1' || res.raw === '0';

            // First nonce failure: silently mint a fresh nonce and retry once.
            if(isNonceFailure && !isRetry){
              waRefreshNonce().then(function(fresh){
                if(fresh){ waPerformSave(true); }
                else { waShowSaveError(res); }   // couldn't refresh \u2014 surface original error
              });
              return;
            }

            waShowSaveError(res);
          })
          .catch(function(err){
            saveBtn.disabled = false;
            saveBtn.textContent = 'Publish as Page';
            waShowStmtMsg('Could not reach the server: ' + ((err && err.message) ? err.message : 'network error') + '. Check any security/firewall plugin and try again.', true);
            waReportSaveFailure('network_error', { error: (err && err.message) ? err.message : 'network error' });
          });
      }

      saveBtn.addEventListener('click', function(){ waPerformSave(false); });
    }

    // Copy button
    var copyBtn = document.getElementById('wa-copy-stmt');
    if(copyBtn){
      copyBtn.addEventListener('click', function(){
        var output = document.getElementById('wa-stmt-output');
        var content = '';
        if(currentFormat === 'html'){
          content = output.innerHTML;
        } else if(currentFormat === 'text'){
          content = output.innerText;
        } else {
          content = htmlToMarkdown(output);
        }
        if(navigator.clipboard && window.isSecureContext){
          navigator.clipboard.writeText(content).then(function(){
            copyBtn.textContent = 'Copied!';
            setTimeout(function(){ copyBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg> Copy'; }, 2000);
          });
        } else {
          var ta = document.createElement('textarea');
          ta.value = content;
          ta.style.position = 'fixed';
          ta.style.left = '-9999px';
          document.body.appendChild(ta);
          ta.select();
          document.execCommand('copy');
          document.body.removeChild(ta);
          copyBtn.textContent = 'Copied!';
          setTimeout(function(){ copyBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg> Copy'; }, 2000);
        }
      });
    }

    // Download button
    var downloadBtn = document.getElementById('wa-download-stmt');
    if(downloadBtn){
      downloadBtn.addEventListener('click', function(){
        var output = document.getElementById('wa-stmt-output');
        var content, ext, mime;
        if(currentFormat === 'html'){
          content = output.innerHTML;
          ext = 'html'; mime = 'text/html';
        } else if(currentFormat === 'text'){
          content = output.innerText;
          ext = 'txt'; mime = 'text/plain';
        } else {
          content = htmlToMarkdown(output);
          ext = 'md'; mime = 'text/markdown';
        }
        var company = (document.getElementById('wa-stmt-company') || {}).value || 'accessibility';
        var blob = new Blob([content], {type: mime});
        var a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = company.replace(/[^a-z0-9]/gi, '-').toLowerCase() + '-statement.' + ext;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(a.href);
      });
    }
  }

  function appendEl(parent, tag, text){
    var el = document.createElement(tag);
    el.textContent = text;
    parent.appendChild(el);
  }
  function appendBold(parent, text){
    var b = document.createElement('strong');
    b.textContent = text;
    parent.appendChild(b);
  }
  function appendList(parent, items){
    var ul = document.createElement('ul');
    items.forEach(function(item){
      var li = document.createElement('li');
      // Split on first colon for bold label pattern (e.g. "Label: description")
      var colonIdx = item.indexOf(':');
      if(colonIdx > 0 && colonIdx < 40){
        appendBold(li, item.substring(0, colonIdx + 1));
        li.appendChild(document.createTextNode(item.substring(colonIdx + 1)));
      } else {
        li.textContent = item;
      }
      ul.appendChild(li);
    });
    parent.appendChild(ul);
  }
  function htmlToMarkdown(el){
    var md = '';
    el.childNodes.forEach(function(node){
      if(node.nodeType === 3){ md += node.textContent; return; }
      var tag = (node.tagName || '').toLowerCase();
      if(tag === 'h1') md += '# ' + node.textContent + '\n\n';
      else if(tag === 'h2') md += '## ' + node.textContent + '\n\n';
      else if(tag === 'h3') md += '### ' + node.textContent + '\n\n';
      else if(tag === 'hr') md += '---\n\n';
      else if(tag === 'p') md += node.textContent + '\n\n';
      else if(tag === 'ul'){
        node.querySelectorAll('li').forEach(function(li){
          md += '- ' + li.textContent.trim() + '\n';
        });
        md += '\n';
      } else if(tag === 'ol'){
        var i = 1;
        node.querySelectorAll('li').forEach(function(li){
          md += i + '. ' + li.textContent.trim() + '\n';
          i++;
        });
        md += '\n';
      } else {
        md += node.textContent;
      }
    });
    return md.trim();
  }
})();
