/* Campus Gridiron - VIP Gate
   - Locks UI for VIP-only areas (disabled/readonly style)
   - Provides a consistent "VIP required" message + upgrade CTA
   - Future-proof: swap vipActive() implementation later for server verification
*/
(function () {
  "use strict";

  // ---- CONFIG: paste your Stripe Payment Link URLs here (TEST links for now) ----
  // These should be the same links your modal uses today.
  const VIP_LINKS = {
    monthly: "PASTE_YOUR_MONTHLY_PAYMENT_LINK_HERE",
    days90:  "PASTE_YOUR_90_DAY_PAYMENT_LINK_HERE",
    yearly:  "PASTE_YOUR_YEARLY_PAYMENT_LINK_HERE",
  };

  // Optional: lock targets by selector WITHOUT editing HTML.
  // If you prefer attribute-based locking instead, leave this empty.
  // Example:
  // const LOCK_SELECTORS = ["#advancedScoutingPanel", "#recruitingTools", ".vip-only"];
  const LOCK_SELECTORS = [];

  // Attribute-based locking (recommended): add data-vip="required" to containers
  // Optional per-element mode: data-vip-mode="disabled" (default) | "readonly" | "hidden"
  const ATTR_SELECTOR = '[data-vip="required"]';

  // ---- VIP status (TEST MODE right now) ----
  // Later you’ll replace this function to call /api/vip/status
  function vipActive() {
    try {
      // honors your existing test simulation: localStorage cgVip = "1" enables VIP
      return localStorage.getItem("cgVip") === "1";
    } catch (e) {
      return false;
    }
  }

  // ---- UI helpers ----
  function ensureOverlay() {
    let overlay = document.getElementById("cgVipOverlay");
    if (overlay) return overlay;

    overlay = document.createElement("div");
    overlay.id = "cgVipOverlay";
    overlay.className = "cg-vip-overlay";
    overlay.innerHTML = `
      <div class="cg-vip-dialog" role="dialog" aria-modal="true" aria-labelledby="cgVipTitle">
        <header>
          <div>
            <h3 id="cgVipTitle">VIP required</h3>
            <div style="margin-top:8px;">
              <span class="cg-vip-badge"><strong>VIP</strong> feature locked</span>
            </div>
          </div>
          <button class="close" type="button" aria-label="Close">✕</button>
        </header>
        <div class="body">
          <div id="cgVipMsg">
            This tool is available to VIP members. Choose a plan below to unlock it.
          </div>

          <div class="plans" style="margin-top: 14px;">
            <div class="plan">
              <div class="title">
                <strong>Monthly</strong>
                <small>$3.99</small>
              </div>
              <button class="cg-vip-cta-btn" type="button" data-plan="monthly">Go VIP (Monthly)</button>
            </div>

            <div class="plan">
              <div class="title">
                <strong>90 Days</strong>
                <small>$10.99</small>
              </div>
              <button class="cg-vip-cta-btn" type="button" data-plan="days90">Go VIP (90 Days)</button>
            </div>

            <div class="plan year">
              <div class="title">
                <strong>Yearly</strong>
                <small>$39.99</small>
              </div>
              <button class="cg-vip-cta-btn" type="button" data-plan="yearly">Go VIP (Yearly)</button>
            </div>
          </div>
        </div>
        <footer>
          <button class="cg-vip-secondary" type="button" data-action="close">Not now</button>
        </footer>
      </div>
    `;
    document.body.appendChild(overlay);

    overlay.addEventListener("click", (e) => {
      if (e.target === overlay) closeOverlay();
    });

    overlay.querySelectorAll('[data-action="close"], .close').forEach(btn => {
      btn.addEventListener("click", closeOverlay);
    });

    overlay.querySelectorAll("[data-plan]").forEach(btn => {
      btn.addEventListener("click", () => {
        const plan = btn.getAttribute("data-plan");
        const url = VIP_LINKS[plan];
        if (!url || url.includes("PASTE_YOUR_")) {
          alert("VIP link not configured yet. Paste your Stripe Payment Link URLs in /app/js/vip-gate.js (VIP_LINKS).");
          return;
        }
        window.location.href = url;
      });
    });

    document.addEventListener("keydown", (e) => {
      if (e.key === "Escape") closeOverlay();
    });

    return overlay;
  }

  function openOverlay(message) {
    const overlay = ensureOverlay();
    const msg = overlay.querySelector("#cgVipMsg");
    if (msg && message) msg.textContent = message;
    overlay.classList.add("is-open");
  }

  function closeOverlay() {
    const overlay = document.getElementById("cgVipOverlay");
    if (overlay) overlay.classList.remove("is-open");
  }

  // ---- Locking behavior ----
  function applyLock(el, mode) {
    const m = (mode || el.getAttribute("data-vip-mode") || "disabled").toLowerCase();

    if (m === "hidden") {
      el.style.display = "none";
      return;
    }

    // default: disabled-style overlay lock
    el.classList.add("cg-vip-locked");

    // For readonly mode: allow scrolling/selection, but prevent edits/click actions
    if (m === "readonly") {
      el.classList.remove("cg-vip-locked");

      // Disable interactive controls (but keep visible)
      el.querySelectorAll("input, select, textarea, button").forEach(ctrl => {
        if (ctrl.tagName === "INPUT" || ctrl.tagName === "TEXTAREA") {
          ctrl.setAttribute("readonly", "readonly");
        } else {
          ctrl.setAttribute("disabled", "disabled");
        }
      });

      // Prevent link/button actions and show VIP overlay
      el.addEventListener("click", (e) => {
        const t = e.target.closest("a, button, [role='button'], input, select, textarea");
        if (!t) return;
        e.preventDefault();
        e.stopPropagation();
        openOverlay(el.getAttribute("data-vip-message") || "This feature is VIP-only. Choose a plan to unlock it.");
      }, true);
      return;
    }

    // disabled mode: block clicks via overlay, but we still want a clickable “gate”
    // So we add a capturing click handler on the container itself.
    el.addEventListener("click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      openOverlay(el.getAttribute("data-vip-message") || "This feature is VIP-only. Choose a plan to unlock it.");
    }, true);
  }

  function unlock(el) {
    el.style.display = "";
    el.classList.remove("cg-vip-locked");
    // We intentionally do NOT try to “re-enable” fields here because dashboard logic likely controls that.
    // VIP UI unlock should be driven by your existing CG.vip methods/UI rules.
  }

  function gateAll() {
    const isVip = vipActive();

    const attrTargets = Array.from(document.querySelectorAll(ATTR_SELECTOR));
    const selectorTargets = LOCK_SELECTORS.flatMap(sel => Array.from(document.querySelectorAll(sel)));
    const targets = Array.from(new Set([...attrTargets, ...selectorTargets]));

    targets.forEach(el => {
      if (isVip) unlock(el);
      else applyLock(el);
    });
  }

  // Public hook (for your existing “Reset VIP (test)” button or future toggles)
  window.CG = window.CG || {};
  window.CG.vipGate = {
    refresh: gateAll,
    requireVip: (message) => {
      if (vipActive()) return true;
      openOverlay(message || "This feature is VIP-only. Choose a plan to unlock it.");
      return false;
    }
  };

  document.addEventListener("DOMContentLoaded", gateAll);

  // If your existing test tools change localStorage at runtime, you can call:
  // window.CG.vipGate.refresh();
})();
