<?php

namespace App\Livewire\Common;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Livewire\Component;

class LanguageSwitcher extends Component
{
    public string $currentLocale;

    /** Idiomas disponibles con nombre y bandera. */
    public array $languages = [
        'en' => ['name' => 'English', 'flag' => 'gb.svg'],
        'es' => ['name' => 'Español', 'flag' => 'es.svg'],
        'fr' => ['name' => 'Français', 'flag' => 'fr.svg'],
        'ru' => ['name' => 'Русский', 'flag' => 'ru.svg'],
    ];

    public function mount(): void
    {
        $this->currentLocale = App::getLocale();
    }

    public function updatedCurrentLocale(string $locale): void
    {
        if (! in_array($locale, ['en', 'es', 'fr', 'ru'])) {
            return;
        }

        Session::put('locale', $locale);

        if (Auth::check()) {
            $user = Auth::user();
            $user->locale = $locale;
            $user->save();
        }

        // Dispatch a browser event — JavaScript reloads the page.
        $this->dispatch('locale-changed');
    }

    public function switchLanguage(string $locale): void
    {
        $this->updatedCurrentLocale($locale);
    }

    public function render()
    {
        return view('livewire.common.language-switcher');
    }
}
