<?php
// ─────────────────────────────────────────────────────────────
//  plans.php — Public membership plans page
// ─────────────────────────────────────────────────────────────
require_once __DIR__ . '/lib.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"/>
<title>Membership Plans</title>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Syne:wght@600;700;800&family=DM+Sans:opsz,wght@9..40,300;9..40,400;9..40,500;9..40,600&display=swap" rel="stylesheet"/>
<style>
*{box-sizing:border-box;margin:0;padding:0}
:root{
  --bg:#f4f5f7;--surface:#ffffff;--card-alt:#f8f9fb;
  --border:#e8eaed;--border-hi:#d1d5db;
  --accent:#e09500;--accent-hi:#f5a623;--accent-d:#b87800;
  --accent-pale:#fff8eb;--accent-glow:rgba(224,149,0,0.18);
  --accent-border:rgba(224,149,0,0.3);
  --green:#16a34a;--green-pale:#f0fdf4;--green-border:#bbf7d0;
  --red:#dc2626;--red-pale:#fef2f2;--red-border:#fecaca;
  --text:#111827;--text-2:#4b5563;--text-3:#9ca3af;
  --font-display:'Syne',sans-serif;
  --font-body:'DM Sans',sans-serif;
  --font-mono:'DM Mono',monospace;
}
html,body{
  min-height:100vh;background:var(--bg);color:var(--text);
  font-family:var(--font-body);-webkit-font-smoothing:antialiased;
  font-size:14px;line-height:1.6;
  padding-bottom:env(safe-area-inset-bottom,0px);
}
button,input,select{font-family:inherit}
a{text-decoration:none;color:inherit}

/* ── Hero ── */
.hero{
  background:linear-gradient(135deg,var(--accent-hi) 0%,var(--accent-d) 100%);
  padding:48px 20px 60px;text-align:center;color:#fff;
  position:relative;overflow:hidden;
}
.hero::before{
  content:'';position:absolute;width:400px;height:400px;border-radius:50%;
  background:rgba(255,255,255,0.06);top:-100px;right:-80px;pointer-events:none;
}
.hero::after{
  content:'';position:absolute;width:300px;height:300px;border-radius:50%;
  background:rgba(255,255,255,0.04);bottom:-80px;left:-60px;pointer-events:none;
}
.hero-brand{
  display:inline-flex;align-items:center;gap:8px;
  font-family:var(--font-mono);font-size:11px;font-weight:500;
  letter-spacing:.14em;text-transform:uppercase;
  color:rgba(255,255,255,0.7);margin-bottom:20px;
}
.hero-brand-dot{width:6px;height:6px;border-radius:50%;background:rgba(255,255,255,0.7)}
.hero h1{
  font-family:var(--font-display);font-size:clamp(26px,5vw,40px);font-weight:800;
  margin-bottom:14px;line-height:1.15;
}
.hero p{
  font-size:15px;color:rgba(255,255,255,0.85);max-width:500px;
  margin:0 auto 28px;line-height:1.7;font-weight:300;
}
.hero-back{
  display:inline-flex;align-items:center;gap:6px;
  position:absolute;top:16px;left:16px;
  font-size:13px;font-weight:600;color:rgba(255,255,255,0.85);
  background:rgba(255,255,255,0.12);
  padding:6px 12px;border-radius:20px;
  transition:background .15s;
}
.hero-back:hover{background:rgba(255,255,255,0.2)}
.hero-back svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}

