/**
 * NadiPlayer — nadi.kr/nadiplayer/ activation front-end glue.
 *
 * Wire-up:
 *   1. User picks a plan + types their email.
 *   2. Your payment widget fires on "paid" — replace the stub inside
 *      #pay-btn handler with the real hook (Stripe checkout.session.completed,
 *      PayPal onApprove, crypto confirm, etc.).
 *   3. Once paid, POST /api/signup.php with:
 *        header X-Signup-Secret: <SIGNUP_SECRET from api/config.php>
 *        body   { plan, email, payment_ref }
 *   4. The endpoint returns { username, password, expiry_at } and we show
 *      them to the buyer. Email is OPTIONAL on the server side — plug in
 *      your own mailer (sendgrid, PHPMailer, cron) inside signup.php.
 *
 * SECURITY WARNING:
 *   Do NOT ship the SIGNUP_SECRET to the browser.  The fetch() below is
 *   expected to run server-side (e.g. from your payment webhook) with
 *   the secret attached.  The HTML form here is a demo; in production
 *   you'd redirect the user to a "thank-you" page that POSTs to your
 *   server, which in turn POSTs to /api/signup.php with the secret.
 *
 *   For a lightweight all-client flow, turn off the shared-secret check
 *   (remove the `hash_equals` line in signup.php) and add a reCAPTCHA
 *   step instead.
 */

(function () {
  "use strict";

  var plans = document.querySelectorAll(".plan");
  var payBtn = document.getElementById("pay-btn");
  var stepPlan = document.getElementById("step-plan");
  var stepSuccess = document.getElementById("step-success");
  var errBox = document.getElementById("err");
  var yearEl = document.getElementById("year");
  yearEl.textContent = String(new Date().getFullYear());

  // --- plan picker ---
  var selectedPlan = "yearly";
  plans.forEach(function (p) {
    p.addEventListener("click", function () {
      plans.forEach(function (x) { x.classList.remove("active"); });
      p.classList.add("active");
      selectedPlan = p.getAttribute("data-plan");
    });
  });

  // --- copy buttons ---
  document.querySelectorAll(".copy").forEach(function (b) {
    b.addEventListener("click", function () {
      var target = document.getElementById(b.getAttribute("data-copy"));
      if (!target) return;
      navigator.clipboard.writeText(target.textContent.trim());
      var old = b.textContent;
      b.textContent = "Copied";
      setTimeout(function () { b.textContent = old; }, 1200);
    });
  });

  // --- signup trigger ---
  payBtn.addEventListener("click", async function () {
    errBox.classList.add("hidden");
    var email = document.getElementById("email").value.trim();
    if (!email || email.indexOf("@") === -1) {
      errBox.textContent = "Please enter a valid email address.";
      errBox.classList.remove("hidden");
      return;
    }

    payBtn.disabled = true;
    payBtn.textContent = "Processing…";

    try {
      // ═══════════════════════════════════════════════════════════════
      // TODO: replace this stub with your real payment provider call.
      // For Stripe:  window.location = stripeCheckoutUrl;
      // For PayPal:  paypal.Buttons().render(...)
      // After payment success → POST /api/signup.php from your SERVER
      // with the X-Signup-Secret header.  The code below is only for
      // local dev / demo purposes and assumes a proxy that injects the
      // secret header (e.g. via a reverse-proxy rule on nadi.kr).
      // ═══════════════════════════════════════════════════════════════
      var res = await fetch("api/signup.php", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          // In production this header must be injected server-side —
          // NEVER put the real secret in public JavaScript.
          "X-Signup-Secret": window.__NADI_SIGNUP_SECRET || "demo-secret",
        },
        body: JSON.stringify({
          plan: selectedPlan,
          email: email,
          payment_ref: "demo-" + Date.now(),
        }),
      });

      var data = await res.json();
      if (!res.ok || !data.ok) {
        throw new Error(data.error || "Signup failed");
      }

      // Show success panel
      document.getElementById("out-username").textContent = data.username;
      document.getElementById("out-password").textContent = data.password;
      document.getElementById("out-plan").textContent = data.plan + " · " + data.days + " days";
      document.getElementById("out-expiry").textContent =
        "expires " + new Date(data.expiry_at).toLocaleDateString();

      stepPlan.classList.add("hidden");
      stepSuccess.classList.remove("hidden");
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (e) {
      errBox.textContent = e.message || "Something went wrong. Please try again.";
      errBox.classList.remove("hidden");
    } finally {
      payBtn.disabled = false;
      payBtn.textContent = "Continue to payment →";
    }
  });
})();
