<?php
// app/Livewire/Auth/Login.php
namespace App\Livewire\Auth;

use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\ValidationException;

class Login extends Component
{
    public $email = '';
    public $password = '';
    public $remember = false;
    public $theme = 'light';

    protected function rules()
    {
        return [
            'email' => ['required', 'email', 'max:255'],
            'password' => ['required', 'string', 'min:6'],
        ];
    }

    protected function messages()
    {
        return [
            'email.required' => 'We need your email address.',
            'email.email' => 'Please enter a valid email.',
            'password.required' => 'Password cannot be empty.',
            'password.min' => 'Password must be at least 6 characters.',
        ];
    }

    public function mount()
    {
        // Load theme from session or default to light
        $this->theme = session('theme', 'light');
    }

    // Fix: Don't try to call updated() directly - Livewire calls it automatically
    // Remove the updated() method or keep it without manual calls

    public function toggleTheme()
    {
        $this->theme = $this->theme === 'light' ? 'dark' : 'light';
        session(['theme' => $this->theme]);
        
        // Dispatch event with proper payload structure
        $this->dispatch('themeChanged', theme: $this->theme);
    }

    public function login()
    {
        $this->validate();

        // Rate limiting (max 5 attempts per minute)
        $key = strtolower($this->email) . '|' . request()->ip();
        if (RateLimiter::tooManyAttempts($key, 5)) {
            $seconds = RateLimiter::availableIn($key);
            throw ValidationException::withMessages([
                'email' => "Too many login attempts. Please try again in {$seconds} seconds.",
            ]);
        }

        // Attempt authentication
        if (Auth::attempt([
            'email' => $this->email,
            'password' => $this->password,
        ], $this->remember)) {
            RateLimiter::clear($key);
            session()->regenerate();
            
            // Preserve theme setting across redirect
            session(['theme' => $this->theme]);
            
            return redirect()->intended('/dashboard');
        }

        // Failed attempt: increment rate limiter
        RateLimiter::hit($key, 60);

        throw ValidationException::withMessages([
            'email' => 'These credentials do not match our records.',
        ]);
    }

    // Fix: Add proper validation method without manual calls
    public function updatedEmail()
    {
        $this->validateOnly('email');
    }

    public function updatedPassword()
    {
        $this->validateOnly('password');
    }

    public function render()
    {
        return view('livewire.auth.login')->layout('layouts.guest');
    }
}