// checkout.el - Integrated Stripe checkout page.
//
// Uses Stripe Payment Element (not hosted checkout) so the entire
// purchase experience lives on neurontechnologies.ai. The page is
// designed to match the Neuron brand - navy, clean, no Stripe chrome.
//
// Flow:
//   1. GET /checkout?plan=founding|professional
//   2. Page JS calls POST /api/payment-intent → { client_secret, publishable_key, plan }
//   3. Stripe Payment Element mounts into #payment-element
//   4. User fills name, email, card - submits
//   5. stripe.confirmPayment() → redirects to /marketplace/success

fn checkout_page(plan: String, pub_key: String) -> String {
    let is_founding: Bool = str_eq(plan, "founding")
    let is_free: Bool = str_eq(plan, "free")

    let plan_name: String = if is_founding { "Founding Member" } else { if is_free { "Free" } else { "Professional" } }
    let plan_price: String = if is_founding { "$199" } else { if is_free { "$0" } else { "$19 / month" } }
    let plan_desc: String = if is_founding {
        "Pay once. Neuron inference when it launches - priced below the major APIs. No subscription, ever."
    } else { if is_free {
        "Start building your memory. No card required."
    } else {
        "Full access. Bring your own API keys or use Neuron Inference when it launches - Q3 2026."
    } }
    let plan_cadence: String = if is_founding { "one-time" } else { if is_free { "forever" } else { "billed monthly" } }

    let features_html: String = if is_founding {
        "<li>Everything in Professional - forever</li>
         <li>Neuron Inference when it launches - priced below the major APIs, forever</li>
         <li>Never pay again - lifetime updates included</li>
         <li>Founding member badge in the app</li>
         <li>Private founding member community</li>
         <li>Shape the roadmap - your votes carry more weight</li>
         <li>Beta features before general release</li>
         <li>Name in the credits</li>"
    } else { if is_free {
        "<li>Persistent memory - never resets</li>
         <li>Local inference via Ollama (coming)</li>
         <li>Bring your own API keys</li>
         <li>3 marketplace plugins included</li>
         <li>Core built-in capabilities</li>
         <li>2 devices included</li>"
    } else {
        "<li>Persistent memory - never resets</li>
         <li>Bring your own API keys (OpenAI, Anthropic, Grok...)</li>
         <li>Neuron Inference when it launches - Q3 2026, priced below the major APIs</li>
         <li>Unlimited projects</li>
         <li>Full plugin marketplace</li>
         <li>IDE, Slack, and more integrations</li>
         <li>Early access to new features</li>
         <li>2 devices included</li>"
    } }

    return "
<nav id=\"nav\">
  <div class=\"nav-inner\">
    <a href=\"/\" class=\"nav-logo\" aria-label=\"Neuron home\"><img src=\"/assets/brand/neuron-wordmark-on-light.png\" srcset=\"/assets/brand/neuron-wordmark-on-light@2x.png 2x\" alt=\"Neuron\" height=\"28\"></a>
    <div class=\"nav-links\">
      <a href=\"/\" class=\"nav-link\">&#8592; Back</a>
    </div>
  </div>
</nav>

<main style=\"min-height: 100vh; padding: clamp(6rem, 14vh, 9rem) 2rem 4rem;\">
  <div class=\"checkout-shell\">

    <!-- Left: order summary -->
    <div class=\"checkout-summary\">
      <p class=\"label\" style=\"margin-bottom: 1.5rem; color: var(--navy);\">Your order</p>

      <div style=\"margin-bottom: 2rem;\">
        <p class=\"checkout-plan-name\">" + plan_name + "</p>
        <p class=\"checkout-plan-desc\">" + plan_desc + "</p>
        <div style=\"display: flex; align-items: baseline; gap: .5rem; margin-top: 1.25rem;\">
          <span class=\"checkout-price\">" + plan_price + "</span>
          <span class=\"checkout-cadence\">" + plan_cadence + "</span>
        </div>
      </div>

      <div class=\"navy-line-left\" style=\"width: 3rem; margin-bottom: 1.75rem;\"></div>

      <ul class=\"checkout-features\">
        " + features_html + "
      </ul>

      <p class=\"checkout-guarantee\">
        Your data stays yours. Runs locally. No telemetry.
      </p>
    </div>

    <!-- Right: either free thank-you or sign-in + payment form -->
    <div class=\"checkout-form-wrap\">

    " + (if is_free { "
      <p class=\"label\" style=\"margin-bottom: 1.5rem; color: var(--navy);\">Create your account.</p>
      <p class=\"checkout-auth-hint\" style=\"margin-bottom: 2rem;\">Create an account to reserve your free tier spot. You'll receive your download link and setup instructions at launch.</p>
    " } else { "
      <!-- Optional sign-in (collapsed by default - users can purchase without an account) -->
      <div id=\"auth-section\" style=\"display:none;\">
        <p class=\"label\" style=\"margin-bottom: 1.25rem;\">Sign in (optional)</p>
        <p class=\"checkout-auth-hint\">Sign in to link this purchase to an existing account. Or skip and create one later - we'll match it to your email.</p>

        <div class=\"checkout-social-btns\">
          <button type=\"button\" class=\"checkout-social-btn\" id=\"btn-google\" onclick=\"signInWith('google')\">
            <svg width=\"18\" height=\"18\" viewBox=\"0 0 18 18\" fill=\"none\" aria-hidden=\"true\">
              <path d=\"M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615z\" fill=\"#4285F4\"/>
              <path d=\"M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z\" fill=\"#34A853\"/>
              <path d=\"M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z\" fill=\"#FBBC05\"/>
              <path d=\"M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 6.29C4.672 4.163 6.656 3.58 9 3.58z\" fill=\"#EA4335\"/>
            </svg>
            Continue with Google
          </button>

          <button type=\"button\" class=\"checkout-social-btn\" id=\"btn-github\" onclick=\"signInWith('github')\">
            <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden=\"true\">
              <path d=\"M12 0C5.37 0 0 5.37 0 12c0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61-.546-1.385-1.335-1.755-1.335-1.755-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.605-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 21.795 24 17.298 24 12c0-6.63-5.37-12-12-12z\"/>
            </svg>
            Continue with GitHub
          </button>

        </div>

        <div id=\"auth-message\" class=\"checkout-message\" style=\"display:none;\"></div>

        <div class=\"checkout-auth-divider\">
          <span id=\"auth-divider-label\">or create an account</span>
        </div>

        <div id=\"email-auth-form\">
          <input type=\"email\" id=\"auth-email\" class=\"checkout-input\" placeholder=\"Email address\" autocomplete=\"email\" style=\"width:100%;display:block;margin-bottom:.75rem\">
          <input type=\"password\" id=\"auth-password\" class=\"checkout-input\" placeholder=\"Password - min 8 characters\" autocomplete=\"new-password\" style=\"width:100%;display:block;margin-bottom:.75rem\">
          <button type=\"button\" class=\"checkout-email-btn\" onclick=\"signUpWithEmail()\">Create account &rarr;</button>
          <p class=\"checkout-auth-hint\" style=\"margin-top:.75rem;text-align:center\">Already have an account? <a href=\"#\" onclick=\"showSignIn();return false;\" style=\"color:var(--navy)\">Sign in</a></p>
        </div>
      </div>

      <!-- Payment form (visible immediately - no auth wall) -->
      <div id=\"payment-section\">
        <div id=\"auth-badge\" style=\"display:none; margin-bottom: 1.5rem;\"></div>
        <p class=\"checkout-auth-hint\" id=\"signin-prompt\" style=\"margin-bottom:1.25rem;font-size:.8125rem\">Already have an account? <a href=\"#\" onclick=\"document.getElementById('auth-section').style.display='';this.parentNode.style.display='none';return false;\" style=\"color:var(--navy);text-decoration:underline\">Sign in</a> to link your purchase.</p>

        <!-- Founding Member attestation (only shown for founding plan) -->
        " + (if is_founding { "
        <div id=\"founding-attestation\" style=\"margin-bottom:2rem;padding:1.5rem;border:1px solid rgba(0,82,160,.2);background:rgba(0,82,160,.03)\">
          <p style=\"font-family:var(--body);font-weight:500;font-size:.9rem;color:var(--t1);margin-bottom:.75rem\">Before you continue</p>
          <p style=\"font-family:var(--body);font-weight:300;font-size:.8375rem;color:var(--t2);line-height:1.75;margin-bottom:1.25rem\">Founding Member is not a ceremonial title. These are the people who will work directly with the team to shape what Neuron becomes. You will have a real voice in what gets built, and we will take it seriously. That requires you to show up in good faith.</p>
          <label style=\"display:flex;gap:.875rem;align-items:flex-start;cursor:pointer\">
            <input type=\"checkbox\" id=\"founding-attest-cb\" style=\"margin-top:.2rem;width:16px;height:16px;flex-shrink:0;accent-color:var(--navy)\">
            <span style=\"font-family:var(--body);font-weight:300;font-size:.8125rem;color:var(--t2);line-height:1.7\">
              I am joining as a genuine early user, not to extract proprietary information about Neuron&#39;s technology, architecture, or roadmap. I will engage in good faith. I understand that if this is not my intent, a different plan is a better fit.
            </span>
          </label>
          <p id=\"attest-warn\" style=\"display:none;font-family:var(--body);font-size:.8rem;color:#c44;margin-top:.75rem\">Please confirm the above before continuing.</p>
        </div>
        " } else { "" }) + "

        <!-- Payment timing (Professional only, Founding always charges now) -->
        " + (if !is_founding { "
        <div style=\"margin-bottom:1.75rem\">
          <p class=\"label\" style=\"margin-bottom:1rem\">When would you like to be charged?</p>
          <div style=\"display:flex;flex-direction:column;gap:.625rem\">
            <label class=\"checkout-timing-opt\" id=\"timing-now-label\">
              <input type=\"radio\" name=\"charge-timing\" value=\"now\" id=\"timing-now\" checked style=\"accent-color:var(--navy)\">
              <div>
                <span style=\"font-family:var(--body);font-weight:500;font-size:.875rem;color:var(--t1)\">Charge me now</span>
                <span style=\"font-family:var(--body);font-weight:300;font-size:.8rem;color:var(--t3);display:block;margin-top:.15rem\">Paying now signals you're serious. It gives us real signal about what people actually want to use Neuron for - not just who's curious. That shapes what we build first.</span>
              </div>
            </label>
            <label class=\"checkout-timing-opt\" id=\"timing-later-label\">
              <input type=\"radio\" name=\"charge-timing\" value=\"later\" id=\"timing-later\" style=\"accent-color:var(--navy)\">
              <div>
                <span style=\"font-family:var(--body);font-weight:500;font-size:.875rem;color:var(--t1)\">Hold until product launches (Q3 2026)</span>
                <span style=\"font-family:var(--body);font-weight:300;font-size:.8rem;color:var(--t3);display:block;margin-top:.15rem\">We save your payment method securely. Nothing charged until launch. Cancel anytime before then.</span>
              </div>
            </label>
          </div>
        </div>
        " } else { "" }) + "

        <p class=\"label\" style=\"margin-bottom: 1.75rem;\">Payment</p>

      <form id=\"payment-form\" autocomplete=\"on\">

        <div class=\"checkout-field-group\">
          <div class=\"checkout-field\">
            <label for=\"buyer-name\" class=\"checkout-label\">Full name</label>
            <input id=\"buyer-name\" name=\"name\" type=\"text\" autocomplete=\"name\"
              class=\"checkout-input\" placeholder=\"Full name\" required>
          </div>
          <div class=\"checkout-field\">
            <label for=\"buyer-email\" class=\"checkout-label\">Email</label>
            <input id=\"buyer-email\" name=\"email\" type=\"email\" autocomplete=\"email\"
              class=\"checkout-input\" placeholder=\"you@example.com\" required>
          </div>
        </div>

        <div class=\"checkout-payment-element-wrap\">
          <div id=\"payment-element\">
            <!-- Stripe Payment Element mounts here -->
            <div class=\"checkout-element-loading\">Loading payment form&#8230;</div>
          </div>
        </div>

        <div id=\"payment-message\" class=\"checkout-message\" style=\"display:none;\"></div>

        <button id=\"submit-btn\" class=\"checkout-submit\" type=\"submit\" disabled>
          <span id=\"submit-label\">Complete purchase &#8594;</span>
          <span id=\"submit-spinner\" style=\"display:none;\">Processing&#8230;</span>
        </button>

        <p class=\"checkout-security\">
          <svg aria-hidden=\"true\" width=\"12\" height=\"14\" viewBox=\"0 0 12 14\" fill=\"none\">
            <path d=\"M6 0L0 2.5V7c0 3.3 2.5 6.3 6 7 3.5-.7 6-3.7 6-7V2.5L6 0z\" fill=\"currentColor\" opacity=\".35\"/>
            <path d=\"M4 7l1.5 1.5L8.5 5\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>
          </svg>
          Secured by Stripe &nbsp;&middot;&nbsp; 256-bit TLS &nbsp;&middot;&nbsp; PCI DSS compliant
        </p>

      </form>
      </div><!-- /payment-section -->
    " }) + "
    </div>

  </div>
</main>

<!-- Supabase JS -->
<script src=\"https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/dist/umd/supabase.js\"></script>
<!-- Stripe.js -->
<script src=\"https://js.stripe.com/v3/\" async></script>

<style>
.checkout-shell {
  max-width: 960px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 5rem;
  align-items: start;
}
@media (max-width: 720px) {
  .checkout-shell { grid-template-columns: 1fr; gap: 3rem; }
}
.checkout-plan-name {
  font-family: var(--head);
  font-size: clamp(1.5rem, 3vw, 2rem);
  font-weight: 600;
  color: var(--t1);
  letter-spacing: -0.02em;
  margin: 0 0 .5rem;
}
.checkout-plan-desc {
  font-family: var(--body);
  font-weight: 300;
  font-size: .9375rem;
  color: var(--t2);
  line-height: 1.65;
  margin: 0;
}
.checkout-price {
  font-family: var(--head);
  font-size: 2.5rem;
  font-weight: 700;
  color: var(--t1);
  letter-spacing: -0.03em;
  line-height: 1;
}
.checkout-cadence {
  font-family: var(--body);
  font-size: .8125rem;
  color: var(--t3);
  letter-spacing: .04em;
}
.checkout-features {
  list-style: none;
  padding: 0;
  margin: 0 0 2rem;
  display: flex;
  flex-direction: column;
  gap: .6rem;
}
.checkout-features li {
  font-family: var(--body);
  font-weight: 300;
  font-size: .9rem;
  color: var(--t2);
  padding-left: 1.1rem;
  position: relative;
}
.checkout-features li::before {
  content: '–';
  position: absolute;
  left: 0;
  color: var(--navy);
  opacity: .6;
}
.checkout-guarantee {
  font-family: var(--body);
  font-weight: 300;
  font-size: .8125rem;
  color: var(--t3);
  line-height: 1.6;
  margin: 0;
}
.checkout-field-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  margin-bottom: 1.5rem;
}
@media (max-width: 480px) { .checkout-field-group { grid-template-columns: 1fr; } }
.checkout-field { display: flex; flex-direction: column; gap: .4rem; }
.checkout-label {
  font-family: var(--body);
  font-size: .75rem;
  font-weight: 500;
  letter-spacing: .06em;
  text-transform: uppercase;
  color: var(--t2);
}
.checkout-input {
  font-family: var(--body);
  font-size: .9375rem;
  font-weight: 300;
  color: var(--t1);
  background: #fff;
  border: 1px solid rgba(0,82,160,.22);
  padding: .75rem 1rem;
  outline: none;
  width: 100%;
  box-sizing: border-box;
  transition: border-color .2s;
  border-radius: 0;
  -webkit-appearance: none;
  appearance: none;
}
.checkout-input::placeholder { color: var(--t3); }
.checkout-input:focus { border-color: rgba(0,82,160,.6); box-shadow: 0 0 0 3px rgba(0,82,160,.08); }
.checkout-payment-element-wrap {
  margin-bottom: 1.5rem;
  border: 1px solid rgba(0,82,160,.22);
  padding: 1.25rem;
  background: #fff;
  min-height: 80px;
}
.checkout-element-loading {
  font-family: var(--body);
  font-size: .875rem;
  color: var(--t3);
}
.checkout-message {
  font-family: var(--body);
  font-size: .875rem;
  color: #c0392b;
  margin-bottom: 1rem;
  padding: .75rem 1rem;
  background: rgba(192,57,43,.06);
  border-left: 2px solid rgba(192,57,43,.4);
}
.checkout-submit {
  width: 100%;
  padding: 1.05rem 2rem;
  background: var(--navy);
  color: #fff;
  font-family: var(--body);
  font-size: .8125rem;
  font-weight: 600;
  letter-spacing: .12em;
  text-transform: uppercase;
  border: none;
  cursor: pointer;
  transition: background .2s, opacity .2s;
  margin-bottom: 1.25rem;
}
.checkout-submit:hover:not(:disabled) { background: #0078D4; }
.checkout-submit:disabled { opacity: .5; cursor: not-allowed; }
.checkout-security {
  font-family: var(--body);
  font-size: .75rem;
  color: var(--t3);
  display: flex;
  align-items: center;
  gap: .4rem;
  margin: 0;
}
.checkout-auth-hint {
  font-family: var(--body);
  font-weight: 300;
  font-size: .875rem;
  color: var(--t2);
  line-height: 1.6;
  margin: 0 0 1.75rem;
}
.checkout-social-btns {
  display: flex;
  flex-direction: column;
  gap: .75rem;
  margin-bottom: 1.75rem;
}
.checkout-social-btn {
  display: flex;
  align-items: center;
  gap: .875rem;
  width: 100%;
  padding: .875rem 1.25rem;
  background: #fff;
  border: 1.5px solid rgba(0,82,160,.18);
  font-family: var(--body);
  font-size: .9375rem;
  font-weight: 500;
  color: var(--t1);
  cursor: pointer;
  transition: border-color .2s, background .2s, box-shadow .2s;
  text-align: left;
  border-radius: 0;
  letter-spacing: .01em;
}
.checkout-social-btn:hover {
  border-color: var(--navy);
  background: rgba(0,82,160,.03);
  box-shadow: 0 2px 12px rgba(0,82,160,.08);
}
.checkout-social-btn:disabled { opacity: .45; cursor: not-allowed; }
.checkout-auth-divider {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin: 1.75rem 0 1.25rem;
  color: var(--t3);
  font-family: var(--body);
  font-size: .75rem;
  font-weight: 500;
  letter-spacing: .12em;
  text-transform: uppercase;
}
.checkout-auth-divider::before,
.checkout-auth-divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background: rgba(0,82,160,.12);
}
.checkout-email-btn {
  display: block;
  width: 100%;
  padding: .875rem 1.5rem;
  background: var(--navy);
  color: #fff;
  border: none;
  font-family: var(--body);
  font-size: .8125rem;
  font-weight: 500;
  letter-spacing: .12em;
  text-transform: uppercase;
  cursor: pointer;
  margin-top: .75rem;
  transition: background .2s, box-shadow .2s;
}
.checkout-email-btn:hover { background: #0078D4; box-shadow: 0 2px 16px rgba(0,82,160,.25); }
.checkout-skip-btn {
  background: none;
  border: none;
  font-family: var(--body);
  font-size: .8125rem;
  color: var(--t3);
  cursor: pointer;
  text-decoration: underline;
  text-underline-offset: 3px;
  padding: 0;
}
.checkout-skip-btn:hover { color: var(--navy); }
.checkout-auth-badge {
  display: flex;
  align-items: center;
  gap: .6rem;
  padding: .6rem .875rem;
  background: rgba(0,82,160,.05);
  border: 1px solid rgba(0,82,160,.18);
  font-family: var(--body);
  font-size: .8125rem;
  color: var(--t2);
}
.checkout-auth-badge strong { color: var(--navy); font-weight: 500; }
</style>

<script>
// ── Supabase auth ─────────────────────────────────────────────────────────────
(function() {
  var supabase;

  function initSupabase(cb) {
    if (supabase) { cb(); return; }
    fetch('/api/supabase-config')
      .then(function(r) { return r.json(); })
      .then(function(cfg) {
        supabase = window.supabase.createClient(cfg.url, cfg.anon_key, {
          auth: { flowType: 'implicit' }
        });
        cb();
      })
      .catch(function(err) {
        console.error('Supabase init failed', err);
      });
  }

  function showAuthMessage(msg, isError) {
    var el = document.getElementById('auth-message');
    el.textContent = msg;
    el.style.display = 'block';
    el.style.color = isError ? '#c0392b' : '#2ecc71';
  }

  function revealPaymentForm(user) {
    // Hide optional auth section if it was shown
    var auth = document.getElementById('auth-section');
    if (auth) auth.style.display = 'none';
    var payment = document.getElementById('payment-section');
    if (payment) payment.style.display = '';

    // Show auth badge if we have a user, hide the inline 'sign in' prompt
    if (user) {
      var badge = document.getElementById('auth-badge');
      var name = user.user_metadata && user.user_metadata.full_name
        ? user.user_metadata.full_name
        : user.email || '';
      badge.innerHTML = '<div class=\"checkout-auth-badge\">'
        + '<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M20 6L9 17l-5-5\" stroke=\"#0052A0\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>'
        + 'Signed in as <strong>' + name + '</strong>'
        + '</div>';
      badge.style.display = '';
      var prompt = document.getElementById('signin-prompt');
      if (prompt) prompt.style.display = 'none';
    }

    // Pre-fill email only (not name - let user enter their own)
    if (user && user.email) {
      var emailEl = document.getElementById('buyer-email');
      if (emailEl) { emailEl.value = user.email; }
    }

    // Initialize Stripe Elements with this user's email (or empty if guest)
    var userEmail = user ? (user.email || '') : '';
    var userName = user ? ((user.user_metadata && user.user_metadata.full_name) || '') : '';
    if (typeof initStripe === 'function') initStripe(userEmail, userName);
  }

  // Check if already signed in on load
  function checkExistingSession() {
    initSupabase(function() {
      supabase.auth.getUser().then(function(res) {
        if (res.data && res.data.user) {
          revealPaymentForm(res.data.user);
        }
      });
    });
  }

  // Handle OAuth redirect callback
  function handleAuthRedirect() {
    initSupabase(function() {
      supabase.auth.onAuthStateChange(function(event, session) {
        if ((event === 'SIGNED_IN' || event === 'INITIAL_SESSION') && session && session.user) {
          revealPaymentForm(session.user);
        }
      });
    });
  }

  // Social sign-in
  window.signInWith = function(provider) {
    var btns = document.querySelectorAll('.checkout-social-btn');
    btns.forEach(function(b) { b.disabled = true; });

    initSupabase(function() {
      supabase.auth.signInWithOAuth({
        provider: provider,
        options: {
          redirectTo: window.location.href
        }
      }).then(function(result) {
        if (result.error) {
          showAuthMessage(result.error.message || 'Sign-in failed. Please try again.', true);
          btns.forEach(function(b) { b.disabled = false; });
        }
        // On success, browser redirects to OAuth provider - no further action needed here.
      });
    });
  };

  // Email signup
  window.signUpWithEmail = function() {
    var email = document.getElementById('auth-email').value.trim();
    var password = document.getElementById('auth-password').value;
    if (!email || !password) { showAuthMessage('Please enter your email and a password.', true); return; }
    if (password.length < 8) { showAuthMessage('Password must be at least 8 characters.', true); return; }
    initSupabase(function() {
      supabase.auth.signUp({ email: email, password: password }).then(function(result) {
        if (result.error) { showAuthMessage(result.error.message, true); return; }
        if (result.data && result.data.session) {
          revealPaymentForm(result.data.session.user);
        } else {
          showAuthMessage('Check your email to confirm your account, then come back to complete your purchase.', false);
        }
      });
    });
  };

  // Email sign-in (existing account)
  window.showSignIn = function() {
    var form = document.getElementById('email-auth-form');
    var btn = form.querySelector('.checkout-email-btn');
    var hint = form.querySelector('.checkout-auth-hint');
    btn.textContent = 'Sign in →';
    btn.onclick = signInWithEmail;
    /* hint replaced with DOM manipulation below */
  };

  window.showSignUp = function() {
    var form = document.getElementById('email-auth-form');
    var btn = form.querySelector('.checkout-email-btn');
    var hint = form.querySelector('.checkout-auth-hint');
    btn.textContent = 'Create account →';
    btn.onclick = signUpWithEmail;
    /* hint replaced with DOM manipulation below */
  };

  window.signInWithEmail = function() {
    var email = document.getElementById('auth-email').value.trim();
    var password = document.getElementById('auth-password').value;
    if (!email || !password) { showAuthMessage('Please enter your email and password.', true); return; }
    initSupabase(function() {
      supabase.auth.signInWithPassword({ email: email, password: password }).then(function(result) {
        if (result.error) { showAuthMessage(result.error.message, true); return; }
        revealPaymentForm(result.data.session.user);
      });
    });
  };

  window.resetPassword = function() {
    var email = document.getElementById('auth-email').value.trim();
    if (!email) { showAuthMessage('Enter your email address above first.', true); return; }
    initSupabase(function() {
      supabase.auth.resetPasswordForEmail(email, {
        redirectTo: window.location.origin + '/checkout?plan=' + (new URLSearchParams(window.location.search).get('plan') || 'professional')
      }).then(function(result) {
        if (result.error) { showAuthMessage(result.error.message, true); }
        else { showAuthMessage('Password reset email sent. Check your inbox.', false); }
      });
    });
  };

  // Init
  handleAuthRedirect();
  checkExistingSession();
})();
</script>

<script>
(function() {
  var PLAN = '" + plan + "';
  var STRIPE_PK = '" + pub_key + "';
  var stripe, elements;

  // Wait for Stripe.js to load
  function waitForStripe(cb) {
    if (window.Stripe) { cb(); return; }
    setTimeout(function() { waitForStripe(cb); }, 50);
  }

  function showMessage(msg) {
    var el = document.getElementById('payment-message');
    el.textContent = msg;
    el.style.display = 'block';
  }

  function setLoading(loading) {
    var btn = document.getElementById('submit-btn');
    var label = document.getElementById('submit-label');
    var spinner = document.getElementById('submit-spinner');
    btn.disabled = loading;
    label.style.display = loading ? 'none' : '';
    spinner.style.display = loading ? '' : 'none';
  }

  // Fetch client secret from our server
  fetch('/api/payment-intent', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ plan: PLAN })
  })
  .then(function(r) { return r.json(); })
  .then(function(data) {
    if (data.error === 'sold_out') {
      showMessage('All 1,000 Founding Member spots have been claimed. Thank you for your interest - please consider the Professional plan.');
      var submitBtn = document.getElementById('submit-btn');
      if (submitBtn) { submitBtn.disabled = true; submitBtn.textContent = 'Sold out'; }
      return;
    }
    if (!data.client_secret) {
      showMessage('Unable to initialise payment. Please try again.');
      return;
    }

    window._neuronPiId = data.id || (data.client_secret ? data.client_secret.split('_secret_')[0] : '');

    waitForStripe(function() {
      stripe = Stripe(STRIPE_PK);

      elements = stripe.elements({
        clientSecret: data.client_secret,
        appearance: {
          theme: 'flat',
          variables: {
            colorPrimary:        '#0052A0',
            colorBackground:     '#ffffff',
            colorText:           '#1A1A2E',
            colorDanger:         '#c0392b',
            colorTextPlaceholder:'#9B9BAD',
            borderRadius:        '0px',
            fontFamily:          'system-ui, -apple-system, sans-serif',
            fontSizeBase:        '15px',
            fontWeightNormal:    '300',
            spacingUnit:         '4px',
          },
          rules: {
            '.Input': {
              border: '1px solid rgba(0,82,160,.22)',
              boxShadow: 'none',
              padding: '10px 14px',
            },
            '.Input:focus': {
              border: '1px solid rgba(0,82,160,.6)',
              boxShadow: '0 0 0 3px rgba(0,82,160,.08)',
              outline: 'none',
            },
            '.Label': {
              fontSize: '11px',
              fontWeight: '500',
              letterSpacing: '.06em',
              textTransform: 'uppercase',
              color: '#6B6B7E',
              marginBottom: '6px',
            },
            '.Tab': {
              border: '1px solid rgba(0,82,160,.18)',
              boxShadow: 'none',
            },
            '.Tab--selected': {
              border: '1px solid rgba(0,82,160,.5)',
              boxShadow: '0 0 0 2px rgba(0,82,160,.12)',
            },
            '.Error': { color: '#c0392b' },
          }
        }
      });

      var paymentEl = elements.create('payment', {
        fields: { billingDetails: { name: 'never', email: 'never' } }
      });
      paymentEl.mount('#payment-element');

      paymentEl.on('ready', function() {
        document.querySelector('.checkout-element-loading') &&
          document.querySelector('.checkout-element-loading').remove();
        document.getElementById('submit-btn').disabled = false;
      });
    });
  })
  .catch(function() {
    showMessage('Unable to connect. Please check your connection and try again.');
  });

  // Submit
  document.getElementById('payment-form').addEventListener('submit', async function(e) {
    e.preventDefault();
    if (!stripe || !elements) return;

    // Founding Member attestation gate
    var attestCb = document.getElementById('founding-attest-cb');
    if (attestCb && !attestCb.checked) {
      var warn = document.getElementById('attest-warn');
      if (warn) warn.style.display = 'block';
      attestCb.closest('label').scrollIntoView({ behavior: 'smooth', block: 'center' });
      return;
    }

    var name  = document.getElementById('buyer-name').value.trim();
    var email = document.getElementById('buyer-email').value.trim();
    if (!name || !email) {
      showMessage('Please enter your name and email.');
      return;
    }

    // Save founding member attestation before charging - independent audit record
    if (attestCb) {
      try {
        await fetch('/api/attest', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            plan: PLAN,
            name: name,
            email: email,
            timestamp: new Date().toISOString(),
            attestation: 'I am joining as a genuine early user, not to extract proprietary information about Neuron technology, architecture, or roadmap. I will engage in good faith. I understand that if this is not my intent, a different plan is a better fit.',
            user_agent: navigator.userAgent
          })
        });
      } catch(e) {
        // Non-blocking - attestation log failure does not stop payment
        console.warn('attestation log failed', e);
      }
    }

    setLoading(true);
    document.getElementById('payment-message').style.display = 'none';

    if (window._neuronPiId) {
      try {
        await fetch('/api/link-customer', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ pi_id: window._neuronPiId, email: email, name: name, plan: PLAN })
        });
      } catch(e) { /* non-blocking */ }
    }

    var result = await stripe.confirmPayment({
      elements: elements,
      confirmParams: {
        return_url: window.location.origin + '/account?welcome=1',
        payment_method_data: {
          billing_details: { name: name, email: email }
        },
        receipt_email: email,
      }
    });

    if (result.error) {
      showMessage(result.error.message || 'Payment failed. Please try again.');
      setLoading(false);
    }
    // On success, Stripe redirects to return_url automatically.
  });
})();
</script>
"
}
