<?php $types = MailTypes::all(); ?>
<form method="POST" action="/admin/settings">
    <?= Router::csrfField() ?>
    <input type="hidden" name="_tab" value="advanced">
    <input type="hidden" name="_sub" value="mails">

    <div class="space-y-3">

        <div class="flex items-start gap-3 p-4 bg-blue-50 border border-blue-200 rounded-lg">
            <i class="fa-solid fa-circle-info text-blue-500 mt-0.5"></i>
            <div>
                <p class="text-sm font-medium text-blue-900">Customise your transactional emails</p>
                <p class="text-xs text-blue-700 mt-1">Toggle each email on or off right here, or expand one to override its subject and HTML body with a <strong>live inbox preview</strong> (desktop &amp; mobile). Leave a field empty to keep the built-in default. Placeholders such as <code class="bg-white/70 px-1 rounded">{name}</code> are replaced automatically.</p>
            </div>
        </div>

        <?php foreach ($types as $key => $t):
            $enabled = ($settings["mail_type_{$key}_enabled"] ?? $t['default_enabled']) === '1';
            $subjOverride = $settings["mail_type_{$key}_subject"] ?? '';
            $bodyOverride = $settings["mail_type_{$key}_body"] ?? '';
            $customised = trim((string) $subjOverride) !== '' || trim((string) $bodyOverride) !== '';
        ?>
        <div class="accordion-item bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden" data-type="<?= $key ?>">

            
            <div class="accordion-head flex items-center justify-between gap-4 px-5 py-4 cursor-pointer select-none hover:bg-gray-50 transition-colors" onclick="tpAcc(this)" role="button" aria-expanded="false">
                <div class="flex items-start gap-3 min-w-0">
                    <svg class="acc-chevron w-4 h-4 text-gray-400 mt-0.5 shrink-0 transition-transform" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 18 6-6-6-6"/></svg>
                    <div class="min-w-0">
                        <div class="text-sm font-semibold text-gray-900 flex items-center gap-2 flex-wrap">
                            <?= htmlspecialchars($t['label']) ?>
                            <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium <?= $t['audience'] === 'Admin' ? 'bg-purple-100 text-purple-700' : 'bg-gray-100 text-gray-600' ?>">
                                <?= $t['audience'] === 'Admin' ? 'To you' : 'To visitor' ?>
                            </span>
                            <?php if ($customised): ?>
                                <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium bg-blue-100 text-blue-700"><i class="fa-solid fa-pen text-[8px]"></i> Customised</span>
                            <?php endif; ?>
                        </div>
                        <p class="mt-0.5 text-xs text-gray-500 truncate"><?= htmlspecialchars($t['desc']) ?></p>
                    </div>
                </div>
                <label class="relative inline-flex items-center cursor-pointer shrink-0 mt-0.5" title="Enable this email" onclick="event.stopPropagation()">
                    <input type="checkbox" name="mail_type_<?= $key ?>_enabled" value="1" class="sr-only peer" <?= $enabled ? 'checked' : '' ?>>
                    <div class="w-9 h-5 bg-gray-300 rounded-full peer peer-checked:bg-primary-600 transition-colors after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-transform peer-checked:after:translate-x-4 after:shadow-sm"></div>
                </label>
            </div>

            
            <div class="accordion-body hidden border-t border-gray-100 px-5 py-5">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

                    
                    <div class="space-y-4">
                        <div>
                            <label for="mt_<?= $key ?>_subject" class="block text-sm font-medium text-gray-700 mb-1">Subject</label>
                            <input type="text" id="mt_<?= $key ?>_subject" name="mail_type_<?= $key ?>_subject" value="<?= htmlspecialchars($subjOverride) ?>"
                                   oninput="tpMailPreviewDebounced('<?= $key ?>')"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none"
                                   placeholder="<?= htmlspecialchars($t['subject']) ?>">
                        </div>
                        <div>
                            <label for="mt_<?= $key ?>_body" class="block text-sm font-medium text-gray-700 mb-1">Body <span class="text-gray-400 font-normal">(HTML)</span></label>
                            <textarea id="mt_<?= $key ?>_body" name="mail_type_<?= $key ?>_body" rows="10"
                                      oninput="tpMailPreviewDebounced('<?= $key ?>')"
                                      class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none resize-y"
                                      placeholder="Leave empty to use the default template (shown in the preview)."><?= htmlspecialchars($bodyOverride) ?></textarea>
                        </div>

                        <div class="flex flex-wrap items-center gap-1.5">
                            <span class="text-xs text-gray-400 mr-1">Placeholders:</span>
                            <?php foreach ($t['placeholders'] as $ph): ?>
                                <button type="button" onclick="tpCopy('<?= htmlspecialchars($ph, ENT_QUOTES) ?>', this)" class="bg-gray-100 hover:bg-gray-200 text-gray-600 px-1.5 py-0.5 rounded text-xs font-mono transition-colors" title="Copy"><?= htmlspecialchars($ph) ?></button>
                            <?php endforeach; ?>
                        </div>

                        <details class="group">
                            <summary class="cursor-pointer text-xs text-gray-500 hover:text-primary-600 select-none inline-flex items-center gap-1">
                                <svg class="w-3 h-3 transition-transform group-open:rotate-90" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 18 6-6-6-6"/></svg>
                                View default HTML source
                            </summary>
                            <div class="mt-2 rounded-lg border border-gray-200 bg-gray-50 p-3 space-y-2">
                                <div class="text-xs"><span class="text-gray-400">Subject:</span> <span class="font-mono text-gray-700"><?= htmlspecialchars($t['subject']) ?></span></div>
                                <pre class="text-[11px] leading-relaxed text-gray-600 whitespace-pre-wrap break-words font-mono m-0"><?= htmlspecialchars($t['body']) ?></pre>
                            </div>
                        </details>
                    </div>

                    
                    <div>
                        <div class="text-sm font-medium text-gray-700 mb-2 flex items-center gap-1.5">
                            <svg class="w-4 h-4 text-gray-400" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
                            Inbox preview
                        </div>

                        <div class="mail-client rounded-xl border border-gray-200 shadow-sm overflow-hidden bg-white">
                            
                            <div class="flex items-center justify-between px-3 py-2 bg-gray-50 border-b border-gray-200">
                                <div class="inline-flex rounded-lg border border-gray-200 bg-white p-0.5">
                                    <button type="button" data-device="desktop" onclick="tpMailDevice('<?= $key ?>','desktop',this)" class="dev-btn inline-flex items-center gap-1 px-2.5 py-1 rounded-md text-xs font-medium bg-primary-600 text-white transition-colors">
                                        <svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg> Desktop
                                    </button>
                                    <button type="button" data-device="mobile" onclick="tpMailDevice('<?= $key ?>','mobile',this)" class="dev-btn inline-flex items-center gap-1 px-2.5 py-1 rounded-md text-xs font-medium text-gray-500 transition-colors">
                                        <svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="5" y="2" width="14" height="20" rx="2"/><path d="M12 18h.01"/></svg> Mobile
                                    </button>
                                </div>
                                <button type="button" onclick="tpMailPreview('<?= $key ?>')" class="inline-flex items-center gap-1.5 text-xs text-gray-500 hover:text-primary-600 transition-colors" title="Refresh preview">
                                    <svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/></svg> Refresh
                                </button>
                            </div>

                            
                            <div class="px-4 py-3 border-b border-gray-100 bg-white">
                                <div class="text-[15px] font-semibold text-gray-900 leading-snug mail-pv-subject" data-type="<?= $key ?>">&nbsp;</div>
                                <div class="flex items-center gap-2.5 mt-2">
                                    <div class="mail-pv-avatar w-9 h-9 rounded-full bg-primary-600 text-white flex items-center justify-center text-sm font-semibold shrink-0" data-type="<?= $key ?>">·</div>
                                    <div class="min-w-0 flex-1">
                                        <div class="text-sm text-gray-800 truncate"><span class="font-medium mail-pv-fromname" data-type="<?= $key ?>">—</span> <span class="text-gray-400">&lt;<span class="mail-pv-fromemail" data-type="<?= $key ?>">—</span>&gt;</span></div>
                                        <div class="text-xs text-gray-500 truncate">to <span class="mail-pv-to" data-type="<?= $key ?>">—</span></div>
                                    </div>
                                    <div class="text-xs text-gray-400 whitespace-nowrap mail-pv-time" data-type="<?= $key ?>"></div>
                                </div>
                            </div>

                            
                            <div class="overflow-auto" style="background:#f4f4f7;max-height:560px">
                                <div class="mail-stage mx-auto transition-[max-width] duration-200" data-type="<?= $key ?>" style="max-width:100%">
                                    <iframe class="mail-preview-frame block w-full bg-white" data-type="<?= $key ?>" sandbox="allow-same-origin" scrolling="no" style="height:280px;border:0" title="Email preview"></iframe>
                                </div>
                            </div>
                        </div>
                        <p class="mt-1 text-xs text-gray-400">Real rendered email with sample data &amp; your branding. Switch Desktop / Mobile to test responsiveness.</p>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <div class="mt-6">
        <button type="submit" class="inline-flex items-center px-4 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors">Save changes</button>
    </div>
