<h2 class="text-2xl font-bold text-gray-900 text-center mb-2">
  Create Admin Account
</h2>
<% if @require_owner_email %>
<p class="text-center text-gray-600 text-sm mb-8">
  Create your admin account using the email address you verified.
</p>
<% else %>
<p class="text-center text-gray-600 text-sm mb-8">
  Create a new admin account. After sign-up, you'll need to be granted admin privileges.
</p>
<% end %>

<form id="signup-form" class="space-y-6">
  <% if @require_owner_email %>
  <input type="hidden" id="required-email" value="<%= @required_email %>">
  <input type="hidden" id="verification-token" value="<%= @verification_token %>">
  <div>
    <label for="email" class="block text-sm font-medium text-gray-700">
      Email Address
    </label>
    <div class="mt-1">
      <input type="email" id="email" value="<%= @required_email %>" readonly
             class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-100 text-gray-700 cursor-not-allowed sm:text-sm">
    </div>
    <p class="mt-1 text-xs text-gray-500">You must use this email address to create your account.</p>
  </div>
  <% else %>
  <div>
    <label for="email" class="block text-sm font-medium text-gray-700">
      Email Address
    </label>
    <div class="mt-1">
      <input type="email" id="email" placeholder="Enter your email" required
             class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
    </div>
  </div>
  <% end %>

  <div>
    <label for="password" class="block text-sm font-medium text-gray-700">
      Password
    </label>
    <div class="mt-1">
      <input type="password" id="password" placeholder="Enter password (min 6 characters)" required
             class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
    </div>
    <p class="mt-1 text-xs text-gray-500">Password must be at least 6 characters long.</p>
  </div>

  <div>
    <label for="confirm-password" class="block text-sm font-medium text-gray-700">
      Confirm Password
    </label>
    <div class="mt-1">
      <input type="password" id="confirm-password" placeholder="Confirm your password" required
             class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
    </div>
  </div>

  <div>
    <button type="submit" id="signup-button"
            class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed">
      Create Account
    </button>
  </div>

  <div id="message"></div>
</form>

<div class="mt-6 text-center">
  <p class="text-sm text-gray-600">
    Already have an account?
    <%= link_to "Sign In", "/pwb_login",
        class: "font-medium text-blue-600 hover:text-blue-500" %>
  </p>
</div>

<script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-auth-compat.js"></script>

<script>
  // Firebase configuration
  const firebaseConfig = {
    apiKey: "<%= ENV['FIREBASE_API_KEY'] %>",
    authDomain: "<%= ENV['FIREBASE_PROJECT_ID'] %>.firebaseapp.com",
    projectId: "<%= ENV['FIREBASE_PROJECT_ID'] %>",
  };

  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  const auth = firebase.auth();

  document.getElementById('signup-form').addEventListener('submit', function(e) {
    e.preventDefault();

    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    const messageDiv = document.getElementById('message');
    const button = document.getElementById('signup-button');

    // Clear previous messages
    messageDiv.innerHTML = '';

    // Validation
    if (!email || !password || !confirmPassword) {
      messageDiv.innerHTML = '<div class="bg-red-50 border-l-4 border-red-400 p-4 text-red-700 text-sm">Please fill in all fields.</div>';
      return;
    }

    if (password !== confirmPassword) {
      messageDiv.innerHTML = '<div class="bg-red-50 border-l-4 border-red-400 p-4 text-red-700 text-sm">Passwords do not match.</div>';
      return;
    }

    if (password.length < 6) {
      messageDiv.innerHTML = '<div class="bg-red-50 border-l-4 border-red-400 p-4 text-red-700 text-sm">Password must be at least 6 characters long.</div>';
      return;
    }

    // Disable button and show loading
    button.disabled = true;
    button.innerHTML = '<svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white inline" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Creating Account...';

    // Create user with Firebase
    auth.createUserWithEmailAndPassword(email, password)
      .then(function(userCredential) {
        // User created successfully
        const user = userCredential.user;

        // Get ID token and send to backend to create Rails user
        return user.getIdToken();
      })
      .then(function(accessToken) {
        // Send token to backend to create user in Rails database
        // Include verification token for locked website owner signups
        const verificationToken = document.getElementById('verification-token')?.value;
        const requestBody = { token: accessToken };
        if (verificationToken) {
          requestBody.verification_token = verificationToken;
        }

        return fetch('/api_public/v1/auth/firebase', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(requestBody)
        });
      })
      .then(function(response) {
        if (response.ok) {
          return response.json();
        } else {
          throw new Error('Failed to create user in database');
        }
      })
      .then(function(data) {
        <% if @require_owner_email %>
        // Owner signup - they have admin privileges automatically
        messageDiv.innerHTML = '<div class="bg-green-50 border-l-4 border-green-400 p-4 text-green-700 text-sm">' +
          'Account created successfully! You are now the admin of this website. ' +
          'Redirecting to login...</div>';

        // Sign out and redirect to login
        auth.signOut();
        setTimeout(function() {
          window.location.href = '/pwb_login';
        }, 2000);
        <% else %>
        messageDiv.innerHTML = '<div class="bg-green-50 border-l-4 border-green-400 p-4 text-green-700 text-sm">' +
          'Account created successfully! Please contact an administrator to grant you admin privileges. ' +
          'You will be redirected to the login page in 3 seconds...</div>';

        // Sign out the user (they need admin privileges before accessing admin panel)
        auth.signOut();

        // Redirect to login after 3 seconds
        setTimeout(function() {
          window.location.href = '/pwb_login';
        }, 3000);
        <% end %>
      })
      .catch(function(error) {
        let errorMessage = 'An error occurred. Please try again.';

        switch(error.code) {
          case 'auth/email-already-in-use':
            errorMessage = 'This email address is already registered. Please sign in instead.';
            break;
          case 'auth/invalid-email':
            errorMessage = 'Invalid email address.';
            break;
          case 'auth/weak-password':
            errorMessage = 'Password is too weak. Please choose a stronger password.';
            break;
          case 'auth/operation-not-allowed':
            errorMessage = 'Email/password accounts are not enabled. Please contact the administrator.';
            break;
          default:
            errorMessage = error.message;
        }

        messageDiv.innerHTML = '<div class="bg-red-50 border-l-4 border-red-400 p-4 text-red-700 text-sm">' + errorMessage + '</div>';
        button.innerHTML = 'Create Account';
        button.disabled = false;
      });
  });
</script>
