<x-app-layout>
<x-module-hero title="Compose Email" description="Create and send email messages" icon="fa-envelope-open-text">
    <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="{{ route('emails.store') }}" method="POST" enctype="multipart/form-data" x-data="emailComposer()">
        @csrf

        {{-- Sender Info --}}
        @php $emailConfig = \App\Models\EmailConfiguration::getActive(); @endphp
        @if($emailConfig)
        <div class="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg flex items-center gap-3">
            <i class="fas fa-envelope text-blue-600 text-lg"></i>
            <div>
                <p class="text-sm font-semibold text-blue-800">Sending from:</p>
                <p class="text-sm text-blue-700">{{ $emailConfig->from_name }} &lt;{{ $emailConfig->from_address }}&gt;</p>
            </div>
        </div>
        @endif

        {{-- Section: Recipients --}}
        <div class="mb-6">
            <h3 class="text-lg font-semibold text-gray-800 border-b pb-2 mb-4">Recipients</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                {{-- Recipient Type --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Recipient Type <span class="text-red-500">*</span></label>
                    <div class="flex gap-4">
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input type="radio" name="recipient_type" value="manual" x-model="recipientType" class="text-green-600">
                            <span class="text-sm">Manual Entry</span>
                        </label>
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input type="radio" name="recipient_type" value="role" x-model="recipientType" class="text-green-600">
                            <span class="text-sm">By Role</span>
                        </label>
                    </div>
                </div>

                {{-- Template Selection --}}
                @if($templates->count() > 0)
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Use Template (Optional)</label>
                    <select name="template_id" class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500" @change="applyTemplate($event)">
                        <option value="">Start from scratch</option>
                        @foreach($templates as $template)
                            <option value="{{ $template->id }}" data-subject="{{ $template->subject }}" data-body="{{ htmlspecialchars($template->html_content) }}">{{ $template->name }}</option>
                        @endforeach
                    </select>
                </div>
                @endif
            </div>

            {{-- Manual Recipients --}}
            <div x-show="recipientType === 'manual'" class="mt-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">To (Email Addresses) <span class="text-red-500">*</span></label>
                <textarea name="to_recipients" rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500" placeholder="Enter email addresses separated by commas">{{ old('to_recipients') }}</textarea>
                @error('to_recipients')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
            </div>

            {{-- Role Selection --}}
            <div x-show="recipientType === 'role'" class="mt-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">Select Role <span class="text-red-500">*</span></label>
                <select name="target_role" class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                    <option value="">Choose a role...</option>
                    @foreach($availableRoles as $role)
                        <option value="{{ $role }}" {{ old('target_role') == $role ? 'selected' : '' }}>{{ $role }}</option>
                    @endforeach
                </select>
                @error('target_role')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
            </div>
        </div>

        {{-- Section: Message Details --}}
        <div class="mb-6">
            <h3 class="text-lg font-semibold text-gray-800 border-b pb-2 mb-4">Message Details</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                {{-- Subject --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Subject <span class="text-red-500">*</span></label>
                    <input type="text" name="subject" x-model="emailSubject" value="{{ old('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="Email subject">
                    @error('subject')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>

                {{-- Priority --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Priority</label>
                    <select name="priority" class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                        <option value="normal" {{ old('priority') == 'normal' ? 'selected' : '' }}>Normal</option>
                        <option value="high" {{ old('priority') == 'high' ? 'selected' : '' }}>High</option>
                        <option value="low" {{ old('priority') == 'low' ? 'selected' : '' }}>Low</option>
                    </select>
                </div>

                {{-- CC --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">CC (Optional)</label>
                    <input type="text" name="cc_recipients" value="{{ old('cc_recipients') }}"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500" placeholder="CC emails (comma separated)">
                </div>

                {{-- BCC --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">BCC (Optional)</label>
                    <input type="text" name="bcc_recipients" value="{{ old('bcc_recipients') }}"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500" placeholder="BCC emails (comma separated)">
                </div>
            </div>

            {{-- Rich Text Body --}}
            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">Message Body <span class="text-red-500">*</span></label>
                <div id="email-editor" class="min-h-[300px] border border-gray-300 rounded-lg bg-white"></div>
                <textarea name="html_body" id="html-body-input" class="hidden">{{ old('html_body') }}</textarea>
                @error('html_body')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
            </div>

            {{-- Attachments --}}
            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">Attachments (Optional)</label>
                <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-green-400 transition">
                    <input type="file" name="attachments[]" multiple class="hidden" id="attachment-input">
                    <label for="attachment-input" class="cursor-pointer">
                        <i class="fas fa-paperclip text-3xl text-gray-400 mb-2"></i>
                        <p class="text-sm text-gray-600">Click to attach files</p>
                        <p class="text-xs text-gray-400 mt-1">Max 10MB per file</p>
                    </label>
                </div>
            </div>
        </div>

        {{-- Section: Scheduling --}}
        <div class="mb-6">
            <h3 class="text-lg font-semibold text-gray-800 border-b pb-2 mb-4">Scheduling</h3>
            <div class="flex items-center gap-3 mb-3">
                <input type="checkbox" id="schedule-toggle" class="rounded border-gray-300 text-green-600 focus:ring-green-500" @change="showSchedule = $event.target.checked">
                <label for="schedule-toggle" class="text-sm font-medium text-gray-700">Schedule for later</label>
            </div>
            <div x-show="showSchedule" class="mt-3">
                <label class="block text-sm font-medium text-gray-700 mb-2">Send Date & Time</label>
                <input type="datetime-local" name="scheduled_at" value="{{ old('scheduled_at') }}"
                    class="px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                @error('scheduled_at')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
            </div>
        </div>

        {{-- Submit --}}
        <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200">
            <a href="{{ route('emails.index') }}" 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-paper-plane mr-1"></i> Send Email
            </button>
        </div>
    </form>
</div>

@push('scripts')
<script>
function emailComposer() {
    return {
        recipientType: '{{ old('recipient_type', 'manual') }}',
        emailSubject: '{{ old('subject', '') }}',
        showSchedule: false,
        applyTemplate(e) {
            const opt = e.target.selectedOptions[0];
            if (opt.value) {
                this.emailSubject = opt.dataset.subject || '';
                if (window.emailQuill) {
                    window.emailQuill.root.innerHTML = opt.dataset.body || '';
                }
            }
        }
    }
}

document.addEventListener('DOMContentLoaded', function() {
    window.emailQuill = new Quill('#email-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(old('html_body'))
        window.emailQuill.root.innerHTML = @json(old('html_body'));
    @endif

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