@extends('layouts.app')

@section('title', 'Admin · Notifications & Reminders · FamilyTree')
@section('page-title', 'Admin · Notifications & Reminders')

@section('content')
<section class="space-y-6">
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div class="rounded-2xl border border-slate-100 bg-white p-6">
            <h3 class="text-sm font-semibold text-slate-700 mb-3">Default event reminder settings</h3>
            <p class="text-xs text-slate-500 mb-4">These defaults are used when a family has not set its own reminder schedule.</p>
            <form method="POST" action="{{ route('admin.notifications.settings.update') }}" class="space-y-4">
                @csrf
                <div>
                    <label class="block text-sm text-slate-600 mb-1">Reminder days (comma-separated)</label>
                    <input name="reminder_days" type="text" value="{{ old('reminder_days', implode(',', (array)($defaults['days'] ?? []))) }}" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary" placeholder="Example: 7,3,1">
                    <p class="text-xs text-slate-500 mt-1">Enter the number of days before an event to send reminders. Example: 3</p>
                </div>
                <div>
                    <label class="block text-sm text-slate-600 mb-1">Reminder time (24h)</label>
                    <input name="reminder_time" type="time" value="{{ old('reminder_time', $defaults['time'] ?? '07:00') }}" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary">
                </div>
                <div>
                    <button type="submit" class="inline-flex items-center gap-2 bg-primary text-white px-4 py-2 rounded-xl">
                        <span class="material-symbols-rounded">save</span>
                        Save defaults
                    </button>
                </div>
            </form>
        </div>

        <div class="rounded-2xl border border-slate-100 bg-white p-6">
            <h3 class="text-sm font-semibold text-slate-700 mb-3">Bulk notifications</h3>
            <form method="POST" action="{{ route('admin.notifications.bulk.send') }}" class="space-y-4">
                @csrf
                <div>
                    <label class="block text-sm text-slate-600 mb-1">Audience scope</label>
                    <div class="flex items-center gap-4 text-sm">
                        <label class="inline-flex items-center gap-2">
                            <input type="radio" name="scope" value="all_users" class="text-primary" checked>
                            All users
                        </label>
                        <label class="inline-flex items-center gap-2">
                            <input type="radio" name="scope" value="selected_families" class="text-primary">
                            Selected families
                        </label>
                    </div>
                </div>
                <div id="familiesSelectWrapper" class="hidden">
                    <label class="block text-sm text-slate-600 mb-1">Families</label>
                    <select name="families[]" multiple class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary h-48">
                        @foreach($families as $f)
                            <option value="{{ $f->id }}">{{ $f->name }}</option>
                        @endforeach
                    </select>
                    <p class="text-xs text-slate-500 mt-1">Hold Ctrl/Command to select multiple families.</p>
                </div>
                <div>
                    <label class="block text-sm text-slate-600 mb-1">Channels</label>
                    <div class="flex items-center gap-4 text-sm">
                        <label class="inline-flex items-center gap-2">
                            <input type="checkbox" name="channels[]" value="email" class="text-primary" checked>
                            Email
                        </label>
                        <label class="inline-flex items-center gap-2">
                            <input type="checkbox" name="channels[]" value="sms" class="text-primary">
                            SMS
                        </label>
                    </div>
                </div>
                <div class="rounded-xl border border-slate-200 p-4">
                    <h4 class="text-sm font-semibold text-slate-700 mb-2">Email content</h4>
                    <div class="grid grid-cols-1 gap-3">
                        <div>
                            <label class="block text-sm text-slate-600 mb-1">Subject</label>
                            <input name="email_subject" type="text" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary" placeholder="Subject line">
                        </div>
                        <div>
                            <label class="block text-sm text-slate-600 mb-1">Body</label>
                            <textarea name="email_body" rows="6" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary" placeholder="Write your message... You can use placeholders: {name}, {family_name}, {app_name}"></textarea>
                            <p class="text-xs text-slate-500 mt-1">Placeholders: <code>{name}</code>, <code>{family_name}</code>, <code>{app_name}</code></p>
                        </div>
                    </div>
                </div>
                <div class="rounded-xl border border-slate-200 p-4">
                    <h4 class="text-sm font-semibold text-slate-700 mb-2">SMS content</h4>
                    <label class="block text-sm text-slate-600 mb-1">Message</label>
                    <textarea name="sms_body" rows="4" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary" placeholder="Short text... You can use {name} and {app_name}"></textarea>
                    <p class="text-xs text-slate-500 mt-1">Keep it concise. Placeholders: <code>{name}</code>, <code>{family_name}</code>, <code>{app_name}</code></p>
                </div>
                <div>
                    <div class="flex items-center gap-2">
                        <button type="button" id="previewBtn" class="inline-flex items-center gap-2 bg-slate-700 text-white px-4 py-2 rounded-xl">
                            <span class="material-symbols-rounded">visibility</span>
                            Preview
                        </button>
                        <button type="submit" class="inline-flex items-center gap-2 bg-primary text-white px-4 py-2 rounded-xl">
                        <span class="material-symbols-rounded">send</span>
                        Send notifications
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</section>
@endsection

@push('head')
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
@endpush

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function(){
        const scopeInputs = document.querySelectorAll('input[name="scope"]');
        const familiesWrapper = document.getElementById('familiesSelectWrapper');
        function syncFamiliesVisibility(){
            const value = document.querySelector('input[name="scope"]:checked')?.value;
            if (value === 'selected_families') {
                familiesWrapper.classList.remove('hidden');
            } else {
                familiesWrapper.classList.add('hidden');
            }
        }
        scopeInputs.forEach(i => i.addEventListener('change', syncFamiliesVisibility));
        syncFamiliesVisibility();
    });
