/**
 * Ragreen - Auth form handlers (jQuery + AJAX against the PHP API)
 * Requires config.js (defines API_BASE) to be loaded first.
 */

function showAlert($alertBox, message, type = 'error') {
  $alertBox
    .removeClass('alert-error alert-success')
    .addClass(type === 'error' ? 'alert-error' : 'alert-success')
    .text(message)
    .stop(true, true)
    .slideDown(150);
}

function hideAlert($alertBox) {
  $alertBox.slideUp(120);
}

function setLoading($btn, isLoading, labelDefault, labelLoading) {
  $btn.prop('disabled', isLoading).text(isLoading ? labelLoading : labelDefault);
}

$(function () {

  /* ---------------- Register ---------------- */
  const $registerForm = $('#registerForm');
  if ($registerForm.length) {

    // Toggle name field based on account type
    $('input[name="account_type"]').on('change', function () {
      const type = $('input[name="account_type"]:checked').val();
      if (type === 'business') {
        $('#field-full-name').hide();
        $('#field-business-name').show();
      } else {
        $('#field-business-name').hide();
        $('#field-full-name').show();
      }
    });

    $registerForm.on('submit', function (e) {
      e.preventDefault();
      const $alert = $('#registerAlert');
      hideAlert($alert);

      const accountType = $('input[name="account_type"]:checked').val();
      const payload = {
        email: valTrim('#email'),
        password: $('#password').val(),
        account_type: accountType,
        phone: valTrim('#phone'),
      };

      if (accountType === 'business') {
        payload.business_name = valTrim('#business_name');
      } else {
        payload.full_name = valTrim('#full_name');
      }

      if (payload.password.length < 8) {
        showAlert($alert, 'Password must be at least 8 characters.');
        return;
      }

      const $btn = $('#registerBtn');
      setLoading($btn, true, 'Create account', 'Creating account…');

      $.ajax({
        url: `${API_BASE}/auth/register.php`,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(payload),
      })
        .done(function (res) {
          // No auto-login anymore - the account needs email verification first.
          $registerForm.hide();
          const devLink = res.data.dev_verify_link
            ? `<p style="font-size:12px; color:var(--ink-muted); margin-top:10px;">Local dev mode - no real email sent, use this link directly: <a href="${res.data.dev_verify_link}">${res.data.dev_verify_link}</a></p>`
            : '';
          showAlert($alert, 'Account created! Check your email for a verification link before logging in.', 'success');
          $alert.after(`
            <p style="font-size:13px; color:var(--ink-muted); margin-top:14px;">
              Didn't get it? <a href="#" id="resendVerifyLink" style="color:var(--leaf-dark); font-weight:600;">Resend verification email</a>
            </p>
            ${devLink}
          `);
          $('#resendVerifyLink').on('click', function (e) {
            e.preventDefault();
            $.ajax({
              url: `${API_BASE}/auth/resend_verification.php`, method: 'POST', contentType: 'application/json',
              data: JSON.stringify({ email: payload.email }),
            }).always(() => showAlert($alert, 'If that email needs verification, a new link has been sent.', 'success'));
          });
        })
        .fail(function (xhr) {
          const msg = xhr.responseJSON?.message || 'Something went wrong. Please try again.';
          showAlert($alert, msg);
        })
        .always(function () {
          setLoading($btn, false, 'Create account', 'Creating account…');
        });
    });
  }

  /* ---------------- Login ---------------- */
  const $loginForm = $('#loginForm');
  if ($loginForm.length) {
    $loginForm.on('submit', function (e) {
      e.preventDefault();
      const $alert = $('#loginAlert');
      hideAlert($alert);

      const payload = {
        email: valTrim('#email'),
        password: $('#password').val(),
      };

      const $btn = $('#loginBtn');
      setLoading($btn, true, 'Log in', 'Logging in…');

      $.ajax({
        url: `${API_BASE}/auth/login.php`,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(payload),
      })
        .done(function (res) {
          showAlert($alert, 'Welcome back! Redirecting…', 'success');
          const redirect = new URLSearchParams(window.location.search).get('redirect');
          // Only ever follow a bare local .html filename (+ optional query string) -
          // never a full URL, so this can't be turned into an open redirect by
          // crafting a malicious ?redirect= value.
          const safe = redirect && /^[a-zA-Z0-9_-]+\.html(\?[^\s]*)?$/.test(decodeURIComponent(redirect));
          const destination = safe ? decodeURIComponent(redirect) : 'marketplace.html';
          setTimeout(() => { window.location.href = destination; }, 600);
        })
        .fail(function (xhr) {
          const msg = xhr.responseJSON?.message || 'Invalid email or password.';
          showAlert($alert, msg);
          $('#resendVerifyFromLogin').remove();
          if (xhr.responseJSON?.errors?.unverified) {
            $alert.after(`
              <p id="resendVerifyFromLogin" style="font-size:13px; color:var(--ink-muted); margin-top:10px;">
                <a href="#" id="resendVerifyLoginLink" style="color:var(--leaf-dark); font-weight:600;">Resend verification email</a>
              </p>
            `);
            $('#resendVerifyLoginLink').on('click', function (e) {
              e.preventDefault();
              $.ajax({
                url: `${API_BASE}/auth/resend_verification.php`, method: 'POST', contentType: 'application/json',
                data: JSON.stringify({ email: payload.email }),
              }).always(() => showAlert($alert, 'If that email needs verification, a new link has been sent.', 'success'));
            });
          }
        })
        .always(function () {
          setLoading($btn, false, 'Log in', 'Logging in…');
        });
    });
  }

  /* ---------------- Forgot Password ---------------- */
  const $forgotForm = $('#forgotForm');
  if ($forgotForm.length) {
    $forgotForm.on('submit', function (e) {
      e.preventDefault();
      const $alert = $('#forgotAlert');
      hideAlert($alert);

      const payload = { email: valTrim('#email') };
      const $btn = $('#forgotBtn');
      setLoading($btn, true, 'Send reset link', 'Sending…');

      $.ajax({
        url: `${API_BASE}/auth/forgot_password.php`,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(payload),
      })
        .done(function (res) {
          showAlert($alert, res.message || 'If that email exists, a reset link has been sent.', 'success');
          $forgotForm.find('input, button').prop('disabled', true);
        })
        .fail(function (xhr) {
          const msg = xhr.responseJSON?.message || 'Something went wrong. Please try again.';
          showAlert($alert, msg);
        })
        .always(function () {
          setLoading($btn, false, 'Send reset link', 'Sending…');
        });
    });
  }

});
