<?php

namespace App\Livewire;

use Livewire\Component;

class CountrySelect extends Component
{
    public $selectedCountry;
    public $countrySearch = '';
    public $search = '';
    public $isOpen = false;
    public $initialCountry;
    
    protected $rules = [
        'selectedCountry' => 'required',
    ];

    public function mount($initialCountry = null)
    {
        $this->selectedCountry = $initialCountry;
    }

    public function selectCountry($code)
    {
        $this->selectedCountry = $code;
        $this->isOpen = false;
        $this->search = ''; // Limpiar la búsqueda al seleccionar
    }
    
    public function render()
    {
        $countries = collect(config('countries'))
            ->when($this->search, function($collection) {
                // Corregimos el filtrado aquí
                return $collection->filter(function($name, $code) {
                    $searchLower = strtolower($this->search);
                    $nameLower = strtolower($name);
                    $codeLower = strtolower($code);
                    
                    return str_contains($nameLower, $searchLower) || 
                           str_contains($codeLower, $searchLower);
                });
            });
            
        return view('livewire.country-select', compact('countries'));
    }
    
    public function formattedCountry($code, $name)
    {
        return $this->getFlagEmoji($code).' '.$name.' ('.strtoupper($code).')';
    }
    
    protected function getFlagEmoji($countryCode) 
    {
        $countryCode = strtoupper($countryCode);
        $flagOffset = 0x1F1E6;
        $asciiOffset = 0x41;
        
        $firstChar = ord($countryCode[0]) - $asciiOffset + $flagOffset;
        $secondChar = ord($countryCode[1]) - $asciiOffset + $flagOffset;
        
        return mb_convert_encoding('&#'.intval($firstChar).';', 'UTF-8', 'HTML-ENTITIES')
             . mb_convert_encoding('&#'.intval($secondChar).';', 'UTF-8', 'HTML-ENTITIES');
    }
}
