@php
    $user = $user ?? auth()->user();
    $appearance = is_array($user?->appearance_settings) ? $user->appearance_settings : [];
    $themePayload = app(\App\Support\ThemeManager::class)->themeForUser($user);
    $palette = array_replace($themePayload['palette'] ?? [], $appearance['palette'] ?? []);
    $fonts = array_replace($themePayload['fonts'] ?? [], $appearance['fonts'] ?? []);
    $icons = array_replace($themePayload['icons'] ?? [], $appearance['icons'] ?? []);
    $themePresets = \App\Support\ThemeManager::userPresets();
    $themePresetPayload = collect($themePresets)->map(function ($preset): array {
        return [
            'palette' => is_array($preset['palette'] ?? null) ? $preset['palette'] : [],
            'fonts' => is_array($preset['fonts'] ?? null) ? $preset['fonts'] : [],
            'icons' => is_array($preset['icons'] ?? null) ? $preset['icons'] : [],
        ];
    })->all();
    $selectedPreset = (string) old('preset', (string) ($appearance['preset'] ?? ''));
    $startPageOptions = \App\Support\UserStartPage::options();
    $selectedStartPage = (string) old('start_page', $user?->start_page ?? '');
    $backgroundUrl = $user?->background_image_path
        ? \Illuminate\Support\Facades\Storage::disk('public')->url($user->background_image_path)
        : '';
@endphp

