<?php

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Livewire\Attributes\Title;
use Livewire\Component;
use App\Mail\UserRegistered;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rules\Password;
use Illuminate\Support\Str;

new #[Title('Inscription')]
class extends Component {

    public string $firstname = '';
    public string $name = '';
    public string $email = '';
    public string $password = '';
    public string $password_confirmation = '';
    public bool   $newsletter = false;
    public ?string $generatedPassword = null;
    public ?string $gender = null;

    /**
     * Enregistre un nouvel utilisateur dans la base de données.
     */
    public function register()
    {
        if ($this->gender) {
            abort(403);
        }

        $data = $this->validate([
            'firstname'  => 'required|string|max:255',
            'name'       => 'required|string|max:255',
            'newsletter' => 'nullable|boolean',
            'email'      => 'required|string|email|unique:users',
            'password' => [
                'required',
                'confirmed',
                Password::min(8)
                    ->mixedCase()   // Majuscules & Minuscules
                    ->numbers()     // Chiffres
                    ->symbols()     // Caractères spéciaux
                    ->uncompromised(), // Vérifie via "Have I Been Pwned" si le mot de passe a fuité sur le web
            ],
            'password_confirmation' => 'required',
        ]);

        $data['password'] = Hash::make($data['password']);
        $user = User::create($data);
        auth()->login($user);
        request()->session()->regenerate();

        Mail::to($user)->send(new UserRegistered());

        session()->flash('registered', __('Votre compte a été créé avec succès. Un e-mail de confirmation vous a été envoyé.'));

        return redirect('/');
    }

    /**
     * Génère un mot de passe aléatoire et le remplit dans les champs de mot de passe.
     */
    public function generatePassword(): void
    {
        $this->generatedPassword = Str::password(14);
        $this->password = $this->generatedPassword;
        $this->password_confirmation = $this->generatedPassword;
    }

}; ?>

<div class="flex items-center justify-center min-h-[calc(100vh-16rem)] py-12 px-4">
    <div class="w-full max-w-xl">
        <x-card
            title="{{ __('Créer un compte') }}"
            subtitle="{{ __('Renseignez vos informations pour passer une commande sur notre boutique') }}"
            class="shadow-xl bg-base-100"
            separator
            progress-indicator
        >
            <x-form wire:submit="register" x-data="{ rgpd: false }" class="space-y-4">
                {{-- Champ Honeypot Anti-Bot --}}
                <div class="hidden">
                    <x-input wire:model="gender" type="text" />
                </div>

                {{-- Prénom & Nom sur la même ligne en Desktop --}}
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <x-input
                        label="{{ __('Prénom') }}"
                        wire:model="firstname"
                        icon="o-user"
                        required
                    />
                    <x-input
                        label="{{ __('Nom') }}"
                        wire:model="name"
                        icon="o-user"
                        required
                    />
                </div>

                <x-input
                    label="{{ __('Adresse e-mail') }}"
                    wire:model="email"
                    icon="o-envelope"
                    type="email"
                    required
                />

                <div class="space-y-3">
                    <x-password
                        label="{{ __('Mot de passe') }}"
                        wire:model="password"
                        password-icon="o-key"
                        hint="{{ __('8 caractères min., majuscule, minuscule, chiffre et symbole.') }}"
                        clearable
                        required
                    />

                    <x-password
                        label="{{ __('Confirmer le mot de passe') }}"
                        wire:model="password_confirmation"
                        password-icon="o-key"
                        clearable
                        required
                    />

                    <div class="flex justify-end">
                        <x-button
                            type="button"
                            label="{{ __('Générer un mot de passe sécurisé') }}"
                            wire:click="generatePassword"
                            icon="o-wrench"
                            class="btn-ghost btn-xs text-primary"
                        />
                    </div>

                    {{-- Alerte d'affichage du mot de passe généré --}}
                    @if($generatedPassword)
                        <div
                            x-data="{ copied: false }"
                            class="alert alert-warning shadow-sm mt-3 flex items-center justify-between p-3 rounded-xl"
                        >
                            <div class="flex items-center gap-3">
                                <x-icon name="o-key" class="w-5 h-5 shrink-0" />
                                <div class="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-2">
                                    <span class="font-semibold text-xs text-base-content whitespace-nowrap">
                                        {{ __('Mot de passe généré :') }}
                                    </span>
                                    <code class="font-mono bg-base-100 px-2.5 py-1 rounded-md text-sm font-bold text-base-content select-all tracking-wider border border-base-300">
                                        {{ $generatedPassword }}
                                    </code>
                                </div>
                            </div>

                            {{-- Bouton Copier en HTML/DaisyUI pur pour éviter tout bug avec Livewire/MaryUI --}}
                            <button
                                type="button"
                                class="btn btn-xs gap-1 transition-all"
                                :class="copied ? 'btn-success text-white' : 'btn-ghost bg-base-100/60 hover:bg-base-100 text-base-content'"
                                @click="
                                    navigator.clipboard.writeText('{{ $generatedPassword }}');
                                    copied = true;
                                    setTimeout(() => copied = false, 2000);
                                "
                            >
                                <template x-if="!copied">
                                    <span class="flex items-center gap-1">
                                        <x-icon name="o-document-duplicate" class="w-3.5 h-3.5" />
                                        <span>{{ __('Copier') }}</span>
                                    </span>
                                </template>

                                <template x-if="copied">
                                    <span class="flex items-center gap-1">
                                        <x-icon name="o-check" class="w-3.5 h-3.5" />
                                        <span>{{ __('Copié !') }}</span>
                                    </span>
                                </template>
                            </button>
                        </div>
                    @endif
                </div>

                <div class="divider my-2"></div>

                <div class="space-y-2">
                    <x-checkbox
                        label="{{ __('Je souhaite recevoir la newsletter') }}"
                        wire:model="newsletter"
                        class="checkbox-primary checkbox-sm"
                    />

                    <x-checkbox
                        label="{!! __('J\'accepte les conditions générales et la politique de confidentialité') !!}"
                        x-model="rgpd"
                        class="checkbox-primary checkbox-sm"
                    />
                </div>

                <p class="text-xs text-base-content/60 pt-2">
                    <span class="text-error">*</span> @lang('Champs obligatoires')
                </p>

                <x-slot:actions>
                    <div class="flex flex-col sm:flex-row items-center justify-between gap-3 w-full pt-2">
                        <x-button
                            label="{{ __('Déjà inscrit ?') }}"
                            class="btn-ghost btn-sm w-full sm:w-auto order-2 sm:order-1"
                            link="/login"
                        />

                        <x-button
                            x-show="rgpd"
                            label="{{ __('Créer mon compte') }}"
                            type="submit"
                            icon-right="o-arrow-right"
                            class="btn-primary btn-sm w-full sm:w-auto order-1 sm:order-2"
                            spinner="register"
                        />
                    </div>
                </x-slot:actions>
            </x-form>
        </x-card>
    </div>
</div>
