<?php

namespace App\Livewire;

use App\Models\Language;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cookie;
use Livewire\Component;

class LocaleSelector extends Component
{
    public string $currentLocale;

    public bool $dropUp = true;

    public bool $alignStart = false;

    public function mount(bool $dropUp = true, bool $alignStart = false): void
    {
        $this->currentLocale = App::getLocale();
        $this->dropUp = $dropUp;
        $this->alignStart = $alignStart;
    }

    public function setLocale(string $locale): void
    {
        // Validate locale exists and is active
        $language = Language::where('code', $locale)
            ->where('status', 'active')
            ->first();

        if (! $language) {
            return;
        }

        // Update user preference if authenticated
        if (auth()->check()) {
            auth()->user()->update(['locale' => $locale]);
        }

        // Store in session for immediate effect
        session(['locale' => $locale]);

        // Set cookie for guests (30 days)
        Cookie::queue('locale', $locale, 60 * 24 * 30);

        // Update current locale
        $this->currentLocale = $locale;
        App::setLocale($locale);

        // Refresh the page to apply translations (full reload required for Blade components)
        $this->redirect(request()->header('Referer', url('/')));
    }

    public function render()
    {
        return view('livewire.locale-selector', [
            'languages' => Language::where('status', 'active')
                ->orderBy('name')
                ->get(),
        ]);
    }
}