<section class="space-y-6">
    <header>
        <h2 class="text-lg font-medium text-gray-900">{{ __('Appearance') }}</h2>
        <p class="mt-1 text-sm text-gray-600">
            {{ __('Personalize your workspace with your own colors, fonts, and start page.') }}
        </p>
    </header>

    @if (session('status') === 'appearance-updated')
        <div class="rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
            {{ __('Appearance settings updated.') }}
        </div>
    @endif

    <form method="POST" action="{{ route('profile.appearance.update') }}" enctype="multipart/form-data" class="space-y-6" data-appearance-form>
        @csrf
        @method('PATCH')
        @if ($settingsSection ?? false)
            <input type="hidden" name="_settings_section" value="{{ $settingsSection }}">
        @endif

        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div>
                <label for="start_page" class="block text-sm font-medium text-slate-700">{{ __('Start page') }}</label>
                <select id="start_page" name="start_page" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    <option value="">{{ __('Default (Dashboard)') }}</option>
                    @foreach ($startPageOptions as $key => $label)
                        <option value="{{ $key }}" @selected($selectedStartPage === $key)>
                            {{ $label }}
                        </option>
                    @endforeach
                </select>
                <x-input-error class="mt-1" :messages="$errors->get('start_page')" />
            </div>
        </div>

        <div class="rounded-lg border border-slate-200 bg-white p-4">
            <h3 class="text-sm font-semibold text-slate-800">{{ __('Theme presets') }}</h3>
            <p class="mt-1 text-xs text-slate-500">
                {{ __('Choose one of the default themes and then fine-tune colors below.') }}
            </p>
            <div class="mt-3 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
                @foreach ($themePresets as $presetKey => $preset)
                    @php
                        $presetPalette = is_array($preset['palette'] ?? null) ? $preset['palette'] : [];
                    @endphp
                    <label class="cursor-pointer rounded-lg border border-slate-200 bg-slate-50 p-3 transition hover:border-indigo-300 hover:bg-indigo-50">
                        <input
                            type="radio"
                            name="preset"
                            value="{{ $presetKey }}"
                            class="sr-only"
                            data-theme-preset-radio
                            @checked($selectedPreset === $presetKey)
                        >
                        <span class="block text-sm font-semibold text-slate-900">{{ __($preset['name'] ?? '') }}</span>
                        <span class="mt-1 block text-xs text-slate-500">{{ __($preset['description'] ?? '') }}</span>
                        <span class="mt-2 flex items-center gap-2">
                            <span class="inline-flex h-3.5 w-3.5 rounded-full border border-slate-200" style="background: {{ $presetPalette['primary'] ?? '#4F46E5' }}"></span>
                            <span class="inline-flex h-3.5 w-3.5 rounded-full border border-slate-200" style="background: {{ $presetPalette['accent'] ?? '#0EA5E9' }}"></span>
                            <span class="inline-flex h-3.5 w-3.5 rounded-full border border-slate-200" style="background: {{ $presetPalette['background'] ?? '#F3F4F6' }}"></span>
                            <span class="inline-flex h-3.5 w-3.5 rounded-full border border-slate-200" style="background: {{ $presetPalette['sidebar_bg'] ?? '#0F172A' }}"></span>
                        </span>
                    </label>
                @endforeach
                <label class="cursor-pointer rounded-lg border border-slate-200 bg-white p-3 transition hover:border-slate-300 hover:bg-slate-50">
                    <input
                        type="radio"
                        name="preset"
                        value=""
                        class="sr-only"
                        data-theme-preset-radio
                        @checked($selectedPreset === '')
                    >
                    <span class="block text-sm font-semibold text-slate-900">{{ __('Manual customization') }}</span>
                    <span class="mt-1 block text-xs text-slate-500">{{ __('Use current custom colors without preset auto-apply.') }}</span>
                </label>
            </div>
            <x-input-error class="mt-2" :messages="$errors->get('preset')" />
        </div>

        <div class="grid grid-cols-1 gap-4 lg:grid-cols-2">
            <div class="space-y-3">
                <h3 class="text-sm font-semibold text-slate-800">{{ __('Colors') }}</h3>
                <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                    @foreach ([
                        'primary' => __('Primary color'),
                        'primary_hover' => __('Primary hover'),
                        'accent' => __('Accent color'),
                        'background' => __('Background'),
                        'surface' => __('Surface'),
                        'surface_alt' => __('Surface alt'),
                        'text' => __('Text'),
                        'text_muted' => __('Muted text'),
                        'border' => __('Border'),
                        'sidebar_bg' => __('Sidebar background'),
                        'sidebar_surface' => __('Sidebar surface'),
                        'sidebar_border' => __('Sidebar border'),
                        'sidebar_text' => __('Sidebar text'),
                        'sidebar_muted' => __('Sidebar muted'),
                        'sidebar_active' => __('Sidebar active'),
                        'right_rail_bg' => __('Right panel background'),
                        'card_bg' => __('Card background'),
                        'input_bg' => __('Input background'),
                    ] as $key => $label)
                        @php
                            $value = old("palette.$key", $palette[$key] ?? '#FFFFFF');
                        @endphp
                        <label class="flex items-center justify-between gap-3 rounded-md border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700">
                            <span>{{ $label }}</span>
                            <input type="color" name="palette[{{ $key }}]" value="{{ $value }}" class="h-8 w-12 cursor-pointer rounded border border-slate-300 bg-white">
                        </label>
                    @endforeach
                </div>
            </div>

            <div class="space-y-3">
                <h3 class="text-sm font-semibold text-slate-800">{{ __('Fonts') }}</h3>
                <div>
                    <label for="appearance_font_body" class="block text-sm font-medium text-slate-700">{{ __('Body font') }}</label>
                    <input id="appearance_font_body" name="fonts[body]" type="text" value="{{ old('fonts.body', $fonts['body'] ?? '') }}" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                </div>
                <div>
                    <label for="appearance_font_heading" class="block text-sm font-medium text-slate-700">{{ __('Heading font') }}</label>
                    <input id="appearance_font_heading" name="fonts[heading]" type="text" value="{{ old('fonts.heading', $fonts['heading'] ?? '') }}" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                </div>
                <div>
                    <label for="appearance_font_url" class="block text-sm font-medium text-slate-700">{{ __('Font CSS URL') }}</label>
                    <input id="appearance_font_url" name="fonts[url]" type="url" value="{{ old('fonts.url', $fonts['url'] ?? '') }}" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="https://fonts.bunny.net/css?family=...">
                </div>

                <h3 class="mt-4 text-sm font-semibold text-slate-800">{{ __('Icons') }}</h3>
                <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <label class="flex items-center justify-between gap-3 rounded-md border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700">
                        <span>{{ __('Icon color') }}</span>
                        <input type="color" name="icons[color]" value="{{ old('icons.color', $icons['color'] ?? '#475569') }}" class="h-8 w-12 cursor-pointer rounded border border-slate-300 bg-white">
                    </label>
                    <label class="flex items-center justify-between gap-3 rounded-md border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700">
                        <span>{{ __('Muted icon color') }}</span>
                        <input type="color" name="icons[muted]" value="{{ old('icons.muted', $icons['muted'] ?? '#94A3B8') }}" class="h-8 w-12 cursor-pointer rounded border border-slate-300 bg-white">
                    </label>
                </div>
            </div>
        </div>

        <div class="rounded-lg border border-slate-200 bg-white p-4">
            <h3 class="text-sm font-semibold text-slate-800">{{ __('Background image') }}</h3>
            <p class="mt-1 text-xs text-slate-500">{{ __('Upload a personal background image for your workspace.') }}</p>

            <div class="mt-3 grid grid-cols-1 gap-4 lg:grid-cols-2">
                <div class="space-y-3">
                    <input
                        id="background_image"
                        type="file"
                        name="background_image"
                        accept="image/*"
                        class="block w-full text-sm text-slate-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"
                    >

                    @if ($backgroundUrl)
                        <label class="inline-flex items-center gap-2 text-sm text-slate-700">
                            <input
                                type="checkbox"
                                name="remove_background_image"
                                value="1"
                                class="rounded border-slate-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
                            >
                            {{ __('Remove background image') }}
                        </label>
                    @endif
                </div>

                <div class="rounded-lg border border-slate-200 bg-slate-50 p-3">
                    @if ($backgroundUrl)
                        <img src="{{ $backgroundUrl }}" alt="{{ __('Background image') }}" class="h-32 w-full rounded-md object-cover">
                    @else
                        <div class="flex h-32 items-center justify-center text-xs text-slate-500">
                            {{ __('No background image set.') }}
                        </div>
                    @endif
                </div>
            </div>
        </div>

        <div class="flex items-center justify-end">
            <x-primary-button>{{ __('Save') }}</x-primary-button>
        </div>
    </form>
