{% extends 'public_base.html' %}
{% block title %}
    Login
{% endblock %}

{% block content %}
{% load static %}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
  :root {
    --primary: #6366f1;
    --accent: #4f46e5;
    --gradient-start: #6366f1;
    --gradient-end: #8b5cf6;
    --bg: #ffffff;
    --muted: #6b7280;
    --danger: #ef4444;
    --success: #10b981;
    --radius: 16px;
    --shadow: 0 20px 40px rgba(99, 102, 241, 0.15);
    --shadow-hover: 0 25px 50px rgba(99, 102, 241, 0.25);
  }

  body {
    font-family: 'Inter', sans-serif;
    margin: 0;
    padding: 0;
    background: linear-gradient(135deg, #f0f4ff 0%, #fdf2ff 50%, #f0fdf4 100%);
    min-height: 100vh;
  }

  .login-page {
    display: flex;
    min-height: 100vh;
    align-items: center;
    justify-content: center;
    padding: 2rem;
    position: relative;
    overflow: hidden;
  }

  .login-page::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(99, 102, 241, 0.05) 0%, transparent 70%);
    animation: float 20s ease-in-out infinite;
  }

  @keyframes float {
    0%, 100% { transform: translate(0, 0) rotate(0deg); }
    25% { transform: translate(10px, 10px) rotate(1deg); }
    50% { transform: translate(-5px, 15px) rotate(-1deg); }
    75% { transform: translate(15px, -5px) rotate(1deg); }
  }

  .login-container {
    display: flex;
    max-width: 1200px;
    width: 100%;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: var(--radius);
    box-shadow: var(--shadow);
    overflow: hidden;
    border: 1px solid rgba(255, 255, 255, 0.2);
    position: relative;
    z-index: 1;
  }

  .login-left {
    flex: 1;
    padding: 4rem 3rem;
    background: white;
    position: relative;
  }

  .login-left::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(to bottom, var(--gradient-start), var(--gradient-end));
  }

  .form-container {
    max-width: 400px;
    margin: 0 auto;
  }

  .logo-section {
    text-align: center;
    margin-bottom: 2.5rem;
  }

  .logo {
    width: 60px;
    height: 60px;
    background: linear-gradient(135deg, var(--gradient-start), var(--gradient-end));
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 1rem;
    box-shadow: 0 10px 25px rgba(99, 102, 241, 0.3);
  }

  .logo i {
    font-size: 1.8rem;
    color: white;
  }

  .form-container h3 {
    margin-bottom: 0.5rem;
    font-size: 2rem;
    font-weight: 800;
    background: linear-gradient(135deg, var(--gradient-start), var(--gradient-end));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    text-align: center;
  }

  .form-container p.subtext {
    margin-bottom: 2.5rem;
    font-size: 1rem;
    color: var(--muted);
    text-align: center;
    line-height: 1.6;
  }

  .form-group {
    margin-bottom: 1.5rem;
    position: relative;
  }

  .form-label {
    display: block;
    margin-bottom: 0.5rem;
    font-size: 0.9rem;
    font-weight: 600;
    color: #374151;
  }

  .input-group {
    position: relative;
  }

  .form-control {
    width: 100%;
    padding: 1rem 1rem 1rem 3rem;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    font-size: 1rem;
    transition: all 0.3s ease;
    background: #fafafa;
  }

  .form-control:focus {
    border-color: var(--accent);
    background: white;
    box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
    outline: none;
    transform: translateY(-2px);
  }

  .input-icon {
    position: absolute;
    left: 1rem;
    top: 50%;
    transform: translateY(-50%);
    color: var(--muted);
    transition: all 0.3s ease;
  }

  .form-control:focus + .input-icon {
    color: var(--accent);
  }

  .form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;
  }

  .remember-me {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.9rem;
    color: var(--muted);
  }

  .forgot-password {
    color: var(--accent);
    text-decoration: none;
    font-size: 0.9rem;
    font-weight: 500;
  }

  .forgot-password:hover {
    color: var(--gradient-end);
    text-decoration: underline;
  }

  .btn-submit {
    background: linear-gradient(135deg, var(--gradient-start), var(--gradient-end));
    color: white;
    border: none;
    padding: 1rem 2rem;
    width: 100%;
    border-radius: 12px;
    font-weight: 600;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 10px 25px rgba(99, 102, 241, 0.3);
    position: relative;
    overflow: hidden;
  }

  .btn-submit:hover {
    transform: translateY(-3px);
    box-shadow: var(--shadow-hover);
  }

  /* OTP Button */
  .btn-otp {
    background: linear-gradient(135deg, #10b981, #059669);
    margin-top: 1rem;
  }

  .btn-otp:hover {
    background: linear-gradient(135deg, #059669, #047857);
    transform: translateY(-3px);
    box-shadow: var(--shadow-hover);
  }

  .signup-link {
    text-align: center;
    font-size: 0.9rem;
    color: var(--muted);
    margin-top: 1.5rem;
  }

  .signup-link a {
    color: var(--accent);
    font-weight: 600;
  }

  .login-right {
    flex: 1;
    background: linear-gradient(135deg, var(--gradient-start), var(--gradient-end));
    padding: 4rem 3rem;
    color: white;
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: relative;
    overflow: hidden;
  }

  .login-right::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
  }

  .features-title {
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 2rem;
  }

  .feature-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 1.5rem;
  }

  .feature-icon {
    width: 24px;
    height: 24px;
    background: rgba(255,255,255,0.2);
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 1rem;
    flex-shrink: 0;
  }

  .alert {
    padding: 1rem 1.5rem;
    margin-bottom: 1.5rem;
    border-radius: 12px;
    font-size: 0.9rem;
    border-left: 4px solid;
  }

  .alert-success { background: rgba(16,185,129,0.1); border-color: var(--success); color: #065f46; }
  .alert-danger { background: rgba(239,68,68,0.1); border-color: var(--danger); color: #991b1b; }

  /* Modal Styles (No Bootstrap) */
  .otp-modal {
    display: none;
    position: fixed;
    top: 0; left: 0; width: 100%; height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 1000;
    align-items: center;
    justify-content: center;
  }

  .otp-modal.active {
    display: flex;
  }

  .otp-modal-content {
    background: white;
    border-radius: 16px;
    box-shadow: var(--shadow);
    width: 90%;
    max-width: 480px;
    overflow: hidden;
  }

  .otp-modal-header {
    padding: 1.5rem 2rem;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .otp-modal-body {
    padding: 2rem;
  }

  .otp-input-group {
    display: flex;
    gap: 12px;
    justify-content: center;
    margin: 1.5rem 0;
  }

  .otp-input {
    width: 56px;
    height: 64px;
    text-align: center;
    font-size: 1.8rem;
    font-weight: bold;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
  }

  .otp-input:focus {
    border-color: var(--accent);
    box-shadow: 0 0 0 4px rgba(99,102,241,0.1);
    outline: none;
  }

  @media (max-width: 768px) {
    .login-container { flex-direction: column; max-width: 500px; }
    .login-left::before { display: none; }
    .login-right { display: none; }
    .login-left { padding: 3rem 2rem; }
  }
</style>

<div class="login-page">
  <div class="login-container">
    <div class="login-left">
      <div class="form-container">
        <div class="logo-section">
          <div class="logo">
            <i class="fas fa-shield-alt"></i>
          </div>
          <h3>Welcome Back</h3>
          <p class="subtext">Sign in to your account to continue</p>
        </div>

        {% if messages %}
          {% for message in messages %}
            <div class="alert {% if 'success' in message.tags %}alert-success{% else %}alert-danger{% endif %}">
              {{ message }}
            </div>
          {% endfor %}
        {% endif %}

        <form method="POST" action="{% url 'login' %}">
          {% csrf_token %}
          <input type="hidden" name="next" value="{{ request.GET.next }}">

          <div class="form-group">
            <label class="form-label" for="username">Username</label>
            <div class="input-group">
              <input id="username" name="username" class="form-control" placeholder="Enter your username" required autofocus type="text">
              <div class="input-icon"><i class="fas fa-user"></i></div>
            </div>
          </div>

          <div class="form-group">
            <label class="form-label" for="password">Password</label>
            <div class="input-group">
              <input type="password" id="password" name="password" class="form-control" placeholder="Enter your password" required>
              <div class="input-icon"><i class="fas fa-lock"></i></div>
            </div>
          </div>

          <div class="form-options">
            <label class="remember-me">
              <input type="checkbox" name="remember"> Remember me
            </label>
            <a href="{% url 'password_reset' %}" class="forgot-password">Forgot password?</a>
          </div>

          <button type="submit" class="btn-submit">
            <i class="fas fa-sign-in-alt"></i> Sign In
          </button>

          <button type="button" class="btn-submit btn-otp" id="openOtpModal">
            <i class="fas fa-mobile-alt"></i> Login with OTP
          </button>

          <div class="signup-link">
            Don't have an account? <a href="{% url 'signup' %}">Sign up here</a>
          </div>
        </form>
      </div>
    </div>

    <div class="login-right">
      <h2 class="features-title">Why Choose Us?</h2>
      <ul class="feature-list">
        <li class="feature-item">
          <div class="feature-icon"><i class="fas fa-rocket"></i></div>
          <div class="feature-text"><strong>Lightning Fast</strong><br>Quick and seamless login experience</div>
        </li>
        <li class="feature-item">
          <div class="feature-icon"><i class="fas fa-shield-alt"></i></div>
          <div class="feature-text"><strong>Bank-Level Security</strong><br>Your data is protected with enterprise-grade security</div>
        </li>
        <li class="feature-item">
          <div class="feature-icon"><i class="fas fa-sync-alt"></i></div>
          <div class="feature-text"><strong>Sync Across Devices</strong><br>Access your account from anywhere, anytime</div>
        </li>
        <li class="feature-item">
          <div class="feature-icon"><i class="fas fa-headset"></i></div>
          <div class="feature-text"><strong>24/7 Support</strong><br>Our team is always here to help you</div>
        </li>
        <li class="feature-item">
          <div class="feature-icon"><i class="fas fa-chart-line"></i></div>
          <div class="feature-text"><strong>Advanced Analytics</strong><br>Get insights into your business performance</div>
        </li>
      </ul>
    </div>
  </div>
</div>

<!-- Custom OTP Modal (No Bootstrap) -->
<div class="otp-modal" id="otpModal">
  <div class="otp-modal-content">
    <div class="otp-modal-header">
      <h5 class="fw-bold">Login with OTP</h5>
      <button type="button" id="closeOtpModal" style="background:none;border:none;font-size:1.5rem;cursor:pointer;">&times;</button>
    </div>
    <div class="otp-modal-body">
      <div id="step1">
        <p class="text-center text-muted mb-4">Enter your registered email or mobile number</p>
        <input type="text" id="otpIdentifier" class="form-control" placeholder="Email or Phone (+91...)" required autofocus>
        <button id="sendOtpBtn" class="btn-submit w-100 mt-4">
          <i class="fas fa-paper-plane"></i> Send OTP
        </button>
      </div>

      <div id="step2" style="display:none;">
        <p class="text-center text-muted mb-4">Enter the 6-digit OTP sent to<br><strong id="sentTo"></strong></p>
        <div class="otp-input-group">
          <input type="text" class="otp-input" maxlength="1" inputmode="numeric">
          <input type="text" class="otp-input" maxlength="1" inputmode="numeric">
          <input type="text" class="otp-input" maxlength="1" inputmode="numeric">
          <input type="text" class="otp-input" maxlength="1" inputmode="numeric">
          <input type="text" class="otp-input" maxlength="1" inputmode="numeric">
          <input type="text" class="otp-input" maxlength="1" inputmode="numeric">
        </div>
        <button id="verifyOtpBtn" class="btn-submit w-100">
          <i class="fas fa-check-circle"></i> Verify & Login
        </button>
        <p class="text-center mt-3">
          <a href="#" id="resendOtp" class="text-muted small">Resend OTP</a>
        </p>
      </div>
    </div>
  </div>
</div>

<script>
  // Modal Controls
  const modal = document.getElementById('otpModal');
  const openBtn = document.getElementById('openOtpModal');
  const closeBtn = document.getElementById('closeOtpModal');
  const step1 = document.getElementById('step1');
  const step2 = document.getElementById('step2');
  const identifierInput = document.getElementById('otpIdentifier');
  const sentTo = document.getElementById('sentTo');
  const otpInputs = document.querySelectorAll('.otp-input');

  openBtn.onclick = () => modal.classList.add('active');
  closeBtn.onclick = () => modal.classList.remove('active');
  modal.onclick = (e) => { if (e.target === modal) modal.classList.remove('active'); };

  // Auto-focus OTP inputs
  otpInputs.forEach((input, i) => {
    input.addEventListener('input', () => {
      if (input.value && i < 5) otpInputs[i + 1].focus();
    });
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Backspace' && !input.value && i > 0) otpInputs[i - 1].focus();
    });
  });

  // Send OTP
  document.getElementById('sendOtpBtn').onclick = async () => {
    const identifier = identifierInput.value.trim();
    if (!identifier) return alert('Please enter email or phone');

    const btn = document.getElementById('sendOtpBtn');
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
    btn.disabled = true;

    const res = await fetch("{% url 'request_otp' %}", {
      method: 'POST',
      headers: { 'X-CSRFToken': '{{ csrf_token }}' },
      body: new URLSearchParams({ 'identifier': identifier })
    });

    if (res.ok) {
      step1.style.display = 'none';
      step2.style.display = 'block';
      sentTo.textContent = identifier;
      otpInputs[0].focus();
    } else {
      alert('Failed to send OTP');
    }
    btn.innerHTML = '<i class="fas fa-paper-plane"></i> Send OTP';
    btn.disabled = false;
  };

  // Verify OTP
  document.getElementById('verifyOtpBtn').onclick = async () => {
    const otp = Array.from(otpInputs).map(i => i.value).join('');
    if (otp.length !== 6) return alert('Enter full 6-digit OTP');

    const btn = document.getElementById('verifyOtpBtn');
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Verifying...';
    btn.disabled = true;

    const res = await fetch("{% url 'verify_otp' %}", {
      method: 'POST',
      headers: { 'X-CSRFToken': '{{ csrf_token }}' },
      body: new URLSearchParams({ 'otp': otp })
    });

    if (res.ok) {
      window.location.href = "{% url 'home' %}";
    } else {
      alert('Invalid or expired OTP');
    }
    btn.innerHTML = '<i class="fas fa-check-circle"></i> Verify & Login';
    btn.disabled = false;
  };

  // Resend
  document.getElementById('resendOtp').onclick = (e) => {
    e.preventDefault();
    step2.style.display = 'none';
    step1.style.display = 'block';
    identifierInput.value = sentTo.textContent;
    identifierInput.focus();
  };

  // Loading spinner on normal login
  document.querySelector('form').addEventListener('submit', function() {
    this.querySelector('.btn-submit').innerHTML = '<i class="fas fa-spinner fa-spin"></i> Signing In...';
  });
</script>
{% endblock %}