@extends('admin.layouts.app')
@section('title', 'Settings')
@section('page-title', 'Settings')

@section('content')
<div class="flex flex-col md:flex-row gap-6">
    <div class="w-full md:w-48 md:flex-shrink-0">
        <nav class="flex md:flex-col gap-1 overflow-x-auto pb-1 md:pb-0">
            @php
                $settingsGroups = ['general', 'reading', 'media', 'seo', 'social'];
                if (\AleshaCMS\Models\CMS\Plugin::where('slug', 'Disqus')->where('is_active', true)->exists()) {
                    $settingsGroups[] = 'integrations';
                }
            @endphp
            @foreach($settingsGroups as $g)
            <a href="{{ route('admin.settings.index', $g) }}"
               class="flex items-center px-3 py-2 text-sm rounded-lg transition-colors whitespace-nowrap flex-shrink-0
                      {{ $group === $g ? 'bg-indigo-600 text-white' : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700' }}">
                {{ ucfirst($g) }}
            </a>
            @endforeach
        </nav>
    </div>
    <div class="flex-1 min-w-0">
        <form method="POST" action="{{ route('admin.settings.update', $group) }}"
              enctype="multipart/form-data"
              x-data="settingsManager()" @submit.prevent="submit($event)"
              class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
            @csrf

            @if($group === 'general')
            <div class="space-y-4">
                @foreach([
                    ['key' => 'site_name', 'label' => 'Site Name', 'type' => 'text'],
                    ['key' => 'site_tagline', 'label' => 'Tagline', 'type' => 'text'],
                    ['key' => 'site_email', 'label' => 'Admin Email', 'type' => 'email'],
                    ['key' => 'site_url', 'label' => 'Site URL', 'type' => 'url'],
                ] as $field)
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ $field['label'] }}</label>
                    <input type="{{ $field['type'] }}" name="{{ $field['key'] }}" value="{{ $settings[$field['key']] ?? '' }}"
                           class="w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                </div>
                @endforeach

                {{-- Timezone --}}
                @php
                    $currentTz = $settings['site_timezone'] ?? config('app.timezone', 'UTC');
                    $tzOptions  = collect(DateTimeZone::listIdentifiers())
                        ->map(fn($tz) => ['value' => $tz, 'label' => str_replace('_', ' ', $tz)])
                        ->values()->all();
                @endphp
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Timezone</label>
                    <div x-data="selectSearch({{ json_encode($tzOptions) }}, '{{ $currentTz }}', 'Search timezone...')"
                         class="relative" @keydown.escape="open = false; search = ''">
                        <input type="hidden" name="site_timezone" :value="value">
                        <button type="button" @click="open = !open"
                                class="w-full flex items-center justify-between border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm bg-white dark:bg-gray-700 text-left">
                            <span :class="selectedLabel ? 'text-gray-900 dark:text-white' : 'text-gray-400'"
                                  x-text="selectedLabel || 'Select timezone'"></span>
                            <svg class="w-4 h-4 text-gray-400 flex-shrink-0 transition-transform" :class="open ? 'rotate-180' : ''"
                                 fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                            </svg>
                        </button>
                        <div x-show="open" x-cloak @click.outside="open = false; search = ''"
                             x-effect="if(open) setTimeout(() => { $refs.tzSearch?.focus({ preventScroll: true }); $refs.tzList?.querySelector('[data-active]')?.scrollIntoView({ block: 'center' }); }, 30)"
                             class="absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg flex flex-col"
                             style="display:none; max-height:260px;">
                            <div class="p-2 border-b border-gray-100 dark:border-gray-700 flex-shrink-0">
                                <input type="text" x-model="search" x-ref="tzSearch"
                                       placeholder="Search timezone..." @click.stop
                                       class="w-full text-sm border border-gray-300 dark:border-gray-600 rounded px-2.5 py-1.5 bg-white dark:bg-gray-700 text-gray-900 dark:text-white outline-none focus:ring-2 focus:ring-indigo-500">
                            </div>
                            <div class="overflow-y-auto flex-1" x-ref="tzList">
                                <template x-for="opt in filtered" :key="opt.value">
                                    <div @click="select(opt)"
                                         :data-active="opt.value === value ? '' : null"
                                         :class="opt.value === value ? 'bg-indigo-50 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300 font-medium' : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'"
                                         class="px-3 py-2 text-sm cursor-pointer" x-text="opt.label"></div>
                                </template>
                                <div x-show="filtered.length === 0" class="px-3 py-4 text-sm text-gray-400 text-center">No results.</div>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Site Logo --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Site Logo</label>
                    @if(!empty($settings['site_logo']))
                    <div class="mb-2 p-2 border border-gray-200 dark:border-gray-700 rounded-lg inline-block bg-gray-50 dark:bg-gray-700">
                        <img src="{{ $settings['site_logo'] }}" alt="Site Logo" class="h-12 object-contain">
                    </div>
                    @endif
                    <input type="file" name="site_logo" accept="image/*"
                           class="w-full text-sm text-gray-500 dark:text-gray-400 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-xs file:font-medium file:bg-indigo-50 file:text-indigo-700 dark:file:bg-indigo-900/30 dark:file:text-indigo-400 hover:file:bg-indigo-100">
                    <p class="text-xs text-gray-400 mt-1">PNG, SVG, WebP recommended. Max 2 MB.</p>
                </div>

                {{-- Site Favicon --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Site Favicon</label>
                    @if(!empty($settings['site_favicon']))
                    <div class="mb-2 p-2 border border-gray-200 dark:border-gray-700 rounded-lg inline-block bg-gray-50 dark:bg-gray-700">
                        <img src="{{ $settings['site_favicon'] }}" alt="Favicon" class="h-8 w-8 object-contain">
                    </div>
                    @endif
                    <input type="file" name="site_favicon" accept="image/*,.ico"
                           class="w-full text-sm text-gray-500 dark:text-gray-400 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-xs file:font-medium file:bg-indigo-50 file:text-indigo-700 dark:file:bg-indigo-900/30 dark:file:text-indigo-400 hover:file:bg-indigo-100">
                    <p class="text-xs text-gray-400 mt-1">ICO, PNG, atau SVG. Ukuran 32×32 px ideal.</p>
                </div>
            </div>
            @elseif($group === 'reading')
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Posts per page</label>
                    <input type="number" name="posts_per_page" value="{{ $settings['posts_per_page'] ?? 10 }}"
                           class="w-32 border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                </div>
            </div>
            @elseif($group === 'seo')
            <div class="space-y-4">
                @foreach([
                    ['key' => 'meta_title', 'label' => 'Default Meta Title'],
                    ['key' => 'meta_description', 'label' => 'Default Meta Description'],
                ] as $field)
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ $field['label'] }}</label>
                    <textarea name="{{ $field['key'] }}" rows="2"
                              class="w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white">{{ $settings[$field['key']] ?? '' }}</textarea>
                </div>
                @endforeach
                <div>
                    <label class="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer">
                        <input type="checkbox" name="enable_sitemap" value="1" @checked(!empty($settings['enable_sitemap']))
                               class="rounded border-gray-300">
                        Enable Sitemap
                    </label>
                </div>
            </div>
            @elseif($group === 'integrations')
            <div class="space-y-6">
                <div>
                    <h3 class="text-sm font-semibold text-gray-900 dark:text-white mb-3">Disqus Comments</h3>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Shortname</label>
                        <input type="text" name="disqus_shortname" value="{{ $settings['disqus_shortname'] ?? '' }}"
                               placeholder="your-disqus-shortname"
                               class="w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                        <p class="text-xs text-gray-400 mt-1">Temukan shortname di Admin Disqus → Settings → General. Kosongkan untuk menonaktifkan.</p>
                    </div>
                </div>
            </div>
            @elseif($group === 'media')
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Max Upload Size (KB)</label>
                    <input type="number" name="media_max_size" value="{{ $settings['media_max_size'] ?? 51200 }}"
                           class="w-40 border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                    <p class="text-xs text-gray-400 mt-1">Default: 51200 KB (50 MB)</p>
                </div>
            </div>
            @elseif($group === 'social')
            <div class="space-y-3">
                @foreach([
                    ['key' => 'social_facebook',  'label' => 'Facebook',    'placeholder' => 'https://facebook.com/yourpage',   'color' => '#1877f2', 'icon' => 'M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z'],
                    ['key' => 'social_instagram', 'label' => 'Instagram',   'placeholder' => 'https://instagram.com/yourhandle', 'color' => '#e1306c', 'icon' => 'M16 11.37A4 4 0 1112.63 8 4 4 0 0116 11.37zm1.5-4.87h.01M6.5 6.5h11a1 1 0 011 1v9a1 1 0 01-1 1h-11a1 1 0 01-1-1v-9a1 1 0 011-1z'],
                    ['key' => 'social_tiktok',    'label' => 'TikTok',      'placeholder' => 'https://tiktok.com/@yourhandle',   'color' => '#010101', 'icon' => 'M9 12a4 4 0 104 4V4a5 5 0 005 5'],
                    ['key' => 'social_twitter',   'label' => 'X (Twitter)', 'placeholder' => 'https://x.com/yourhandle',         'color' => '#000000', 'icon' => 'M4 4l16 16M4 20L20 4'],
                    ['key' => 'social_youtube',   'label' => 'YouTube',     'placeholder' => 'https://youtube.com/@yourchannel', 'color' => '#ff0000', 'icon' => 'M22.54 6.42a2.78 2.78 0 00-1.95-1.96C18.88 4 12 4 12 4s-6.88 0-8.59.46A2.78 2.78 0 001.46 6.42 29 29 0 001 12a29 29 0 00.46 5.58 2.78 2.78 0 001.95 1.95C5.12 20 12 20 12 20s6.88 0 8.59-.47a2.78 2.78 0 001.95-1.95A29 29 0 0023 12a29 29 0 00-.46-5.58zM9.75 15.02V8.98L15.5 12l-5.75 3.02z'],
                ] as $s)
                <div>
                    <label class="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" style="color:{{ $s['color'] }}">
                            <path stroke-linecap="round" stroke-linejoin="round" d="{{ $s['icon'] }}"/>
                        </svg>
                        {{ $s['label'] }}
                    </label>
                    <input type="url" name="{{ $s['key'] }}" value="{{ $settings[$s['key']] ?? '' }}"
                           placeholder="{{ $s['placeholder'] }}"
                           class="w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                </div>
                @endforeach
            </div>
            @else
            <p class="text-sm text-gray-500 dark:text-gray-400">No settings for this group yet.</p>
            @endif

            <div class="mt-6 pt-4 border-t border-gray-200 dark:border-gray-700 flex items-center gap-4">
                <button type="submit" :disabled="saving"
                        class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 disabled:opacity-60 text-white rounded-lg text-sm font-medium flex items-center gap-2">
                    <svg x-show="saving" class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
                    </svg>
                    <span x-text="saving ? 'Saving...' : 'Save Settings'"></span>
                </button>
                <span x-show="message" x-text="message"
                      :class="saved ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'"
                      class="text-sm" style="display:none"></span>
            </div>
        </form>
    </div>
</div>
@endsection