</script>

<div id="previewModal" class="fixed inset-0 z-50 hidden" role="dialog" aria-modal="true" aria-labelledby="previewTitle">
    <div class="absolute inset-0 bg-black/40" data-preview-close></div>
    <div class="relative mx-auto max-w-3xl bg-white rounded-2xl shadow-2xl border border-slate-200 mt-12 overflow-hidden">
        <div class="flex items-center justify-between px-4 py-3 border-b border-slate-200 bg-slate-50">
            <h3 id="previewTitle" class="text-sm font-semibold text-slate-800">Bulk notification preview</h3>
            <button type="button" class="p-2 rounded-full hover:bg-slate-200" data-preview-close aria-label="Close preview">
                <span class="material-symbols-rounded">close</span>
            </button>
        </div>
        <div id="previewContent" class="p-4 max-h-[70vh] overflow-auto text-sm"></div>
        <div class="px-4 py-3 border-t border-slate-200 bg-slate-50 flex items-center justify-end">
            <button type="button" class="inline-flex items-center gap-2 bg-primary text-white px-4 py-2 rounded-xl" data-preview-close>
                <span class="material-symbols-rounded">check</span>
                Looks good
            </button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
    const appName = @json(config('app.name', 'FamilyTree'));
    const previewBtn = document.getElementById('previewBtn');
    const modal = document.getElementById('previewModal');
    const contentEl = document.getElementById('previewContent');
    const closeEls = modal ? modal.querySelectorAll('[data-preview-close]') : [];

    function substitute(str, name, fam, app){
        if (!str) return '';
        return String(str)
            .replaceAll('{name}', name)
            .replaceAll('{family_name}', fam)
            .replaceAll('{app_name}', app);
    }

    function escapeHtml(str){
        return String(str)
            .replaceAll('&', '&amp;')
            .replaceAll('<', '&lt;')
            .replaceAll('>', '&gt;')
            .replaceAll('"', '&quot;')
            .replaceAll("'", '&#39;');
    }

    function nl2br(str){
        return String(str).replace(/\n/g, '<br>');
    }

    function selectedFamilyName(){
        const scope = document.querySelector('input[name="scope"]:checked')?.value;
        if (scope !== 'selected_families') return null;
        const select = document.querySelector('select[name="families[]"]');
        if (!select) return null;
        const opt = Array.from(select.options).find(o => o.selected);
        return opt ? opt.textContent : null;
    }

    function buildEmailPreview(subject, bodyHtml){
        return `
        <div class="mb-4 text-xs text-slate-500">Email preview</div>
        <div class="border border-slate-200 rounded-xl overflow-hidden">
            <div class="px-4 py-3 bg-gradient-to-r from-sky-500 to-indigo-500 text-white">
                <div class="text-sm font-semibold">${escapeHtml(appName)}</div>
            </div>
            <div class="p-4">
                <div class="text-sm font-semibold text-slate-800 mb-2">Subject: ${escapeHtml(subject || '(no subject)')}</div>
                <div class="prose prose-sm max-w-none">${bodyHtml || ''}</div>
            </div>
            <div class="px-4 py-3 bg-slate-50 text-xs text-slate-500 border-t border-slate-200">© ${new Date().getFullYear()} ${escapeHtml(appName)}. All rights reserved.</div>
        </div>`;
    }

    function buildSmsPreview(text){
        return `
        <div class="mt-6">
            <div class="mb-2 text-xs text-slate-500">SMS preview</div>
            <div class="rounded-xl border border-slate-200 p-4 bg-slate-50 text-slate-800">${escapeHtml(text || '')}</div>
        </div>`;
    }

    function openModal(){ if (modal) modal.classList.remove('hidden'); }
    function closeModal(){ if (modal) modal.classList.add('hidden'); }
    closeEls.forEach(el => el.addEventListener('click', closeModal));
    document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closeModal(); });

    if (previewBtn && modal && contentEl) {
        previewBtn.addEventListener('click', function(){
            const scope = document.querySelector('input[name="scope"]:checked')?.value || 'all_users';
            const channels = Array.from(document.querySelectorAll('input[name="channels[]"]:checked')).map(i => i.value);
            const emailSubject = document.querySelector('input[name="email_subject"]').value || '';
            const emailBodyRaw = document.querySelector('textarea[name="email_body"]').value || '';
            const smsBodyRaw = document.querySelector('textarea[name="sms_body"]').value || '';

            const sampleName = 'Ada Lovelace';
            const famName = selectedFamilyName() || 'Your Family';

            const subj = substitute(emailSubject, sampleName, famName, appName);
            const emailBodyEsc = escapeHtml(substitute(emailBodyRaw, sampleName, famName, appName));
            const emailBodyHtml = nl2br(emailBodyEsc);
            const smsText = substitute(smsBodyRaw, sampleName, famName, appName);

            let html = '';
            if (channels.includes('email')) {
                html += buildEmailPreview(subj, emailBodyHtml);
            }
            if (channels.includes('sms')) {
                html += buildSmsPreview(smsText);
            }
            if (!html) {
                html = '<div class="text-sm text-red-600">Select at least one channel to preview.</div>';
            }
            contentEl.innerHTML = html;
            openModal();
        });
    }
});
</script>
@endpush