/* ── Plans grid ── */
.plans-wrap{max-width:960px;margin:-32px auto 0;padding:0 16px 60px;position:relative;z-index:1}
.plans-grid{
  display:grid;
  grid-template-columns:repeat(auto-fill,minmax(280px,1fr));
  gap:20px;margin-bottom:32px;
}
.plan-card{
  background:var(--surface);border:2px solid var(--border);
  border-radius:18px;padding:28px;
  transition:all .2s;position:relative;overflow:hidden;
}
.plan-card:hover{
  border-color:var(--accent);
  box-shadow:0 8px 32px var(--accent-glow);transform:translateY(-3px);
}
.plan-card.featured{
  border-color:var(--accent);
  box-shadow:0 4px 24px var(--accent-glow);
}
.plan-featured-badge{
  position:absolute;top:0;right:0;
  background:linear-gradient(135deg,var(--accent-hi),var(--accent-d));
  color:#fff;font-family:var(--font-mono);font-size:9px;font-weight:500;
  text-transform:uppercase;letter-spacing:.08em;
  padding:5px 14px;border-radius:0 16px 0 12px;
}
.plan-color-bar{
  width:36px;height:4px;border-radius:2px;margin-bottom:16px;
}
.plan-name{
  font-family:var(--font-display);font-size:20px;font-weight:800;
  color:var(--text);margin-bottom:6px;
}
.plan-desc{
  font-size:13px;color:var(--text-2);margin-bottom:18px;
  line-height:1.6;font-weight:300;min-height:40px;
}
.plan-price-row{
  display:flex;align-items:baseline;gap:4px;margin-bottom:6px;
}
.plan-currency{font-size:18px;font-weight:600;color:var(--text-2);align-self:flex-start;margin-top:6px}
.plan-amount{font-family:var(--font-display);font-size:40px;font-weight:800;color:var(--text);line-height:1}
.plan-period{font-size:13px;color:var(--text-3);font-weight:400}
.plan-duration{
  font-family:var(--font-mono);font-size:10px;color:var(--text-3);
  text-transform:uppercase;letter-spacing:.07em;
  margin-bottom:20px;
  display:flex;align-items:center;gap:5px;
}
.plan-duration svg{width:11px;height:11px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
.plan-divider{height:1px;background:var(--border);margin:18px 0}
.plan-services-label{
  font-family:var(--font-mono);font-size:9px;font-weight:500;
  text-transform:uppercase;letter-spacing:.1em;color:var(--text-3);
  margin-bottom:10px;
}
.plan-services{list-style:none;margin-bottom:22px}
.plan-services li{
  display:flex;align-items:center;gap:8px;
  font-size:13px;color:var(--text-2);padding:5px 0;
}
.plan-services li::before{
  content:'';width:16px;height:16px;border-radius:50%;
  background:var(--green-pale);border:1px solid var(--green-border);
  display:flex;align-items:center;justify-content:center;
  flex-shrink:0;font-size:9px;line-height:16px;text-align:center;
  background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpolyline points='20 6 9 17 4 12' stroke='%2316a34a' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round' fill='none'/%3E%3C/svg%3E");
  background-size:10px;background-repeat:no-repeat;background-position:center;
}
.plan-services li .svc-duration{
  margin-left:auto;font-family:var(--font-mono);font-size:10px;
  color:var(--text-3);flex-shrink:0;
}
.btn-plan{
  width:100%;padding:13px;border-radius:12px;
  font-family:var(--font-display);font-size:14px;font-weight:700;
  border:none;cursor:pointer;transition:all .15s;
  background:linear-gradient(135deg,var(--accent-hi),var(--accent-d));
  color:#fff;box-shadow:0 2px 12px var(--accent-glow);
}
.btn-plan:hover{opacity:.92;transform:translateY(-1px);box-shadow:0 4px 18px var(--accent-glow)}
.btn-plan:active{transform:none}
.btn-plan:disabled{opacity:.55;cursor:not-allowed;transform:none}
.plan-spinner{display:inline-block;width:14px;height:14px;border:2px solid rgba(255,255,255,.4);border-top-color:#fff;border-radius:50%;animation:spin .7s linear infinite;vertical-align:middle;margin-right:5px}
@keyframes spin{to{transform:rotate(360deg)}}

/* ── FAQ / Info section ── */
.info-section{
  background:var(--surface);border:1px solid var(--border);
  border-radius:18px;padding:28px;margin-bottom:20px;
}
.info-title{font-family:var(--font-display);font-size:18px;font-weight:800;color:var(--text);margin-bottom:18px}
.faq-item{border-bottom:1px solid var(--border);padding:14px 0}
.faq-item:last-child{border-bottom:none;padding-bottom:0}
.faq-q{font-size:14px;font-weight:600;color:var(--text);margin-bottom:6px;cursor:pointer;display:flex;align-items:center;justify-content:space-between;gap:10px}
.faq-q svg{width:16px;height:16px;stroke:var(--text-3);fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0;transition:transform .2s}
.faq-item.open .faq-q svg{transform:rotate(180deg)}
.faq-a{font-size:13px;color:var(--text-2);line-height:1.7;display:none}
.faq-item.open .faq-a{display:block}

/* ── Already a member CTA ── */
.member-cta{
  background:var(--accent-pale);border:1px solid var(--accent-border);
  border-radius:14px;padding:20px 22px;
  display:flex;align-items:center;gap:14px;flex-wrap:wrap;
}
.member-cta-icon{
  width:40px;height:40px;border-radius:10px;
  background:linear-gradient(135deg,var(--accent-hi),var(--accent-d));
  display:flex;align-items:center;justify-content:center;flex-shrink:0;
}
.member-cta-icon svg{width:18px;height:18px;stroke:#fff;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
.member-cta-text{flex:1;min-width:160px}
.member-cta-title{font-family:var(--font-display);font-size:15px;font-weight:700;color:var(--text);margin-bottom:2px}
.member-cta-sub{font-size:12px;color:var(--text-2)}
.btn-cta{
  padding:10px 20px;border-radius:10px;
  font-size:13px;font-weight:700;border:none;cursor:pointer;
  background:var(--accent);color:#fff;
  transition:opacity .15s;flex-shrink:0;
  font-family:var(--font-body);
}
.btn-cta:hover{opacity:.9}

/* ── Checkout modal ── */
.checkout-overlay{
  position:fixed;inset:0;background:rgba(17,24,39,.4);
  backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);
  z-index:200;display:flex;align-items:flex-end;justify-content:center;
  opacity:0;pointer-events:none;transition:opacity .2s;
}
.checkout-overlay.open{opacity:1;pointer-events:all}
.checkout-sheet{
  background:var(--surface);border-radius:20px 20px 0 0;
  width:100%;max-width:520px;padding:28px;
  transform:translateY(100%);transition:transform .28s cubic-bezier(.34,1.56,.64,1);
  box-shadow:0 -4px 32px rgba(0,0,0,.12);
}
.checkout-overlay.open .checkout-sheet{transform:translateY(0)}
.checkout-handle{width:36px;height:4px;background:var(--border);border-radius:2px;margin:0 auto 22px}
.checkout-title{font-family:var(--font-display);font-size:18px;font-weight:800;color:var(--text);margin-bottom:4px}
.checkout-plan{font-size:13px;color:var(--text-2);margin-bottom:22px}
.checkout-price{
  font-family:var(--font-display);font-size:28px;font-weight:800;
  color:var(--accent);margin-bottom:20px;
}
.fg{margin-bottom:14px}
.fg label{display:block;font-size:11px;font-weight:600;color:var(--text-2);text-transform:uppercase;letter-spacing:.07em;margin-bottom:5px}
.fg input{
  width:100%;background:var(--bg);border:1.5px solid var(--border-hi);
  border-radius:10px;padding:12px 14px;font-size:15px;color:var(--text);
  outline:none;transition:border .15s;
}
.fg input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-pale)}
.fg input::placeholder{color:var(--text-3)}
.btn-checkout{
  width:100%;padding:14px;border-radius:12px;
  font-family:var(--font-display);font-size:15px;font-weight:700;
  border:none;cursor:pointer;
  background:linear-gradient(135deg,var(--accent-hi),var(--accent-d));
  color:#fff;box-shadow:0 2px 12px var(--accent-glow);
  transition:opacity .15s,transform .15s;
}
.btn-checkout:hover{opacity:.92;transform:translateY(-1px)}
.btn-checkout:disabled{opacity:.55;cursor:not-allowed;transform:none}
.checkout-secure{
  display:flex;align-items:center;justify-content:center;gap:6px;
  margin-top:12px;font-size:11px;color:var(--text-3);
  font-family:var(--font-mono);
}
.checkout-secure svg{width:12px;height:12px;stroke:var(--text-3);fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
.checkout-cancel{
  display:block;text-align:center;margin-top:10px;
  font-size:12px;color:var(--text-3);cursor:pointer;background:none;border:none;width:100%;
}
.checkout-cancel:hover{color:var(--text-2)}

/* ── Loading / empty ── */
.loading-block{display:flex;align-items:center;justify-content:center;padding:60px 20px;gap:10px;color:var(--text-3)}
.loading-block .spinner{width:22px;height:22px;border:2px solid var(--accent-pale);border-top-color:var(--accent);border-radius:50%;animation:spin .7s linear infinite}
.empty-plans{text-align:center;padding:60px 20px;color:var(--text-3)}

/* ── Toast ── */
.toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%) translateY(14px);background:var(--text);color:#fff;padding:10px 18px 10px 13px;border-radius:999px;font-size:13px;font-weight:500;z-index:999;opacity:0;transition:all .28s cubic-bezier(.34,1.56,.64,1);pointer-events:none;white-space:nowrap;box-shadow:0 4px 20px rgba(0,0,0,.18);display:flex;align-items:center;gap:8px}
.toast-dot{width:7px;height:7px;border-radius:50%;flex-shrink:0}
.toast.show{opacity:1;transform:translateX(-50%) translateY(0)}
.toast.ok .toast-dot{background:#4ade80}
.toast.err .toast-dot{background:#f87171}
.toast.warn .toast-dot{background:var(--accent-hi)}

/* ── Responsive ── */
@media(max-width:640px){
  .hero{padding:40px 16px 56px}
  .hero h1{font-size:26px}
  .plans-wrap{padding:0 12px 48px}
  .plans-grid{grid-template-columns:1fr;gap:14px}
  .info-section{padding:20px}
  .member-cta{flex-direction:column;text-align:center}
  .fg input{font-size:16px}
}
</style>
</head>
<body>

<!-- Hero -->
<div class="hero">
  <a href="book.php" class="hero-back">
    <svg viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"/></svg>
    Back to Booking
  </a>
  <div class="hero-brand">
    <div class="hero-brand-dot"></div>
    <span id="app-name">FormBuilder</span>
    <div class="hero-brand-dot"></div>
  </div>
  <h1>Membership Plans</h1>
  <p>Choose a plan that works for you. Unlock premium services and book appointments with ease.</p>
</div>

<!-- Plans -->
<div class="plans-wrap">
  <div id="plans-container" class="plans-grid">
    <div class="loading-block">
      <div class="spinner"></div>
      Loading plans…
    </div>
  </div>

  <!-- Already a member CTA -->
  <div class="member-cta" style="margin-bottom:20px">
    <div class="member-cta-icon">
      <svg viewBox="0 0 24 24"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
    </div>
    <div class="member-cta-text">
      <div class="member-cta-title">Already a member?</div>
      <div class="member-cta-sub">Sign in with your email to book an appointment</div>
    </div>
    <button class="btn-cta" onclick="location.href='book.php'">Book Now →</button>
  </div>

  <!-- FAQ -->
  <div class="info-section">
    <div class="info-title">Frequently Asked Questions</div>
    <div class="faq-item open">
      <div class="faq-q" onclick="toggleFaq(this)">
        How long does my membership last?
        <svg viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"/></svg>
      </div>
      <div class="faq-a">Each membership plan has a specific duration (e.g., 30 days, 90 days). Your membership starts on the date of purchase and expires at the end of the period.</div>
    </div>
    <div class="faq-item">
      <div class="faq-q" onclick="toggleFaq(this)">
        Can I cancel or reschedule a booking?
        <svg viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"/></svg>
      </div>
      <div class="faq-a">Yes. You can cancel or reschedule appointments up to 24 hours before the scheduled time. Contact us directly to make changes.</div>
    </div>
    <div class="faq-item">
      <div class="faq-q" onclick="toggleFaq(this)">
        What payment methods do you accept?
        <svg viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"/></svg>
      </div>
      <div class="faq-a">We accept all major credit and debit cards through our secure Stripe payment gateway. Your payment information is never stored on our servers.</div>
    </div>
    <div class="faq-item">
      <div class="faq-q" onclick="toggleFaq(this)">
        Do I need to create an account?
        <svg viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"/></svg>
      </div>
      <div class="faq-a">No account needed. Your membership is linked to your email address. Simply enter your email when booking and we'll look up your active membership.</div>
    </div>
  </div>
</div>

<!-- Checkout bottom sheet -->
<div class="checkout-overlay" id="checkout-overlay" onclick="if(event.target===this)closeCheckout()">
  <div class="checkout-sheet">
    <div class="checkout-handle"></div>
    <div class="checkout-title" id="co-title">Get Started</div>
    <div class="checkout-plan" id="co-plan"></div>
    <div class="checkout-price" id="co-price"></div>
    <div class="fg">
      <label>Your Name</label>
      <input type="text" id="co-name" placeholder="Full name"/>
    </div>
    <div class="fg">
      <label>Email Address</label>
      <input type="email" id="co-email" placeholder="your@email.com"/>
    </div>
    <div class="fg" style="margin-bottom:6px">
      <label>Promo Code <span style="font-weight:400;color:var(--text-3)">(optional)</span></label>
      <div style="display:flex;gap:8px">
        <input type="text" id="co-promo" placeholder="YOURCODE" style="text-transform:uppercase;flex:1" oninput="this.value=this.value.toUpperCase()"/>
        <button onclick="applyPromo()" id="co-promo-btn" style="white-space:nowrap;padding:10px 14px;background:var(--accent);color:#fff;border:none;border-radius:9px;font-size:13px;font-weight:600;cursor:pointer">Apply</button>
      </div>
    </div>
    <div id="co-promo-msg" style="font-size:12px;margin-bottom:10px;display:none;padding:7px 10px;border-radius:7px"></div>
    <div id="co-err" style="font-size:12px;color:var(--red);margin-bottom:10px;display:none"></div>
    <button class="btn-checkout" id="co-btn" onclick="proceedToStripe()">
      Continue to Payment →
    </button>
    <div class="checkout-secure">
      <svg viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
      Secured by Stripe — we never store card details
    </div>
    <button class="checkout-cancel" onclick="closeCheckout()">Cancel</button>
  </div>
</div>

<div class="toast" id="toast"><div class="toast-dot"></div><span id="toast-msg"></span></div>

<script>
const CONFIG_BASE = <?= json_encode(APP_URL, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>;
const BASE = (() => {
  const p = window.location.pathname;
  const d = p.endsWith('/') ? p.slice(0, -1) : p.substring(0, p.lastIndexOf('/'));
  const derived = window.location.origin + d.replace(/\/booking(\/.*)?$/, '');
  if (!CONFIG_BASE) return derived;
  try {
    const u = new URL(CONFIG_BASE, window.location.origin);
    const normalized = u.origin + u.pathname.replace(/\/+$/, '');
    return u.host === window.location.host ? normalized : derived;
  } catch (_) {
    return derived;
  }
})();
const API = BASE + '/api/booking';

let selectedPlanId = null;
let plans = [];

const esc = s => String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
const q = sel => document.querySelector(sel);

function toast(msg, type='') {
  const t = q('#toast');
  q('#toast-msg').textContent = msg;
  t.className = 'toast show ' + type;
  clearTimeout(t._t);
  t._t = setTimeout(() => t.className = 'toast', 3200);
}

async function loadPlans() {
  const j = await fetch(API + '/plans').then(r=>r.json()).catch(()=>({ok:false}));

  if (!j.ok || !j.plans?.length) {
    q('#plans-container').className = '';
    q('#plans-container').innerHTML = `
      <div class="empty-plans">
        <div style="font-size:32px;margin-bottom:10px">📋</div>
        <div style="font-size:15px;font-weight:600;color:var(--text-2);margin-bottom:6px">No plans available</div>
        <div style="font-size:13px">Check back soon for membership options.</div>
      </div>`;
    return;
  }

  plans = j.plans;

  const featuredIdx = plans.length > 1 ? 1 : 0;

  q('#plans-container').innerHTML = plans.map((p, idx) => {
    const isFeatured = idx === featuredIdx && plans.length > 1;
    const price = parseFloat(p.price);
    const duration = p.duration_days >= 365
      ? `${Math.round(p.duration_days/365)} year${Math.round(p.duration_days/365)!==1?'s':''}`
      : p.duration_days >= 28
        ? `${Math.round(p.duration_days/30)} month${Math.round(p.duration_days/30)!==1?'s':''}`
        : `${p.duration_days} days`;

    return `
      <div class="plan-card${isFeatured?' featured':''}">
        ${isFeatured ? '<div class="plan-featured-badge">Most Popular</div>' : ''}
        <div class="plan-color-bar" style="background:${esc(p.color||'#e09500')}"></div>
        <div class="plan-name">${esc(p.name)}</div>
        <div class="plan-desc">${esc(p.description||'')}</div>
        <div class="plan-price-row">
          <span class="plan-currency">$</span>
          <span class="plan-amount">${price % 1 === 0 ? price.toFixed(0) : price.toFixed(2)}</span>
        </div>
        <div class="plan-duration">
          <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
          ${esc(duration)} access
        </div>
        <div class="plan-divider"></div>
        <div class="plan-services-label">Included Services</div>
        <ul class="plan-services">
          ${(p.services||[]).length
            ? p.services.map(s => `
              <li>
                ${esc(s.name)}
                <span class="svc-duration">${s.duration_min} min</span>
              </li>`).join('')
            : '<li style="color:var(--text-3)">All available services</li>'}
        </ul>
        <button class="btn-plan" onclick="openCheckout(${p.id})" id="plan-btn-${p.id}">
          Get ${esc(p.name)} →
        </button>
      </div>`;
  }).join('');
}

// ── Checkout ─────────────────────────────────────────────────────
function openCheckout(planId) {
  const plan = plans.find(p => p.id == planId);
  if (!plan) { location.href = `${BASE}/booking/checkout.php?plan_id=${Number(planId)}`; return; }
  selectedPlanId = planId;
  window._selectedPlan = plan;
  appliedPromo = null;
  // Reset promo UI
  q('#co-promo').value = '';
  q('#co-promo-msg').style.display = 'none';
  q('#co-err').style.display = 'none';
  q('#co-name').value = '';
  q('#co-email').value = '';
  q('#co-title').textContent = `Get ${plan.name}`;
  q('#co-plan').textContent = plan.name;
  q('#co-price').textContent = `€${parseFloat(plan.price).toFixed(2)} / ${plan.duration_days} days`;
  q('#checkout-overlay').classList.add('open');
}

function closeCheckout() {
  q('#checkout-overlay').classList.remove('open');
}

let appliedPromo = null;

async function applyPromo() {
  const code = q('#co-promo').value.trim().toUpperCase();
  const msg  = q('#co-promo-msg');
  if (!code) { msg.style.display='none'; appliedPromo=null; updatePriceDisplay(); return; }
  const btn = q('#co-promo-btn');
  btn.disabled = true; btn.textContent = '…';
  const j = await fetch(API + '/validate-promo', {
    method: 'POST',
    headers: {'Content-Type':'application/json'},
    body: JSON.stringify({code, plan_id: selectedPlanId}),
  }).then(r=>r.json()).catch(()=>({ok:false,error:'Network error'}));
  btn.disabled = false; btn.textContent = 'Apply';
  if (j.ok) {
    appliedPromo = j;
    const disp = j.discount_type === 'percent'
      ? `${j.discount_value}% off`
      : `€${parseFloat(j.discount_value).toFixed(2)} off`;
    msg.style.cssText = 'display:block;padding:7px 10px;border-radius:7px;font-size:12px;background:var(--green-pale);color:var(--green);border:1px solid var(--green-border)';
    msg.textContent = `✓ Code applied — ${disp}${j.description ? ': ' + j.description : ''}`;
    updatePriceDisplay();
  } else {
    appliedPromo = null;
    msg.style.cssText = 'display:block;padding:7px 10px;border-radius:7px;font-size:12px;background:var(--red-pale);color:var(--red);border:1px solid var(--red-border)';
    msg.textContent = j.error || 'Invalid promo code';
    updatePriceDisplay();
  }
}

function updatePriceDisplay() {
  if (!window._selectedPlan) return;
  const p = window._selectedPlan;
  if (appliedPromo) {
    const price = parseFloat(p.price);
    const disc = appliedPromo.discount_type === 'percent'
      ? price * appliedPromo.discount_value / 100
      : Math.min(parseFloat(appliedPromo.discount_value), price);
    const final = Math.max(0, price - disc).toFixed(2);
    q('#co-price').innerHTML = `<s style="color:var(--text-3)">€${price.toFixed(2)}</s> <strong style="color:var(--green)">€${final}</strong>`;
  } else {
    q('#co-price').textContent = `€${parseFloat(p.price).toFixed(2)} / ${p.duration_days} days`;
  }
}

async function proceedToStripe() {
  const name  = q('#co-name').value.trim();
  const email = q('#co-email').value.trim();
  if (!name) { showCoErr('Please enter your name.'); return; }
  if (!email || !email.includes('@')) { showCoErr('Please enter a valid email.'); return; }

  const btn = q('#co-btn');
  btn.disabled = true;
  btn.innerHTML = '<span class="plan-spinner"></span> Redirecting…';

  const payload = {
    plan_id: selectedPlanId,
    email, name,
    success_url: window.location.origin + BASE + '/plans.php?success=1',
    cancel_url: window.location.href,
  };
  if (appliedPromo) payload.promo_code = appliedPromo.code;

  const j = await fetch(API + '/stripe/checkout', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  }).then(r=>r.json()).catch(()=>({ok:false,error:'Network error'}));

  btn.disabled = false;
  btn.innerHTML = 'Continue to Payment →';

  if (j.ok && j.checkout_url) {
    window.location.href = j.checkout_url;
  } else {
    showCoErr(j.error || 'Could not start checkout. Please try again.');
  }
}

function showCoErr(msg) {
  q('#co-err').textContent = msg;
  q('#co-err').style.display = 'block';
}


// ── FAQ ──────────────────────────────────────────────────────────
function toggleFaq(el) {
  const item = el.closest('.faq-item');
  item.classList.toggle('open');
}

// ── Success state ────────────────────────────────────────────────
function checkSuccess() {
  const params = new URLSearchParams(location.search);
  if (params.get('success')) {
    toast('🎉 Membership activated! You can now book appointments.', 'ok');
    history.replaceState({}, '', location.pathname);
    setTimeout(() => {
      if (confirm('Your membership is now active! Would you like to book an appointment now?')) {
        location.href = 'book.php';
      }
    }, 500);
  }
}

// ── Boot ─────────────────────────────────────────────────────────
async function boot() {
  try {
    const j = await fetch(API + '/config').then(r=>r.json());
    if (j.app_name) {
      q('#app-name').textContent = j.app_name;
      document.title = 'Membership Plans — ' + j.app_name;
    }
  } catch(e) {}

  await loadPlans();
  checkSuccess();
}

boot();
</script>
</body>
</html>
