<!DOCTYPE html>
<html lang="en">
  {% load static %}

  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Welcome to Tayapromediverse</title>

    <link rel="stylesheet" href="{% static 'css/signin.css' %}" />

    <link
      href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap"
      rel="stylesheet"
    />

    <!-- Toastify CSS -->
    <link
      rel="stylesheet"
      type="text/css"
      href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css"
    />
  </head>

  <body>
    <div class="container">
      <!-- Left side -->
      <div class="left-side">
        <img
          src="{% static 'images/logo-desktop.png' %}"
          alt="Tayapromediverse Logo"
        />
      </div>

      <!-- Right side -->
      <div class="right-side">
        <div class="mobile-logo">
          <img
            src="{% static 'images/logo-mobile.png' %}"
            alt="Tayapromediverse Mobile Logo"
            style="max-width: 180px"
          />
        </div>

        <div class="form-container">
          <h2>Welcome to Tayapromediverse</h2>

          <!-- Google Login Button -->
          <a href="/accounts/google/login/" class="google-btn">
            <svg width="20" height="20" viewBox="0 0 24 24">
              <path
                fill="#4285f4"
                d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
              />
              <path
                fill="#34a853"
                d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
              />
              <path
                fill="#fbbc05"
                d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
              />
              <path
                fill="#ea4335"
                d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
              />
            </svg>
            Continue with Google
          </a>

          <div class="divider">
            <span class="line"></span>
            <span>Instant Sign In</span>
            <span class="line"></span>
          </div>

          <!-- Login Form -->
          <form
            id="loginForm"
            method="POST"
            action="{% url 'login' %}"
            autocomplete="off"
          >
            {% csrf_token %}

            <!-- Hidden dummy fields to stop Chrome autofill -->
            <input type="text" style="display: none" autocomplete="username" />
            <input
              type="password"
              style="display: none"
              autocomplete="new-password"
            />

            <!-- Actual visible fields -->
            <input
              type="email"
              id="email"
              class="input-box"
              placeholder="Email"
              name="login_email"
              autocomplete="off"
              required
            />
            <div class="error-message" id="emailError"></div>

            <input
              type="password"
              id="password"
              class="input-box"
              placeholder="Password"
              name="login_pass"
              autocomplete="new-password"
              required
            />
            <div class="error-message" id="passwordError"></div>

            <div class="checkbox">
              <div class="checkbox-left">
                <input type="checkbox" id="remember" />
                <label for="remember">Remember Me</label>
              </div>
              <a href="{% url 'forgot-password' %}" class="forgot-link"
                >Forgot your password?</a
              >
            </div>

            <div
              class="success-message"
              id="successMessage"
              style="display: none"
            ></div>

            <div class="button-container">
              <button type="submit" class="login-btn" id="loginBtn">
                Login
              </button>
              <a href="{% url 'signup' %}" class="signup-btn" id="signupBtn"
                >Sign Up</a
              >
            </div>
          </form>

          <div class="terms">
            By signing into <b>Tayapromediverse</b>, you agree to our
            <a href="{% url 'term' %}">Terms of Service</a> and
            <a href="{% url 'term' %}">Privacy Policy</a>.
          </div>
        </div>
      </div>
    </div>

    <script>
      // === Error Handling ===
      function clearErrors() {
        document.querySelectorAll(".error-message").forEach((el) => {
          el.textContent = "";
        });
      }

      function showError(field, message) {
        const errorElement = document.getElementById(field + "Error");
        if (errorElement) {
          errorElement.textContent = message;
        }
      }

      // === Get CSRF Token from cookie ===
      function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== "") {
          const cookies = document.cookie.split(";");
          for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === name + "=") {
              cookieValue = decodeURIComponent(
                cookie.substring(name.length + 1)
              );
              break;
            }
          }
        }
        return cookieValue;
      }

      // === Form Submit Handler ===
      document
        .getElementById("loginForm")
        .addEventListener("submit", function (e) {
          e.preventDefault();

          const email = document.getElementById("email");
          const password = document.getElementById("password");
          const loginBtn = document.getElementById("loginBtn");
          const successMessage = document.getElementById("successMessage");

          clearErrors();
          loginBtn.disabled = true;
          loginBtn.textContent = "Logging in...";

          const remember = document.getElementById("remember").checked;

          const formData = {
            email: email.value.trim(),
            password: password.value,
            remember: remember,
          };

          fetch("/login/", {
            method: "POST",
            credentials: "same-origin",
            headers: {
              "Content-Type": "application/json",
              "X-CSRFToken": getCookie("csrftoken"),
            },
            body: JSON.stringify(formData),
          })
            .then((response) => {
              const contentType = response.headers.get("content-type");
              if (
                contentType &&
                contentType.indexOf("application/json") !== -1
              ) {
                return response.json();
              } else {
                // If not JSON, show a generic error
                throw new Error(
                  "Server returned an unexpected response. Please try again."
                );
              }
            })
            .then((data) => {
              if (data.success) {
                successMessage.textContent = "Login successful! Redirecting...";
                successMessage.style.display = "block";
                setTimeout(() => {
                  window.location.href = data.redirect;
                }, 1500);
              } else {
                if (data.errors) {
                  for (const [field, message] of Object.entries(data.errors)) {
                    showError(field, message);
                  }
                }
                loginBtn.disabled = false;
                loginBtn.textContent = "Login";
              }
            })
            .catch((error) => {
              console.error("Error:", error);
              alert(error.message || "An error occurred. Please try again.");
              loginBtn.disabled = false;
              loginBtn.textContent = "Login";
            });
        });
    </script>

    <!-- Toastify JS -->
    <script
      type="text/javascript"
      src="https://cdn.jsdelivr.net/npm/toastify-js"
    ></script>

    <!-- Toastify Utils -->
    <script src="{% static 'js/toastify-utils.js' %}"></script>

    <!-- Django Messages with Toastify -->
    {% if messages %}
    <div id="django-messages" style="display: none">
      {% for message in messages %}
      <div
        data-type="{{ message.tags }}"
        data-message="{{ message|escapejs }}"
      ></div>
      {% endfor %}
    </div>
    {% endif %}
  </body>
</html>
