/* NRI Property Guard — portal auth screen logic */
(function () {
  var sb = window.sbClient;
  var pending = { name: '', email: '', phone: '', password: '', tier: 'regular' };

  /* Every role now has a real web destination. super_admin shares the Admin
     dashboard (same is_admin_or_above() access level as admin everywhere in
     the backend, so there is no separate super_admin web screen to build). */
  var ROLE_DASHBOARDS = {
    customer: 'dashboard.html',
    admin: 'admin-dashboard.html',
    super_admin: 'admin-dashboard.html',
    property_manager: 'manager-dashboard.html',
    property_executive: 'executive-dashboard.html'
  };
  function dashboardForRole(role) { return ROLE_DASHBOARDS[role] || 'dashboard.html'; }

  function showAlert(id, msg, type) {
    var el = document.getElementById(id);
    el.textContent = msg;
    el.className = 'alert show ' + (type || 'error');
  }
  function hideAlert(id) {
    document.getElementById(id).className = 'alert';
  }

  /* This web portal is the Property Owner (customer) dashboard only — Admin,
     Property Manager and Property Executive accounts have their own screens
     in the mobile app, not here. Look up the signed-in account's real role
     (readable under RLS: users_select allows id = auth.uid()) before ever
     creating a customer row or opening the dashboard for it. Returns the
     role string, or 'customer' if the lookup fails open (fail-safe: an
     unreadable role should not block a genuine owner from signing in). */
  async function getUserRole(userId) {
    try {
      var res = await sb.from('users').select('role').eq('id', userId).maybeSingle();
      if (res.error || !res.data) return 'customer';
      return res.data.role || 'customer';
    } catch (e) {
      console.warn('role lookup failed, defaulting to customer:', e.message);
      return 'customer';
    }
  }

  /* Ensure a public.customers row exists for the signed-in user (covers Email-OTP
     registration and a first-time Google sign-in alike). Safe to call every login —
     no-ops if the row already exists. */
  async function ensureCustomerRow(userId, defaultTier) {
    try {
      var existing = await sb.from('customers').select('id').eq('user_id', userId).maybeSingle();
      if (existing.data && existing.data.id) return existing.data.id;
      var ins = await sb.from('customers').insert({ user_id: userId, package_tier: defaultTier || 'regular' }).select('id').single();
      if (ins.error) throw ins.error;
      return ins.data.id;
    } catch (e) {
      console.warn('ensureCustomerRow failed (non-fatal):', e.message);
      return null;
    }
  }

  async function applyProfileDetails(userId, name, phone) {
    try {
      var patch = {};
      if (name) patch.name = name;
      if (phone) patch.phone_number = phone;
      if (Object.keys(patch).length) await sb.from('users').update(patch).eq('id', userId);
    } catch (e) { console.warn('profile update failed (non-fatal):', e.message); }
  }

  async function boot() {
    var params = new URLSearchParams(location.search);
    var { data } = await sb.auth.getSession();
    if (data && data.session) {
      var role = await getUserRole(data.session.user.id);
      if (role !== 'customer') { location.href = dashboardForRole(role); return; }
      await ensureCustomerRow(data.session.user.id, 'regular');
      location.href = 'dashboard.html' + (params.get('register') ? '#register' : '');
      return;
    }
    document.getElementById('loadingGate').style.display = 'none';
    document.getElementById('authArea').style.display = 'block';
    if (location.hash === '#register' || params.get('register')) {
      document.querySelector('.auth-tab[data-tab="register"]').click();
    }
  }

  /* ---------- Tabs ---------- */
  document.querySelectorAll('.auth-tab').forEach(function (tab) {
    tab.addEventListener('click', function () {
      document.querySelectorAll('.auth-tab').forEach(function (t) { t.classList.remove('active'); });
      document.querySelectorAll('.auth-panel').forEach(function (p) { p.classList.remove('active'); });
      tab.classList.add('active');
      document.getElementById('panel-' + tab.dataset.tab).classList.add('active');
    });
  });

  /* ---------- Sign in ---------- */
  document.getElementById('signinForm').addEventListener('submit', async function (e) {
    e.preventDefault();
    hideAlert('signinAlert');
    var btn = document.getElementById('siSubmit');
    var email = document.getElementById('si-email').value.trim();
    var password = document.getElementById('si-pass').value;
    btn.disabled = true; btn.innerHTML = '<span class="loading-spin"></span> Signing in…';
    try {
      var res = await sb.auth.signInWithPassword({ email: email, password: password });
      if (res.error) throw res.error;
      var role = await getUserRole(res.data.user.id);
      if (role !== 'customer') {
        location.href = dashboardForRole(role);
        return;
      }
      await ensureCustomerRow(res.data.user.id, 'regular');
      location.href = 'dashboard.html';
    } catch (err) {
      showAlert('signinAlert', err.message || 'Could not sign in. Check your email and password.', 'error');
      btn.disabled = false; btn.textContent = 'Sign In';
    }
  });

  /* ---------- Google OAuth (both tabs) ---------- */
  function googleSignIn() {
    var redirectTo = location.origin + location.pathname.replace(/index\.html$/, '') + 'dashboard.html';
    sb.auth.signInWithOAuth({ provider: 'google', options: { redirectTo: redirectTo } }).then(function (res) {
      if (res.error) window.NRIPG.toast(res.error.message || 'Google Sign-In is not enabled yet on this account.', 'error');
    });
  }
  document.getElementById('googleBtnSignin').addEventListener('click', googleSignIn);
  document.getElementById('googleBtnRegister').addEventListener('click', googleSignIn);

  /* ---------- Register: tier picker ---------- */
  document.querySelectorAll('.tier-opt').forEach(function (opt) {
    opt.addEventListener('click', function () {
      document.querySelectorAll('.tier-opt').forEach(function (o) { o.classList.remove('selected'); });
      opt.classList.add('selected');
      pending.tier = opt.dataset.tier;
    });
  });

  /* ---------- Register: step 1 -> send OTP ---------- */
  document.getElementById('sendOtpBtn').addEventListener('click', async function () {
    hideAlert('regAlert');
    var name = document.getElementById('r-name').value.trim();
    var email = document.getElementById('r-email').value.trim();
    var phone = document.getElementById('r-phone').value.trim();
    var password = document.getElementById('r-pass').value;
    if (!name || !email || password.length < 6) {
      showAlert('regAlert', 'Please enter your name, a valid email, and a password of at least 6 characters.', 'error');
      return;
    }
    var btn = this;
    btn.disabled = true; btn.innerHTML = '<span class="loading-spin"></span> Sending code…';
    try {
      var res = await sb.auth.signInWithOtp({ email: email, options: { shouldCreateUser: true } });
      if (res.error) throw res.error;
      pending.name = name; pending.email = email; pending.phone = phone; pending.password = password;
      document.getElementById('otpEmailShown').textContent = email;
      document.getElementById('regStep1').style.display = 'none';
      document.getElementById('regStep2').style.display = 'block';
      showAlert('regAlert', 'Verification code sent — check your inbox (and spam folder).', 'info');
    } catch (err) {
      showAlert('regAlert', err.message || 'Could not send the verification code. Please try again.', 'error');
    } finally {
      btn.disabled = false; btn.textContent = 'Send Verification Code';
    }
  });

  document.getElementById('backToStep1').addEventListener('click', function (e) {
    e.preventDefault();
    document.getElementById('regStep2').style.display = 'none';
    document.getElementById('regStep1').style.display = 'block';
  });

  document.getElementById('resendOtp').addEventListener('click', async function (e) {
    e.preventDefault();
    try {
      await sb.auth.signInWithOtp({ email: pending.email, options: { shouldCreateUser: true } });
      window.NRIPG.toast('A new code has been sent to ' + pending.email, 'success');
    } catch (err) { window.NRIPG.toast(err.message || 'Could not resend code.', 'error'); }
  });

  /* ---------- Register: step 2 -> verify OTP & finish ---------- */
  document.getElementById('verifyOtpBtn').addEventListener('click', async function () {
    hideAlert('regAlert');
    var code = document.getElementById('r-otp').value.trim();
    if (code.length < 6) { showAlert('regAlert', 'Enter the 6-digit code sent to your email.', 'error'); return; }
    var btn = this;
    btn.disabled = true; btn.innerHTML = '<span class="loading-spin"></span> Verifying…';
    try {
      var res = await sb.auth.verifyOtp({ email: pending.email, token: code, type: 'email' });
      if (res.error) throw res.error;
      var userId = res.data.user.id;

      // Best-effort finishing touches — the account already exists and the person
      // is already signed in at this point, so none of these block success.
      if (pending.password) {
        try { await sb.auth.updateUser({ password: pending.password }); } catch (e) { console.warn(e); }
      }
      await applyProfileDetails(userId, pending.name, pending.phone);
      await ensureCustomerRow(userId, pending.tier);

      window.NRIPG.toast('Account created! Redirecting to your dashboard…', 'success');
      setTimeout(function () { location.href = 'dashboard.html#register'; }, 700);
    } catch (err) {
      showAlert('regAlert', err.message || 'That code is invalid or has expired. Try resending it.', 'error');
      btn.disabled = false; btn.textContent = 'Verify & Create Account';
    }
  });

  boot();
})();