</form>

<script>
var tpDeb = {};
function tpQ(cls, key) { return document.querySelector('.' + cls + '[data-type="' + key + '"]'); }
function tpSet(cls, key, val) { var el = tpQ(cls, key); if (el) el.textContent = val; }
function tpFrameFit(key) {
    var f = tpQ('mail-preview-frame', key);
    if (!f) return;
    try { f.style.height = (f.contentDocument.documentElement.scrollHeight + 6) + 'px'; } catch (e) {}
}
function tpMailPreviewDebounced(key) {
    clearTimeout(tpDeb[key]);
    tpDeb[key] = setTimeout(function () { tpMailPreview(key); }, 450);
}
function tpMailPreview(key) {
    var frame = tpQ('mail-preview-frame', key);
    if (!frame) return;
    var subj = document.getElementById('mt_' + key + '_subject').value;
    var body = document.getElementById('mt_' + key + '_body').value;
    var csrf = (document.querySelector('input[name="csrf_token"]') || {}).value || '';
    tpSet('mail-pv-subject', key, 'Loading…');
    fetch('/admin/settings/mail-preview', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
        body: 'csrf_token=' + encodeURIComponent(csrf) + '&type=' + encodeURIComponent(key) + '&subject=' + encodeURIComponent(subj) + '&body=' + encodeURIComponent(body)
    })
    .then(function (r) { return r.json(); })
    .then(function (d) {
        if (!d.success) { tpSet('mail-pv-subject', key, d.error || 'Preview failed'); return; }
        tpSet('mail-pv-subject', key, d.subject || '(no subject)');
        tpSet('mail-pv-fromname', key, d.from_name || '');
        tpSet('mail-pv-fromemail', key, d.from_email || '');
        tpSet('mail-pv-to', key, d.to || '');
        var av = tpQ('mail-pv-avatar', key);
        if (av) av.textContent = (d.from_name || '?').trim().charAt(0).toUpperCase() || '?';
        var tm = tpQ('mail-pv-time', key);
        if (tm) tm.textContent = new Date().toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
        frame.onload = function () { tpFrameFit(key); };
        frame.srcdoc = d.html;
    })
    .catch(function () { tpSet('mail-pv-subject', key, 'Network error'); });
}
function tpMailDevice(key, device, btn) {
    var stage = tpQ('mail-stage', key);
    if (stage) stage.style.maxWidth = device === 'mobile' ? '380px' : '100%';
    var bar = btn.parentElement;
    bar.querySelectorAll('.dev-btn').forEach(function (b) { b.classList.remove('bg-primary-600', 'text-white'); b.classList.add('text-gray-500'); });
    btn.classList.add('bg-primary-600', 'text-white'); btn.classList.remove('text-gray-500');
    setTimeout(function () { tpFrameFit(key); }, 230);
}
function tpAcc(head) {
    var item = head.closest('.accordion-item');
    var body = item.querySelector('.accordion-body');
    body.classList.toggle('hidden');
    var open = !body.classList.contains('hidden');
    var chev = head.querySelector('.acc-chevron');
    if (chev) chev.classList.toggle('rotate-90', open);
    head.setAttribute('aria-expanded', open ? 'true' : 'false');
    if (open) {
        var frame = item.querySelector('.mail-preview-frame');
        if (frame && !frame.getAttribute('srcdoc')) { tpMailPreview(item.getAttribute('data-type')); }
    }
}
function tpCopy(text, btn) {
    navigator.clipboard.writeText(text).then(function () {
        var o = btn.textContent; btn.textContent = 'Copied!';
        setTimeout(function () { btn.textContent = o; }, 900);
    });
}
</script>
