<form method="POST" action="/admin/settings">
    <?= Router::csrfField() ?>
    <input type="hidden" name="_tab" value="general">

    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
        <div class="p-6 space-y-5">
            <div>
                <label for="site_name" class="block text-sm font-medium text-gray-700 mb-1">Site name</label>
                <input type="text" id="site_name" name="site_name" value="<?= htmlspecialchars($settings['site_name'] ?? '') ?>"
                       class="w-full max-w-lg 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">
                <p class="mt-1 text-xs text-gray-500">The name displayed in the browser title bar and throughout the site.</p>
            </div>

            <div>
                <label for="site_description" class="block text-sm font-medium text-gray-700 mb-1">Site description</label>
                <textarea id="site_description" name="site_description" rows="3"
                          class="w-full max-w-lg 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 resize-y"><?= htmlspecialchars($settings['site_description'] ?? '') ?></textarea>
                <p class="mt-1 text-xs text-gray-500">A short tagline describing your site.</p>
            </div>

            <div>
                <label for="timezone" class="block text-sm font-medium text-gray-700 mb-1">Timezone</label>
                <?php
                    $currentTz = $settings['timezone'] ?? 'UTC';
                    $tzList = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
                    $nowUtc = new DateTime('now', new DateTimeZone('UTC'));
                    $tzGrouped = [];
                    foreach ($tzList as $tz) {
                        $parts = explode('/', $tz, 2);
                        $group = count($parts) > 1 ? $parts[0] : 'Other';
                        $dtz = new DateTimeZone($tz);
                        $offset = $dtz->getOffset($nowUtc);
                        $sign = $offset >= 0 ? '+' : '-';
                        $absOffset = abs($offset);
                        $h = str_pad((string) intdiv($absOffset, 3600), 2, '0', STR_PAD_LEFT);
                        $m = str_pad((string) (($absOffset % 3600) / 60), 2, '0', STR_PAD_LEFT);
                        $label = $tz . ' (UTC' . $sign . $h . ':' . $m . ')';
                        $tzGrouped[$group][] = ['id' => $tz, 'label' => $label, 'offset' => $offset];
                    }
                    ksort($tzGrouped);
                    foreach ($tzGrouped as &$zones) {
                        usort($zones, fn($a, $b) => $a['offset'] <=> $b['offset'] ?: strcmp($a['id'], $b['id']));
                    }
                    unset($zones);
                ?>
                <div class="relative max-w-lg" id="tzPicker">
                    <input type="text" id="tzSearch" autocomplete="off" placeholder="Search timezone..."
                           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">
                    <input type="hidden" name="timezone" id="tzValue" value="<?= htmlspecialchars($currentTz) ?>">
                    <div id="tzDropdown" class="absolute z-30 left-0 right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-64 overflow-y-auto hidden">
                    </div>
                </div>
                <p class="mt-1 text-xs text-gray-500">All dates and times will use this timezone.</p>
                <script>
                (function(){
                    const zones = <?= json_encode(array_merge(...array_map(fn($g, $zs) => array_map(fn($z) => ['id'=>$z['id'],'label'=>$z['label'],'group'=>$g], $zs), array_keys($tzGrouped), array_values($tzGrouped))), JSON_UNESCAPED_UNICODE) ?>;
                    const input = document.getElementById('tzSearch');
                    const hidden = document.getElementById('tzValue');
                    const dropdown = document.getElementById('tzDropdown');
                    let selected = -1;

                    
                    const current = zones.find(z => z.id === hidden.value);
                    if (current) input.value = current.label;

                    function render(filter) {
                        const q = (filter || '').toLowerCase().trim();
                        let html = '', count = 0, lastGroup = '';
                        for (const z of zones) {
                            if (q && !z.label.toLowerCase().includes(q) && !z.id.toLowerCase().includes(q)) continue;
                            if (z.group !== lastGroup) {
                                lastGroup = z.group;
                                html += '<div class="px-3 py-1.5 text-xs font-semibold text-gray-400 bg-gray-50 sticky top-0">' + lastGroup + '</div>';
                            }
                            let display = z.label;
                            if (q) {
                                display = display.replace(new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + ')', 'gi'), '<mark class="bg-yellow-100 text-inherit rounded px-0.5">$1</mark>');
                            }
                            html += '<div class="tz-opt px-3 py-2 text-sm cursor-pointer hover:bg-primary-50 hover:text-primary-700 transition-colors" data-id="' + z.id + '" data-label="' + z.label.replace(/"/g,'&quot;') + '">' + display + '</div>';
                            count++;
                        }
                        if (!count) html = '<div class="px-3 py-3 text-sm text-gray-400 text-center">No timezone found</div>';
                        dropdown.innerHTML = html;
                        selected = -1;
                    }

                    function open() { render(input.value === (current?.label||'') ? '' : input.value); dropdown.classList.remove('hidden'); }
                    function close() { setTimeout(() => dropdown.classList.add('hidden'), 150); }

                    input.addEventListener('focus', function() { this.select(); open(); });
                    input.addEventListener('blur', close);
                    input.addEventListener('input', function() { open(); });

                    input.addEventListener('keydown', function(e) {
                        const opts = dropdown.querySelectorAll('.tz-opt');
                        if (e.key === 'ArrowDown') { e.preventDefault(); selected = Math.min(selected + 1, opts.length - 1); highlight(opts); }
                        else if (e.key === 'ArrowUp') { e.preventDefault(); selected = Math.max(selected - 1, 0); highlight(opts); }
                        else if (e.key === 'Enter') { e.preventDefault(); if (opts[selected]) pick(opts[selected]); }
                        else if (e.key === 'Escape') { input.blur(); }
                    });

                    function highlight(opts) {
                        opts.forEach((o, i) => { o.classList.toggle('bg-primary-50', i === selected); o.classList.toggle('text-primary-700', i === selected); });
                        if (opts[selected]) opts[selected].scrollIntoView({ block: 'nearest' });
                    }

                    function pick(el) {
                        hidden.value = el.dataset.id;
                        input.value = el.dataset.label;
                        dropdown.classList.add('hidden');
                    }

                    dropdown.addEventListener('mousedown', function(e) {
                        const opt = e.target.closest('.tz-opt');
                        if (opt) { e.preventDefault(); pick(opt); }
                    });
                })();
                </script>
            </div>

            <div class="border-t border-gray-200 pt-5">
                <div class="mb-5">
                    <h3 class="text-sm font-medium text-gray-900 mb-3">Search engine visibility</h3>
                    <label class="flex items-start gap-3 cursor-pointer p-3 rounded-lg border <?= ($settings['seo_noindex_entire_site'] ?? '0') === '1' ? 'border-amber-300 bg-amber-50' : 'border-gray-200 bg-white' ?> transition-colors">
                        <input type="checkbox" name="seo_noindex_entire_site" value="1"
                               class="w-4 h-4 mt-0.5 rounded border-gray-300 text-amber-600 focus:ring-amber-500"
                               onchange="var w=this.closest('label');w.classList.toggle('border-amber-300',this.checked);w.classList.toggle('bg-amber-50',this.checked);w.classList.toggle('border-gray-200',!this.checked);w.classList.toggle('bg-white',!this.checked);document.getElementById('noindexWarn').style.display=this.checked?'':'none'"
                            <?= ($settings['seo_noindex_entire_site'] ?? '0') === '1' ? ' checked' : '' ?>>
                        <div class="flex-1">
                            <span class="text-sm text-gray-700">Discourage search engines from indexing this site</span>
                            <p class="mt-0.5 text-xs text-gray-500">Adds <code class="text-xs bg-gray-100 px-1 py-0.5 rounded">noindex, nofollow</code> to every page and blocks crawlers via <code class="text-xs bg-gray-100 px-1 py-0.5 rounded">robots.txt</code>. It is up to search engines to honor this request.</p>
                            <p id="noindexWarn" class="mt-2 text-xs font-medium text-amber-700" style="<?= ($settings['seo_noindex_entire_site'] ?? '0') !== '1' ? 'display:none' : '' ?>">
                                <svg class="inline w-3.5 h-3.5 -mt-0.5 mr-0.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"/></svg>
                                Your site is currently hidden from search engines.
                            </p>
                        </div>
                    </label>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                    <div>
                        <h3 class="text-sm font-medium text-gray-900 mb-3">Users</h3>
                        <div class="space-y-3">
                        <label class="flex items-center gap-3 cursor-pointer">
                            <input type="checkbox" name="registration_enabled" value="1"
                                   class="w-4 h-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                                <?php if (!empty($settings['registration_enabled'])): ?> checked<?php endif; ?>>
                            <div>
                                <span class="text-sm text-gray-700">Enable registration</span>
                                <p class="text-xs text-gray-500">Allow visitors to create an account.</p>
                            </div>
                        </label>
                        <label class="flex items-center gap-3 cursor-pointer">
                            <input type="checkbox" name="auto_update_enabled" value="1"
                                   class="w-4 h-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                                <?php if (!empty($settings['auto_update_enabled'])): ?> checked<?php endif; ?>>
                            <div>
                                <span class="text-sm text-gray-700">Automatic updates (CMS &amp; plugins)</span>
                                <p class="text-xs text-gray-500">Auto-apply signed CMS core &amp; free plugin updates (each backed up, auto-rollback on failure). Themes always update manually. Off by default.</p>
                            </div>
                        </label>
                        <label class="flex items-center gap-3 cursor-pointer">
                            <input type="checkbox" name="channels_as_users" value="1"
                                   class="w-4 h-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                                <?= Setting::get('channels_as_users', '1') === '1' ? ' checked' : '' ?>>
                            <div>
                                <span class="text-sm text-gray-700">Channels are users</span>
                                <p class="text-xs text-gray-500">On import, create a user account for each channel (channel = user) and assign its videos to it. The channel profile (logo, bio, pages) is always created either way.</p>
                            </div>
                        </label>
                        <label class="flex items-center gap-3 cursor-pointer">
                            <input type="checkbox" name="albums_enabled" value="1"
                                   class="w-4 h-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                                <?= (($settings['albums_enabled'] ?? '1') === '1') ? ' checked' : '' ?>>
                            <div>
                                <span class="text-sm text-gray-700">Albums (image galleries)</span>
                                <p class="text-xs text-gray-500">Enable the Albums content type. When off, public album pages return HTTP 410, album links disappear from menus, profiles, search &amp; the sitemap, and album sections are hidden site-wide (no SEO dead-ends). Album data is preserved and reappears when re-enabled.</p>
                            </div>
                        </label>
                        </div>
                    </div>
                    <div>
                        <h3 class="text-sm font-medium text-gray-900 mb-3">Comments</h3>
                        <div class="space-y-3">
                            <label class="flex items-center gap-3 cursor-pointer">
                                <input type="checkbox" name="comments_enabled" value="1" id="commentsEnabled"
                                       class="w-4 h-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                                       onchange="document.getElementById('spamLink').style.display=this.checked?'':'none'"
                                    <?= ($settings['comments_enabled'] ?? '1') === '1' ? ' checked' : '' ?>>
                                <div>
                                    <span class="text-sm text-gray-700">Enable comments</span>
                                    <p class="text-xs text-gray-500">Allow comments on videos.</p>
                                </div>
                            </label>
                            <label class="flex items-center gap-3 cursor-pointer">
                                <input type="checkbox" name="comments_moderation" value="1"
                                       class="w-4 h-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                                    <?= ($settings['comments_moderation'] ?? '0') === '1' ? ' checked' : '' ?>>
                                <div>
                                    <span class="text-sm text-gray-700">Moderation</span>
                                    <p class="text-xs text-gray-500">Approve comments before they appear.</p>
                                </div>
                            </label>
                        </div>
                        <div id="spamLink" class="mt-3" style="<?= ($settings['comments_enabled'] ?? '1') !== '1' ? 'display:none' : '' ?>">
                            <button type="button" onclick="document.getElementById('spamModal').classList.add('open')"
                                    class="inline-flex items-center gap-1.5 text-xs text-gray-500 hover:text-primary-600 transition-colors">
                                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                                Anti-spam settings&hellip;
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 rounded-b-lg">
            <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>
    </div>

    
    <?php $sg = function(string $k, string $d) use ($settings) { return $settings[$k] ?? $d; }; ?>
    <div id="spamModal" style="display:none;position:fixed;inset:0;z-index:50;align-items:center;justify-content:center;background:rgba(0,0,0,.4)"
         onclick="if(event.target===this)this.classList.remove('open')">
        <div style="background:#fff;border-radius:12px;box-shadow:0 20px 60px rgba(0,0,0,.2);width:100%;max-width:480px;max-height:90vh;overflow-y:auto;margin:16px">

            <div style="padding:20px 24px 0;display:flex;align-items:center;justify-content:space-between">
                <h3 style="font-size:15px;font-weight:600;color:#111;display:flex;align-items:center;gap:8px">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                    Comment Anti-Spam
                </h3>
                <button type="button" onclick="document.getElementById('spamModal').classList.remove('open')"
                        style="background:none;border:none;cursor:pointer;color:#999;font-size:20px;line-height:1;padding:4px">&times;</button>
            </div>
            <p style="padding:4px 24px 16px;font-size:12px;color:#888;margin:0">Toggle each protection independently. Works with or without <a href="/admin/settings?tab=security" style="color:#4f46e5;text-decoration:underline">reCAPTCHA</a>.</p>

            <div style="padding:0 24px 24px;display:flex;flex-direction:column;gap:16px">
                
                <label style="display:flex;align-items:flex-start;gap:10px;font-size:13px;color:#333;cursor:pointer">
                    <input type="checkbox" name="spam_honeypot" value="1" style="width:16px;height:16px;accent-color:#4f46e5;margin-top:2px" <?= $sg('spam_honeypot', '1') === '1' ? 'checked' : '' ?>>
                    <span style="flex:1">
                        <strong style="color:#111">Bot trap</strong>
                        <span style="display:block;font-size:11px;color:#888;margin-top:1px">Adds a hidden field that only bots fill in.</span>
                    </span>
                </label>

                
                <div style="display:flex;align-items:flex-start;gap:10px;font-size:13px;color:#333">
                    <input type="checkbox" name="spam_timegate" value="1" style="width:16px;height:16px;accent-color:#4f46e5;margin-top:2px" <?= $sg('spam_timegate', '1') === '1' ? 'checked' : '' ?>>
                    <span style="flex:1">
                        <strong style="color:#111">Minimum time on page</strong>
                        <span style="display:block;font-size:11px;color:#888;margin-top:1px">Reject comments posted faster than a human can type.</span>
                    </span>
                    <span style="display:flex;align-items:center;gap:4px;white-space:nowrap">
                        <input type="number" name="spam_timegate_seconds" value="<?= (int)$sg('spam_timegate_seconds', '3') ?>" min="1" max="30"
                               style="width:48px;padding:3px 6px;border:1px solid #d1d5db;border-radius:6px;font-size:12px;text-align:center">
                        <span style="font-size:11px;color:#888">sec</span>
                    </span>
                </div>

                
                <div style="display:flex;align-items:flex-start;gap:10px;font-size:13px;color:#333">
                    <input type="checkbox" name="spam_ratelimit" value="1" style="width:16px;height:16px;accent-color:#4f46e5;margin-top:2px" <?= $sg('spam_ratelimit', '1') === '1' ? 'checked' : '' ?>>
                    <span style="flex:1">
                        <strong style="color:#111">Rate limit per IP</strong>
                        <span style="display:block;font-size:11px;color:#888;margin-top:1px">Limit how many comments one visitor can post.</span>
                    </span>
                    <span style="display:flex;align-items:center;gap:4px;white-space:nowrap">
                        <input type="number" name="spam_ratelimit_hour" value="<?= (int)$sg('spam_ratelimit_hour', '5') ?>" min="1" max="100"
                               style="width:48px;padding:3px 6px;border:1px solid #d1d5db;border-radius:6px;font-size:12px;text-align:center">
                        <span style="font-size:11px;color:#888">/h</span>
                        <input type="number" name="spam_ratelimit_day" value="<?= (int)$sg('spam_ratelimit_day', '30') ?>" min="1" max="500"
                               style="width:48px;padding:3px 6px;border:1px solid #d1d5db;border-radius:6px;font-size:12px;text-align:center;margin-left:2px">
                        <span style="font-size:11px;color:#888">/day</span>
                    </span>
                </div>

                
                <div style="display:flex;align-items:flex-start;gap:10px;font-size:13px;color:#333">
                    <input type="checkbox" name="spam_duplicate" value="1" style="width:16px;height:16px;accent-color:#4f46e5;margin-top:2px" <?= $sg('spam_duplicate', '1') === '1' ? 'checked' : '' ?>>
                    <span style="flex:1">
                        <strong style="color:#111">Block duplicate comments</strong>
                        <span style="display:block;font-size:11px;color:#888;margin-top:1px">Prevent the same message from being posted twice.</span>
                    </span>
                    <span style="display:flex;align-items:center;gap:4px;white-space:nowrap">
                        <input type="number" name="spam_duplicate_window" value="<?= (int)$sg('spam_duplicate_window', '60') ?>" min="1" max="1440"
                               style="width:52px;padding:3px 6px;border:1px solid #d1d5db;border-radius:6px;font-size:12px;text-align:center">
                        <span style="font-size:11px;color:#888">min</span>
                    </span>
                </div>

                
                <div style="display:flex;align-items:flex-start;gap:10px;font-size:13px;color:#333">
                    <input type="checkbox" name="spam_links" value="1" style="width:16px;height:16px;accent-color:#4f46e5;margin-top:2px" <?= $sg('spam_links', '1') === '1' ? 'checked' : '' ?>>
                    <span style="flex:1">
                        <strong style="color:#111">Block links</strong>
                        <span style="display:block;font-size:11px;color:#888;margin-top:1px">Reject comments containing URLs. Set 0 to block all links.</span>
                    </span>
                    <span style="display:flex;align-items:center;gap:4px;white-space:nowrap">
                        <span style="font-size:11px;color:#888">max</span>
                        <input type="number" name="spam_max_links" value="<?= (int)$sg('spam_max_links', '0') ?>" min="0" max="20"
                               style="width:48px;padding:3px 6px;border:1px solid #d1d5db;border-radius:6px;font-size:12px;text-align:center">
                    </span>
                </div>

                
                <div style="display:flex;align-items:flex-start;gap:10px;font-size:13px;color:#333">
                    <input type="checkbox" name="spam_length" value="1" style="width:16px;height:16px;accent-color:#4f46e5;margin-top:2px" <?= $sg('spam_length', '1') === '1' ? 'checked' : '' ?>>
                    <span style="flex:1">
                        <strong style="color:#111">Comment length</strong>
                        <span style="display:block;font-size:11px;color:#888;margin-top:1px">Require a minimum and maximum number of characters.</span>
                    </span>
                    <span style="display:flex;align-items:center;gap:4px;white-space:nowrap">
                        <input type="number" name="spam_min_length" value="<?= (int)$sg('spam_min_length', '2') ?>" min="1" max="500"
                               style="width:48px;padding:3px 6px;border:1px solid #d1d5db;border-radius:6px;font-size:12px;text-align:center">
                        <span style="font-size:11px;color:#888">–</span>
                        <input type="number" name="spam_max_length" value="<?= (int)$sg('spam_max_length', '5000') ?>" min="10" max="50000"
                               style="width:60px;padding:3px 6px;border:1px solid #d1d5db;border-radius:6px;font-size:12px;text-align:center">
                        <span style="font-size:11px;color:#888">chars</span>
                    </span>
                </div>
            </div>

            <div style="padding:12px 24px;border-top:1px solid #e5e7eb;text-align:right">
                <button type="button" onclick="document.getElementById('spamModal').classList.remove('open')"
                        style="padding:6px 16px;font-size:13px;font-weight:500;background:#4f46e5;color:#fff;border:none;border-radius:8px;cursor:pointer">Done</button>
            </div>
        </div>
    </div>
    <style>
        #spamModal.open{display:flex!important}
    </style>
</form>
