<section>
    @php
        $settingsSection = isset($settingsSection) && is_string($settingsSection) ? $settingsSection : null;
        $profileUpdateRouteParams = $settingsSection ? ['section' => $settingsSection] : [];
        $organizationSetting = $organizationSetting ?? null;
        $organizationCompanies = ($organizationCompanies ?? collect()) instanceof \Illuminate\Support\Collection
            ? $organizationCompanies
            : collect($organizationCompanies ?? []);
        $organizationChildCompanies = ($organizationChildCompanies ?? collect()) instanceof \Illuminate\Support\Collection
            ? $organizationChildCompanies
            : collect($organizationChildCompanies ?? []);
        $showOrganizationCompanySelector = $organizationChildCompanies->isNotEmpty();
        $initial = mb_strtoupper(mb_substr((string) $user->name, 0, 1));
        $existingPhotoUrl = \App\Support\ProfileAvatarManager::url($user->profile_photo_path);
        $startPhotoUrl = old('remove_profile_photo') ? '' : ($existingPhotoUrl ?? '');
        $startZoom = (float) old('profile_photo_zoom', $user->profile_photo_zoom ?? \App\Support\ProfileAvatarManager::DEFAULT_ZOOM);
    @endphp

    <header>
        <h2 class="text-lg font-medium text-gray-900">
            {{ __('Profile Information') }}
        </h2>

        <p class="mt-1 text-sm text-gray-600">
            {{ __("Update your account's profile information and email address.") }}
        </p>
    </header>

    <form id="send-verification" method="post" action="{{ route('verification.send') }}">
        @csrf
    </form>

    <form method="post" action="{{ route('profile.update', $profileUpdateRouteParams) }}" enctype="multipart/form-data" class="mt-6 space-y-6"
          x-data="{
            previewUrl: @js($startPhotoUrl),
            initialPreviewUrl: @js($existingPhotoUrl),
            initials: @js($initial),
            zoom: @js($startZoom),
            removePhoto: @js((bool) old('remove_profile_photo')),
            onPhotoChange(event) {
                const file = event.target.files?.[0];
                if (!file) {
                    return;
                }

                this.removePhoto = false;
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.previewUrl = typeof e.target?.result === 'string' ? e.target.result : '';
                };
                reader.readAsDataURL(file);
            },
            avatarStyle() {
                return `object-position: center center; transform: scale(${this.zoom}); transform-origin: center center;`;
            },
            onRemoveToggle() {
                if (this.removePhoto) {
                    this.previewUrl = '';
                } else if (!this.previewUrl) {
                    this.previewUrl = this.initialPreviewUrl || '';
                }
            }
          }">
        @csrf
        @method('patch')
        @if ($settingsSection)
            <input type="hidden" name="_settings_section" value="{{ $settingsSection }}">
        @endif

        <div>
            <x-input-label for="name" :value="__('Name')" />
            <x-text-input id="name" name="name" type="text" class="mt-1 block w-full" :value="old('name', $user->name)" required autofocus autocomplete="name" />
            <x-input-error class="mt-2" :messages="$errors->get('name')" />
        </div>

        <div>
            <x-input-label for="email" :value="__('Email')" />
            <x-text-input id="email" name="email" type="email" class="mt-1 block w-full" :value="old('email', $user->email)" required autocomplete="username" />
            <x-input-error class="mt-2" :messages="$errors->get('email')" />

            @if ($user instanceof \Illuminate\Contracts\Auth\MustVerifyEmail && ! $user->hasVerifiedEmail())
                <div>
                    <p class="text-sm mt-2 text-gray-800">
                        {{ __('Your email address is unverified.') }}

                        <button form="send-verification" class="underline text-sm text-gray-600 hover:text-gray-900 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            {{ __('Click here to re-send the verification email.') }}
                        </button>
                    </p>

                    @if (session('status') === 'verification-link-sent')
                        <p class="mt-2 font-medium text-sm text-green-600">
                            {{ __('A new verification link has been sent to your email address.') }}
                        </p>
                    @endif
                </div>
            @endif
        </div>

        <div class="grid grid-cols-1 gap-4 lg:grid-cols-2">
            <div>
                <x-input-label for="phone" :value="__('Telephone')" />
                <x-text-input id="phone" name="phone" type="text" class="mt-1 block w-full" :value="old('phone', $user->phone)" autocomplete="tel" />
                <x-input-error class="mt-2" :messages="$errors->get('phone')" />
            </div>

            <div>
                <x-input-label for="job_title" :value="__('Job title')" />
                <x-text-input id="job_title" name="job_title" type="text" class="mt-1 block w-full" :value="old('job_title', $user->job_title)" />
                <x-input-error class="mt-2" :messages="$errors->get('job_title')" />
            </div>

            <div>
                <x-input-label for="manager_id" :value="__('Supervisor')" />
                <x-user-search-select
                    id="manager_id"
                    name="manager_id"
                    :users="$managers"
                    :selected="old('manager_id', $user->manager_id)"
                    :placeholder="__('Search for a leader')"
                    :empty-label="__('Not selected')"
                />
                <x-input-error class="mt-2" :messages="$errors->get('manager_id')" />
            </div>

            @if ($showOrganizationCompanySelector)
                <div>
                    <x-input-label for="organization_company_id" :value="__('Company')" />
                    <select id="organization_company_id" name="organization_company_id" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                        <option value="">{{ __('Not selected') }}</option>
                        @foreach ($organizationChildCompanies as $organizationCompany)
                            @php
                                $parentName = $organizationCompany->parent?->name;
                                $label = $parentName ? $parentName.' / '.$organizationCompany->name : $organizationCompany->name;
                            @endphp
                            <option value="{{ $organizationCompany->id }}" @selected((int) old('organization_company_id', $user->organization_company_id) === (int) $organizationCompany->id)>
                                {{ $label }}
                            </option>
                        @endforeach
                    </select>
                    <x-input-error class="mt-2" :messages="$errors->get('organization_company_id')" />
                </div>
            @endif

            <div>
                <x-input-label for="birth_date" :value="__('Date of birth')" />
                <x-text-input id="birth_date" name="birth_date" type="date" class="mt-1 block w-full" :value="old('birth_date', $user->birth_date?->format('Y-m-d'))" />
                <x-input-error class="mt-2" :messages="$errors->get('birth_date')" />
            </div>
        </div>

        <div>
            <x-input-label for="profile_photo" :value="__('Profile picture')" />
            <p class="mt-1 text-xs text-gray-500">{{ __('Upload a photo and, if necessary, adjust only the scale.') }}</p>

            <div class="mt-3 grid grid-cols-1 gap-4 lg:grid-cols-2">
                <div class="space-y-3">
                    <input
                        id="profile_photo"
                        type="file"
                        name="profile_photo"
                        accept="image/*"
                        @change="onPhotoChange"
                        class="block w-full text-sm text-gray-700 file:mr-4 file:rounded-md file:border-0 file:bg-indigo-50 file:px-3 file:py-2 file:text-sm file:font-medium file:text-indigo-700 hover:file:bg-indigo-100"
                    >

                    <label class="inline-flex items-center gap-2 text-sm text-gray-700">
                        <input
                            type="checkbox"
                            name="remove_profile_photo"
                            value="1"
                            x-model="removePhoto"
                            @change="onRemoveToggle"
                            class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
                        >
                        {{ __('Delete current photo') }}
                    </label>

                    <x-input-error class="mt-2" :messages="$errors->get('profile_photo')" />
                </div>

                <div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
                    <p class="mb-2 text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Preview') }}</p>
                    <div class="mx-auto h-32 w-32 overflow-hidden rounded-full border border-gray-300 bg-white shadow-inner">
                        <template x-if="previewUrl">
                            <img :src="previewUrl" alt="Avatar preview" class="h-full w-full object-cover" :style="avatarStyle()">
                        </template>
                        <template x-if="!previewUrl">
                            <span class="flex h-full w-full items-center justify-center text-xl font-semibold text-gray-500" x-text="initials"></span>
                        </template>
                    </div>
                </div>
            </div>

            <div class="mt-4 grid grid-cols-1 gap-3">
                <div>
                    <label for="profile_photo_zoom" class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Scale') }}</label>
                    <input id="profile_photo_zoom" type="range" min="1" max="3" step="0.05" x-model="zoom" class="mt-2 w-full">
                    <input type="hidden" name="profile_photo_zoom" :value="zoom">
                    <p class="mt-1 text-xs text-gray-500"><span x-text="Number(zoom).toFixed(2)"></span>x</p>
                    <x-input-error class="mt-1" :messages="$errors->get('profile_photo_zoom')" />
                </div>
            </div>
        </div>

        <div class="flex items-center gap-4">
            <x-primary-button>{{ __('Save') }}</x-primary-button>

            @if (session('status') === 'profile-updated')
                <p
                    x-data="{ show: true }"
                    x-show="show"
                    x-transition
                    x-init="setTimeout(() => show = false, 2000)"
                    class="text-sm text-gray-600"
                >{{ __('Saved.') }}</p>
            @endif
        </div>
    </form>
</section>
