<x-layouts.admin :title="__('Theme Studio')" :subtitle="__('Customize every color across the platform — light + dark mode.')">
    <div class="space-y-6" x-data="themeStudio()" x-init="init()">

        {{-- Flash messages are rendered by the admin layout itself — no
             duplicate block here. --}}

        {{-- Mode switcher + actions --}}
        <div class="panel p-4 flex flex-wrap items-center justify-between gap-3">
            <div class="inline-flex rounded-xl bg-surface p-1 border border-border">
                <button type="button" @click="mode = 'light'"
                        :class="mode === 'light' ? 'bg-brand text-white shadow' : 'text-muted hover:text-ink'"
                        class="px-4 py-2 text-sm font-semibold rounded-lg transition">
                    <svg class="inline w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4" stroke-width="1.6"/><path stroke-linecap="round" stroke-width="1.6" d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
                    {{ __('Light Mode') }}
                </button>
                <button type="button" @click="mode = 'dark'"
                        :class="mode === 'dark' ? 'bg-brand text-white shadow' : 'text-muted hover:text-ink'"
                        class="px-4 py-2 text-sm font-semibold rounded-lg transition">
                    <svg class="inline w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
                    {{ __('Dark Mode') }}
                </button>
            </div>

            <div class="flex items-center gap-2">
                <button type="button" @click="resetToDefaults()"
                        class="px-4 py-2 text-sm font-semibold rounded-xl border border-border text-muted hover:text-ink hover:bg-surface transition">
                    {{ __('Reset Mode to Defaults') }}
                </button>
                <form method="POST" action="{{ route('admin.theme-studio.reset') }}"
                      onsubmit="return confirm('{{ __('Reset ALL colors (light + dark) to defaults?') }}');">
                    @csrf
                    @method('DELETE')
                    <button type="submit"
                            class="px-4 py-2 text-sm font-semibold rounded-xl border border-danger/30 text-danger hover:bg-danger/10 transition">
                        {{ __('Full Reset') }}
                    </button>
                </form>
            </div>
        </div>

        <form method="POST" action="{{ route('admin.theme-studio.save') }}" class="space-y-6">
            @csrf

            {{-- Hidden inputs synced from Alpine state — submitted on save.
                 `name` is static Blade so the form still posts the field even
                 if Alpine fails to mount; `:value` is reactive to Alpine state. --}}
            @foreach(['light', 'dark'] as $m)
                @foreach(array_keys($defaults['light']) as $tok)
                    <input type="hidden" name="{{ $m }}[{{ $tok }}]" :value="colors['{{ $m }}']['{{ $tok }}']">
                @endforeach
            @endforeach

            <div class="grid lg:grid-cols-3 gap-6">

                {{-- LEFT: Color groups (spans 2 cols) --}}
                <div class="lg:col-span-2 space-y-6">

                    {{-- Brand colors --}}
                    <div class="panel p-6">
                        <div class="flex items-center gap-3 mb-4">
                            <div class="w-10 h-10 rounded-xl flex items-center justify-center" :style="`background: ${colors[mode].primary}`">
                                <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01"/></svg>
                            </div>
                            <div>
                                <h2 class="text-lg font-bold text-ink">{{ __('Brand Colors') }}</h2>
                                <p class="text-sm text-muted">{{ __('Primary identity — buttons, links, focus states.') }}</p>
                            </div>
                        </div>
                        <div class="grid sm:grid-cols-2 gap-4">
                            <template x-for="tok in ['primary','primary_strong','secondary','accent']" :key="tok">
                                <div>
                                    <label class="block text-xs font-semibold text-muted uppercase tracking-wide mb-2" x-text="tokenLabel(tok)"></label>
                                    <div class="flex items-center gap-2">
                                        <input type="color" :value="colors[mode][tok]" @input="colors[mode][tok] = $event.target.value.toUpperCase()"
                                               class="w-12 h-12 rounded-xl border-2 border-border cursor-pointer">
                                        <input type="text" :value="colors[mode][tok]" @input="syncHex(mode, tok, $event.target.value)"
                                               class="flex-1 px-3 py-2 text-sm font-mono uppercase rounded-xl border border-border bg-surface text-ink focus:border-brand focus:outline-none">
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>

                    {{-- Status colors --}}
                    <div class="panel p-6">
                        <div class="flex items-center gap-3 mb-4">
                            <div class="w-10 h-10 rounded-xl flex items-center justify-center bg-success/15">
                                <svg class="w-5 h-5 text-success" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                            </div>
                            <div>
                                <h2 class="text-lg font-bold text-ink">{{ __('Status Colors') }}</h2>
                                <p class="text-sm text-muted">{{ __('Success, warning, danger, and info messages.') }}</p>
                            </div>
                        </div>
                        <div class="grid sm:grid-cols-2 gap-4">
                            <template x-for="tok in ['success','warning','danger','info']" :key="tok">
                                <div>
                                    <label class="block text-xs font-semibold text-muted uppercase tracking-wide mb-2" x-text="tokenLabel(tok)"></label>
                                    <div class="flex items-center gap-2">
                                        <input type="color" :value="colors[mode][tok]" @input="colors[mode][tok] = $event.target.value.toUpperCase()"
                                               class="w-12 h-12 rounded-xl border-2 border-border cursor-pointer">
                                        <input type="text" :value="colors[mode][tok]" @input="syncHex(mode, tok, $event.target.value)"
                                               class="flex-1 px-3 py-2 text-sm font-mono uppercase rounded-xl border border-border bg-surface text-ink focus:border-brand focus:outline-none">
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>

                    {{-- Surface + text --}}
                    <div class="panel p-6">
                        <div class="flex items-center gap-3 mb-4">
                            <div class="w-10 h-10 rounded-xl flex items-center justify-center bg-muted/15">
                                <svg class="w-5 h-5 text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h7"/></svg>
                            </div>
                            <div>
                                <h2 class="text-lg font-bold text-ink">{{ __('Surface & Text') }}</h2>
                                <p class="text-sm text-muted">{{ __('Backgrounds, cards, body text, borders.') }}</p>
                            </div>
                        </div>
                        <div class="grid sm:grid-cols-2 gap-4">
                            <template x-for="tok in ['surface','surface_2','ink','muted','border']" :key="tok">
                                <div>
                                    <label class="block text-xs font-semibold text-muted uppercase tracking-wide mb-2" x-text="tokenLabel(tok)"></label>
                                    <div class="flex items-center gap-2">
                                        <input type="color" :value="colors[mode][tok]" @input="colors[mode][tok] = $event.target.value.toUpperCase()"
                                               class="w-12 h-12 rounded-xl border-2 border-border cursor-pointer">
                                        <input type="text" :value="colors[mode][tok]" @input="syncHex(mode, tok, $event.target.value)"
                                               class="flex-1 px-3 py-2 text-sm font-mono uppercase rounded-xl border border-border bg-surface text-ink focus:border-brand focus:outline-none">
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>

                </div>

                {{-- RIGHT: Live preview --}}
                <div class="lg:col-span-1">
                    <div class="panel p-6 sticky top-4">
                        <h3 class="text-lg font-bold text-ink mb-1">{{ __('Live Preview') }}</h3>
                        <p class="text-sm text-muted mb-4" x-text="mode === 'dark' ? '{{ __('Showing dark mode preview') }}' : '{{ __('Showing light mode preview') }}'"></p>

                        <div class="rounded-2xl border overflow-hidden"
                             :style="`background: ${colors[mode].surface}; border-color: ${colors[mode].border}; color: ${colors[mode].ink};`">

                            {{-- Header bar --}}
                            <div class="p-4 border-b" :style="`border-color: ${colors[mode].border}; background: ${colors[mode].surface_2};`">
                                <div class="flex items-center justify-between">
                                    <div class="font-bold" :style="`color: ${colors[mode].ink}`">{{ \App\Helpers\BrandingHelper::name() }}</div>
                                    <div class="w-7 h-7 rounded-full" :style="`background: ${colors[mode].primary}`"></div>
                                </div>
                            </div>

                            {{-- Body --}}
                            <div class="p-4 space-y-3">
                                <div :style="`color: ${colors[mode].ink}`" class="font-semibold">Sample heading text</div>
                                <div :style="`color: ${colors[mode].muted}`" class="text-sm">This is muted helper text used in labels and captions.</div>

                                {{-- Buttons --}}
                                <div class="flex flex-wrap gap-2 pt-2">
                                    <button type="button" class="px-3 py-1.5 text-xs font-semibold rounded-lg text-white"
                                            :style="`background: ${colors[mode].primary}`">Primary</button>
                                    <button type="button" class="px-3 py-1.5 text-xs font-semibold rounded-lg text-white"
                                            :style="`background: ${colors[mode].primary_strong}`">Hover</button>
                                    <button type="button" class="px-3 py-1.5 text-xs font-semibold rounded-lg border"
                                            :style="`border-color: ${colors[mode].border}; color: ${colors[mode].ink};`">Outline</button>
                                </div>

                                {{-- Status pills --}}
                                <div class="flex flex-wrap gap-2 pt-1">
                                    <span class="px-2 py-0.5 text-xs font-semibold rounded text-white" :style="`background: ${colors[mode].success}`">Success</span>
                                    <span class="px-2 py-0.5 text-xs font-semibold rounded text-white" :style="`background: ${colors[mode].warning}`">Warning</span>
                                    <span class="px-2 py-0.5 text-xs font-semibold rounded text-white" :style="`background: ${colors[mode].danger}`">Danger</span>
                                    <span class="px-2 py-0.5 text-xs font-semibold rounded text-white" :style="`background: ${colors[mode].info}`">Info</span>
                                </div>

                                {{-- Link sample --}}
                                <div class="pt-2 text-sm">
                                    <a href="#" :style="`color: ${colors[mode].primary}`" class="underline">Sample link</a>
                                </div>
                            </div>
                        </div>

                        <button type="submit"
                                class="mt-6 w-full px-4 py-3 text-sm font-bold rounded-xl bg-brand text-white hover:opacity-90 transition shadow-soft">
                            {{ __('Save Theme') }}
                        </button>
                        <p class="mt-3 text-xs text-muted text-center">{{ __('Refresh any page after save to see changes site-wide.') }}</p>
                    </div>
                </div>
            </div>
        </form>
    </div>

    {{-- Inline script (admin layout doesn't expose a @stack('scripts'), so a
         @push() would be silently dropped and Alpine would init with empty
         data — leaving all swatches black and labels missing). --}}
    <script>
        function themeStudio() {
            return {
                mode: 'light',
                colors: @json($config),
                defaults: @json($defaults),

                init() {
                    // Detect current html.dark class so admin lands on the mode they're viewing
                    if (document.documentElement.classList.contains('dark')) {
                        this.mode = 'dark';
                    }
                },

                tokenLabel(tok) {
                    const labels = {
                        primary: '{{ __('Primary') }}',
                        primary_strong: '{{ __('Primary Strong (hover)') }}',
                        secondary: '{{ __('Secondary') }}',
                        accent: '{{ __('Accent') }}',
                        success: '{{ __('Success') }}',
                        warning: '{{ __('Warning') }}',
                        danger: '{{ __('Danger / Error') }}',
                        info: '{{ __('Info') }}',
                        surface: '{{ __('Surface (page bg)') }}',
                        surface_2: '{{ __('Surface 2 (cards)') }}',
                        ink: '{{ __('Ink (body text)') }}',
                        muted: '{{ __('Muted (labels)') }}',
                        border: '{{ __('Border / Divider') }}',
                    };
                    return labels[tok] || tok;
                },

                syncHex(mode, tok, val) {
                    // Coerce typed hex strings, allow #abc or #aabbcc, drop bad input silently
                    val = (val || '').trim().toUpperCase();
                    if (!val.startsWith('#')) val = '#' + val;
                    if (/^#([0-9A-F]{3}|[0-9A-F]{6})$/.test(val)) {
                        this.colors[mode][tok] = val;
                    }
                },

                resetToDefaults() {
                    if (!confirm('{{ __('Reset all colors in the current mode to defaults? (this just resets the form — not saved until you click Save Theme)') }}')) return;
                    this.colors[this.mode] = { ...this.defaults[this.mode] };
                },
            };
        }
    </script>
</x-layouts.admin>