</section>

@once
    <script>
        (() => {
            const form = document.querySelector('[data-appearance-form]');
            if (!form || form.dataset.presetBound === '1') {
                return;
            }
            form.dataset.presetBound = '1';

            const presets = @json($themePresetPayload);

            const applyPreset = (slug) => {
                if (!slug || typeof presets[slug] !== 'object') {
                    return;
                }

                const payload = presets[slug];
                const applyMap = (groupName, values) => {
                    if (!values || typeof values !== 'object') {
                        return;
                    }

                    Object.entries(values).forEach(([key, value]) => {
                        const input = form.querySelector(`[name="${groupName}[${key}]"]`);
                        if (!input || typeof value !== 'string') {
                            return;
                        }

                        input.value = value;
                        input.dispatchEvent(new Event('input', { bubbles: true }));
                        input.dispatchEvent(new Event('change', { bubbles: true }));
                    });
                };

                applyMap('palette', payload.palette || {});
                applyMap('fonts', payload.fonts || {});
                applyMap('icons', payload.icons || {});
            };

            form.querySelectorAll('[data-theme-preset-radio]').forEach((radio) => {
                radio.addEventListener('change', (event) => {
                    const target = event.target;
                    if (!(target instanceof HTMLInputElement) || !target.checked) {
                        return;
                    }

                    applyPreset(String(target.value || '').trim());
                });
            });
        })();
    </script>
@endonce
