'use client';

/**
 * ============================================
 * SHOP PAGE MODAL
 * ============================================
 * Opens a Shopware "shop page" (GTC / revocation / privacy / imprint) CMS page
 * in a popup, mirroring the way the default storefront shows the Terms of
 * service on the checkout confirm page.
 *
 * Content is fetched from /api/shop-page (which reads the configured CMS page
 * id via the Admin API and loads it over the Store API).
 */

import { useEffect, useState } from 'react';

type ShopPageKey = 'tos' | 'revocation' | 'privacy' | 'imprint' | 'shippingPayment';

interface ShopPageModalProps {
  open: boolean;
  pageKey: ShopPageKey;
  /** Heading shown while loading / if the page has no name. */
  fallbackTitle?: string;
  onClose: () => void;
}

interface PageState {
  loading: boolean;
  title?: string;
  html?: string | null;
}

export default function ShopPageModal({
  open,
  pageKey,
  fallbackTitle,
  onClose,
}: ShopPageModalProps) {
  const [state, setState] = useState<PageState>({ loading: true });

  // Fetch content whenever the modal opens (or the requested page changes)
  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setState({ loading: true });
    fetch(`/api/shop-page?key=${pageKey}`)
      .then((r) => r.json())
      .then((d) => {
        if (!cancelled) setState({ loading: false, title: d.title, html: d.html });
      })
      .catch(() => {
        if (!cancelled) setState({ loading: false, html: null });
      });
    return () => {
      cancelled = true;
    };
  }, [open, pageKey]);

  // Escape to close + lock body scroll while open
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-[70] flex items-start justify-center overflow-y-auto bg-black/40 px-4 py-10"
      onClick={onClose}
    >
      <div
        className="relative w-full max-w-2xl bg-white rounded-xl shadow-xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Close button */}
        <button
          type="button"
          onClick={onClose}
          aria-label="Close"
          className="absolute top-4 right-4 text-surface-400 hover:text-surface-700 transition-colors"
        >
          <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>

        <div className="px-8 py-8">
          {state.loading ? (
            <div className="flex items-center gap-3 text-surface-500 py-8">
              <svg className="w-5 h-5 animate-spin" viewBox="0 0 24 24" fill="none">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
              Loading…
            </div>
          ) : state.html ? (
            <div
              className="prose prose-sm max-w-none text-surface-700 max-h-[60vh] overflow-y-auto pr-2"
              dangerouslySetInnerHTML={{ __html: state.html }}
            />
          ) : (
            <p className="text-sm text-surface-500 py-4">
              This content is not available. Please contact us if you have any questions.
            </p>
          )}
        </div>
      </div>
    </div>
  );
}
