<x-app-layout>
<x-module-hero title="{{ isset($template) ? 'Edit Template' : 'Create Template' }}" description="{{ isset($template) ? 'Modify email template' : 'Create a reusable email template' }}" icon="fa-file-lines">
    <x-slot name="backButton">
        <a href="{{ route('emails.templates') }}" class="inline-flex items-center gap-1 text-sm text-[#475569] hover:text-[#1e293b] transition-colors">
            <i class="fas fa-arrow-left text-xs"></i> Back to Templates
        </a>
    </x-slot>
    <x-slot name="tabs">
        @can('view emails')
        <a href="{{ route('emails.index') }}"
           class="module-hero-tab inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0
                  {{ request()->routeIs('emails.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}">
            <i class="fas fa-tachometer-alt text-sm"></i> Inbox
        </a>
        @endcan
        @can('create emails')
        <a href="{{ route('emails.compose') }}"
           class="module-hero-tab inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0
                  {{ request()->routeIs('emails.compose') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}">
            <i class="fas fa-pen text-sm"></i> Compose
        </a>
        @endcan
        @can('view emails')
        <a href="{{ route('emails.history') }}"
           class="module-hero-tab inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0
                  {{ request()->routeIs('emails.history') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}">
            <i class="fas fa-history text-sm"></i> History
        </a>
        @endcan
        @can('manage email templates')
        <a href="{{ route('emails.templates') }}"
           class="module-hero-tab inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0
                  {{ request()->routeIs('emails.templates') || request()->routeIs('emails.*template*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}">
            <i class="fas fa-file-lines text-sm"></i> Templates
        </a>
        @endcan
    </x-slot>
</x-module-hero>

<div class="p-6">
    @if(session('error'))
        <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg flex items-center gap-2">
            <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
        </div>
    @endif

    <form action="{{ isset($template) ? route('emails.update-template', $template) : route('emails.store-template') }}" method="POST">
        @csrf
        @if(isset($template)) @method('PUT') @endif

        {{-- Section: Basic Info --}}
        <div class="mb-6">
            <h3 class="text-lg font-semibold text-gray-800 border-b pb-2 mb-4">Template Information</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Template Name <span class="text-red-500">*</span></label>
                    <input type="text" name="name" value="{{ old('name', $template->name ?? '') }}" required
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500" placeholder="e.g., Welcome Email">
                    @error('name')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Email Subject <span class="text-red-500">*</span></label>
                    <input type="text" name="subject" value="{{ old('subject', $template->subject ?? '') }}" required
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500" placeholder="Subject line">
                    @error('subject')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Preheader Text</label>
                    <input type="text" name="preheader" value="{{ old('preheader', $template->preheader ?? '') }}"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500" placeholder="Preview text shown in inbox">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                    <input type="text" name="description" value="{{ old('description', $template->description ?? '') }}"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500" placeholder="When to use this template">
                </div>
            </div>
        </div>

        {{-- Section: Content --}}
        <div class="mb-6">
            <h3 class="text-lg font-semibold text-gray-800 border-b pb-2 mb-4">Template Content</h3>

            {{-- Placeholders Info --}}
            <div class="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                <p class="text-sm font-medium text-blue-800 mb-2"><i class="fas fa-info-circle mr-1"></i> Available Placeholders</p>
                <div class="flex flex-wrap gap-2">
                    @foreach(\App\Models\EmailTemplate::availablePlaceholders() as $placeholder => $desc)
                        <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs" title="{{ $desc }}">{{ $placeholder }}</span>
                    @endforeach
                </div>
            </div>

            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">HTML Content <span class="text-red-500">*</span></label>
                <div id="template-editor" class="min-h-[400px] border border-gray-300 rounded-lg bg-white"></div>
                <textarea name="html_content" id="html-content-input" class="hidden" required>{{ old('html_content', $template->html_content ?? '') }}</textarea>
                @error('html_content')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Plain Text Version</label>
                <textarea name="text_content" rows="5" class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500" placeholder="Plain text fallback for email clients that don't support HTML">{{ old('text_content', $template->text_content ?? '') }}</textarea>
                <p class="text-xs text-gray-400 mt-1">Optional but recommended for accessibility.</p>
            </div>
        </div>

        {{-- Submit --}}
        <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200">
            <a href="{{ route('emails.templates') }}" class="px-6 py-2 border border-gray-300 rounded-lg text-sm text-gray-700 hover:bg-gray-50 transition">
                <i class="fas fa-times mr-1"></i> Cancel
            </a>
            <button type="submit" class="px-6 py-2 bg-[#1a4731] text-white text-sm font-semibold rounded-lg hover:bg-[#276749] transition">
                <i class="fas fa-save mr-1"></i> {{ isset($template) ? 'Update Template' : 'Create Template' }}
            </button>
        </div>
    </form>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const quill = new Quill('#template-editor', {
        theme: 'snow',
        modules: {
            toolbar: [
                ['bold', 'italic', 'underline', 'strike'],
                ['blockquote', 'code-block'],
                [{'header': [1, 2, 3, false]}],
                [{'list': 'ordered'}, {'list': 'bullet'}],
                [{'color': []}, {'background': []}],
                ['link', 'image'],
                ['clean']
            ]
        }
    });

    @if(isset($template) && $template->html_content)
        quill.root.innerHTML = @json($template->html_content);
    @elseif(old('html_content'))
        quill.root.innerHTML = @json(old('html_content'));
    @endif

    document.querySelector('form').addEventListener('submit', function() {
        document.getElementById('html-content-input').value = quill.root.innerHTML;
    });
});
</script>
@endpush
</x-app-layout>
