(() => {
  'use strict';
  const message = document.querySelector('#checkout-message');
  const container = document.querySelector('#paypal-button-container');
  const checkout = document.querySelector('#checkout');
  const sticky = document.querySelector('#sticky-buy');

  function setMessage(text, type = '') {
    if (!message) return;
    message.textContent = text;
    message.className = `checkout-message ${type}`.trim();
  }

  document.querySelectorAll('.scroll-checkout').forEach((button) => {
    button.addEventListener('click', () => {
      checkout?.scrollIntoView({ behavior: 'smooth', block: 'center' });
      setTimeout(() => container?.querySelector('button')?.focus(), 700);
    });
  });

  if (sticky && checkout) {
    const observer = new IntersectionObserver(([entry]) => {
      sticky.classList.toggle('visible', !entry.isIntersecting && window.scrollY > 500);
    }, { threshold: 0.1 });
    observer.observe(checkout);
  }

  async function fetchJson(url, options = {}) {
    const response = await fetch(url, {
      ...options,
      headers: { 'Content-Type': 'application/json', ...(options.headers || {}) }
    });
    const data = await response.json().catch(() => ({ ok: false, error: 'Unexpected server response.' }));
    if (!response.ok || data.ok === false) throw new Error(data.error || 'Request failed.');
    return data;
  }

  function renderMockButton() {
    container.innerHTML = '<button class="primary-button" id="mock-paypal" type="button" style="width:100%">Complete mock PayPal payment</button>';
    document.querySelector('#mock-paypal').addEventListener('click', async () => {
      try {
        setMessage('Creating secure test order...');
        const created = await fetchJson('/api/paypal/create-order', { method: 'POST', body: '{}' });
        setMessage('Approving and verifying test payment...');
        const captured = await fetchJson('/api/paypal/capture-order', { method: 'POST', body: JSON.stringify({ orderID: created.id }) });
        sessionStorage.setItem('mpcDownloadToken', captured.downloadToken);
        sessionStorage.setItem('mpcDownloadExpiresAt', captured.expiresAt);
        window.location.assign('/success');
      } catch (error) {
        setMessage(error.message, 'error');
      }
    });
  }

  async function initializeCheckout() {
    try {
      setMessage('Loading secure checkout...');
      const store = await fetchJson('/api/config');
      if (store.paypalEnv === 'mock') {
        setMessage('Controlled test checkout is active.');
        renderMockButton();
        return;
      }
      if (!store.paypalClientId) throw new Error('PayPal checkout is not configured.');
      const script = document.createElement('script');
      script.src = `https://www.paypal.com/sdk/js?client-id=${encodeURIComponent(store.paypalClientId)}&currency=${encodeURIComponent(store.product.currency)}&intent=capture&components=buttons`;
      script.async = true;
      script.onload = () => {
        if (!window.paypal?.Buttons) return setMessage('PayPal checkout could not load. Please refresh or contact support.', 'error');
        window.paypal.Buttons({
          style: { layout: 'vertical', color: 'gold', shape: 'rect', label: 'buynow', height: 48 },
          async createOrder() {
            setMessage('Opening secure PayPal checkout...');
            const data = await fetchJson('/api/paypal/create-order', { method: 'POST', body: '{}' });
            return data.id;
          },
          async onApprove(data) {
            setMessage('Payment approved. Verifying and preparing your download...');
            const result = await fetchJson('/api/paypal/capture-order', {
              method: 'POST',
              body: JSON.stringify({ orderID: data.orderID })
            });
            sessionStorage.setItem('mpcDownloadToken', result.downloadToken);
            sessionStorage.setItem('mpcDownloadExpiresAt', result.expiresAt);
            window.location.assign('/success');
          },
          onCancel() { setMessage('Checkout was cancelled. No payment was completed.'); },
          onError(error) {
            console.error(error);
            setMessage('PayPal checkout did not complete. Please try again or contact support.', 'error');
          }
        }).render('#paypal-button-container').then(() => setMessage('Secure checkout ready.'));
      };
      script.onerror = () => setMessage('PayPal could not load. Check your connection and try again.', 'error');
      document.head.appendChild(script);
    } catch (error) {
      setMessage(error.message, 'error');
    }
  }

  initializeCheckout();
})();
