/* ───── Services & Pricing section + Booking / payment modal ─────
   Both render from window.SITE (see services.js — single source). */

const fmtPrice = (n) => `${window.SITE.currency}${n}`;

/* The pricing UI — themed cards grouped by category. Each item carries
   its name + price forward to the booking modal via onSelect. */
const Services = ({ onSelect }) => {
  const { serviceGroups } = window.SITE;
  return (
    <section className="services" id="pricing" data-screen-label="05 Services & Pricing">
      <div className="section-head">
        <div className="rp-eyebrow">Services &amp; Pricing</div>
        <h2 className="section-title">
          Sit down, <span className="serif-italic">choose your reading.</span>
        </h2>
        <p className="section-sub">
          Pick a service, pay by UPI or Paytm, then send your payment screenshot
          on WhatsApp to confirm your booking.
        </p>
      </div>

      <div className="svc-groups">
        {serviceGroups.map((g, gi) => (
          <div className="svc-group" key={gi}>
            <div className="svc-group-head">
              <h3 className="svc-group-title">{g.group}</h3>
              {g.blurb && <p className="svc-group-blurb">{g.blurb}</p>}
            </div>
            <div className="item-list svc-list">
              {g.items.map((s, i) => (
                <div className="item svc-item" key={i}>
                  <div className="svc-item-main">
                    <div className="item-head">{s.name}</div>
                    <div className="item-desc">{s.desc}</div>
                  </div>
                  <div className="svc-price">{fmtPrice(s.price)}</div>
                  <button
                    type="button"
                    className="svc-book"
                    onClick={() => onSelect(s)}
                    aria-label={`Book ${s.name} for ${fmtPrice(s.price)}`}
                  >
                    Book
                  </button>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
};

/* Booking / payment modal — shows UPI QR + Paytm, then a pre-filled
   WhatsApp deep link carrying the chosen service + price. */
const BookingModal = ({ service, onClose }) => {
  React.useEffect(() => {
    if (!service) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [service, onClose]);

  if (!service) return null;

  const { payment } = window.SITE;
  const priceLabel = fmtPrice(service.price);
  const waText = `Hi, I booked ${service.name} (${priceLabel}), sharing my payment screenshot.`;
  const waHref = `https://wa.me/${payment.whatsapp}?text=${encodeURIComponent(waText)}`;

  // Build the UPI pay QR live (pre-fills payee + exact amount). Falls back to
  // the optional payment.qr image if the QR library isn't available.
  let qrSrc = payment.qr;
  if (payment.upiId && typeof window.qrcode === "function") {
    try {
      const upiStr =
        `upi://pay?pa=${payment.upiId}` +
        `&pn=${encodeURIComponent(payment.upiName || "")}` +
        `&am=${service.price}&cu=INR&tn=${encodeURIComponent(service.name)}`;
      const qr = window.qrcode(0, "M");
      qr.addData(upiStr);
      qr.make();
      qrSrc = qr.createDataURL(6, 12);
    } catch (e) { /* keep image fallback */ }
  }

  return (
    <div
      className="booking-modal"
      role="dialog"
      aria-modal="true"
      aria-label="Confirm your booking"
      onClick={onClose}
    >
      <div className="booking-card" onClick={(e) => e.stopPropagation()}>
        <button type="button" className="booking-close" aria-label="Close" onClick={onClose}>
          ×
        </button>

        <div className="rp-eyebrow">Confirm your booking</div>
        <h3 className="booking-svc">{service.name}</h3>
        <div className="booking-price">{priceLabel}</div>
        {service.desc && <p className="booking-desc">{service.desc}</p>}

        <div className="booking-pay">
          <figure className="booking-qr">
            <img
              src={qrSrc}
              alt={`UPI QR code — scan to pay ${priceLabel} for ${service.name}`}
              onError={(e) => { e.currentTarget.style.display = "none"; }}
            />
            <figcaption className="booking-qr-cap">Scan with any UPI app to pay {priceLabel}</figcaption>
          </figure>

          {payment.upiId && (
            <div className="booking-upi">
              <span className="booking-upi-label">UPI ID</span>
              <span className="booking-upi-id">{payment.upiId}</span>
            </div>
          )}

          <div className="booking-paytm">
            <span className="booking-paytm-label">or pay on Paytm</span>
            <span className="booking-paytm-num">{payment.paytm}</span>
          </div>
        </div>

        <ol className="booking-steps">
          <li>Pay <strong>{priceLabel}</strong> using the QR code or Paytm number above.</li>
          <li>Take a screenshot of the successful payment.</li>
          <li>Tap the button below and send the screenshot on WhatsApp to confirm.</li>
        </ol>

        <a className="btn-primary booking-wa" href={waHref} target="_blank" rel="noopener">
          Confirm on WhatsApp
        </a>
      </div>
    </div>
  );
};

Object.assign(window, { Services, BookingModal });
