// checkout-auth.el -- Checkout Supabase auth: OAuth, email sign-in/sign-up.
// Compiled with: elc --target=js --bundle --minify --obfuscate
//
// Exposed globals: signInWith(provider), signUpWithEmail(), signInWithEmail(),
//                  showSignIn(), showSignUp(), resetPassword()

fn main() -> Void {
    native_js("(function() {
  var supabaseClient;

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

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

  var _formRevealed = false;
  function revealPaymentForm(user) {
    if (_formRevealed) return;
    _formRevealed = true;
    if (user && user.id) { window._neuronSupaId = user.id; }
    var auth = document.getElementById('auth-section');
    if (auth) auth.style.display = 'none';
    var payment = document.getElementById('payment-section');
    if (payment) payment.style.display = '';

    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 || '';
      if (badge) {
        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';
    }

    if (user && user.email) {
      var emailEl = document.getElementById('buyer-email');
      if (emailEl) emailEl.value = user.email;
    }

    var userEmail = user ? (user.email || '') : '';
    var userName  = user ? ((user.user_metadata && user.user_metadata.full_name) || '') : '';
    if (typeof window.initStripe === 'function') window.initStripe(userEmail, userName);
  }

  function checkExistingSession() {
    initSupabase(function() {
      supabaseClient.auth.getUser().then(function(res) {
        if (res.data && res.data.user) {
          revealPaymentForm(res.data.user);
        } else {
          // No existing session — for paid plans, init Stripe immediately.
          // Auth is optional on paid plans; the user can link their account later.
          var isFree = (window.NEURON_CFG || {}).plan === 'free';
          if (!isFree && typeof window.initStripe === 'function') {
            window.initStripe('', '');
          }
        }
      });
    });
  }

  function handleAuthRedirect() {
    initSupabase(function() {
      supabaseClient.auth.onAuthStateChange(function(event, session) {
        if ((event === 'SIGNED_IN' || event === 'INITIAL_SESSION') && session && session.user) {
          revealPaymentForm(session.user);
        }
      });
    });
  }

  window.signInWith = function(provider) {
    var btns = document.querySelectorAll('.checkout-social-btn');
    btns.forEach(function(b) { b.disabled = true; });
    initSupabase(function() {
      supabaseClient.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; });
        }
      });
    });
  };

  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() {
      supabaseClient.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);
        }
      });
    });
  };

  window.showSignIn = function() {
    var form = document.getElementById('email-auth-form');
    if (!form) return;
    var btn = form.querySelector('.checkout-email-btn');
    if (btn) { btn.textContent = 'Sign in →'; btn.onclick = window.signInWithEmail; }
  };

  window.showSignUp = function() {
    var form = document.getElementById('email-auth-form');
    if (!form) return;
    var btn = form.querySelector('.checkout-email-btn');
    if (btn) { btn.textContent = 'Create account →'; btn.onclick = window.signUpWithEmail; }
  };

  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() {
      supabaseClient.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() {
      supabaseClient.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); }
      });
    });
  };

  handleAuthRedirect();
  checkExistingSession();
})()")
}
