{% extends "admin/base.html" %}

{% block title %}Site Settings - Admin - {{ site_name() }}{% endblock %}

{% block head %}
<style nonce="{{ csp_nonce() }}">
.sk-favicon-zone{border:1.5px dashed var(--sk-color-border);border-radius:var(--sk-radius-lg);background:var(--sk-color-surface);transition:border-color var(--sk-transition-fast),background var(--sk-transition-fast);overflow:hidden}
.sk-favicon-zone.sk-drag-over{border-color:var(--sk-color-accent);background:rgba(52,211,153,.06)}
.sk-favicon-empty{display:flex;align-items:center;justify-content:center;padding:var(--sk-space-sm) var(--sk-space-md);cursor:pointer}
.sk-favicon-empty .sk-btn-outline{pointer-events:none}
.sk-favicon-preview{display:flex;align-items:center;gap:var(--sk-space-sm);padding:var(--sk-space-sm) var(--sk-space-md)}
.sk-favicon-preview img{width:2rem;height:2rem;object-fit:cover;border-radius:var(--sk-radius-sm);flex-shrink:0;background:var(--sk-color-surface-hover)}
.sk-favicon-filename{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:.8rem;color:var(--sk-color-muted)}
.sk-favicon-remove{all:unset;cursor:pointer;font-size:1.1rem;line-height:1;color:var(--sk-color-muted);padding:0 var(--sk-space-xs);flex-shrink:0;transition:color var(--sk-transition-fast)}
.sk-favicon-remove:hover{color:var(--sk-color-error)}
[hidden].sk-favicon-empty,[hidden].sk-favicon-preview{display:none}
</style>
{% endblock %}

{% block admin_content %}
<hgroup>
    <h1>Site Settings</h1>
    <p>Configure your site's name, tagline, and other metadata &middot; <a href="#" id="details-link" class="sk-text-muted">Details</a></p>
</hgroup>

<dialog id="system-info-dialog" class="sk-dialog">
    <div class="sk-dialog-header">
        <h3>System Details</h3>
        <button type="button" class="sk-dialog-close" aria-label="Close">&times;</button>
    </div>
    <div class="sk-dialog-body" id="system-info-content">
        <p class="sk-text-muted">Loading...</p>
    </div>
</dialog>

{% if sites_list %}
<label for="site_selector">Site</label>
<select id="site_selector" onchange="window.location.href='/admin/settings?site=' + this.value">
    {% for site in sites_list %}
    <option value="{{ site.key }}"{% if site.key == selected_site %} selected{% endif %}>{{ site.label }}</option>
    {% endfor %}
</select>
<small class="sk-text-muted">Select which site to configure</small>
{% endif %}

<form method="post" action="/admin/settings" enctype="multipart/form-data">
    {% if sites_list %}
    <input type="hidden" name="_site" value="{{ selected_site }}">
    {% endif %}

    <label for="site_name">Site Name</label>
    <input type="text" id="site_name" name="site_name" value="{{ settings.site_name }}" required>
    <small class="sk-text-muted">The name displayed in the header and browser title</small>

    <label for="site_tagline">Site Tagline</label>
    <input type="text" id="site_tagline" name="site_tagline" value="{{ settings.site_tagline }}">
    <small class="sk-text-muted">A short description or slogan for your site</small>

    {% if not selected_site %}
    <label for="site_copyright_holder">Copyright Holder</label>
    <input type="text" id="site_copyright_holder" name="site_copyright_holder" value="{{ settings.site_copyright_holder }}">
    <small class="sk-text-muted">Name displayed in the copyright notice (defaults to site name if empty)</small>

    <label for="site_copyright_start_year">Copyright Start Year</label>
    <input type="number" id="site_copyright_start_year" name="site_copyright_start_year" value="{{ settings.site_copyright_start_year }}" min="1900" max="2100">
    <small class="sk-text-muted">If different from current year, will show a range (e.g., 2020-2026)</small>

    <label for="robots_txt">robots.txt</label>
    <textarea id="robots_txt" name="robots_txt" rows="6" placeholder="User-agent: *&#10;Allow: /&#10;&#10;Sitemap: https://example.com/sitemap.xml">{{ settings.robots_txt }}</textarea>
    <small class="sk-text-muted">Custom robots.txt content. Leave empty to use the default.</small>

    {% if theme_data %}
    <label for="site_theme">Theme</label>
    <select id="site_theme" name="site_theme">
        <option value=""{% if not theme_data.active %} selected{% endif %}>Default (no theme)</option>
        {% for theme in theme_data.themes %}
        <option value="{{ theme.directory_name }}"{% if theme_data.active == theme.directory_name %} selected{% endif %}>
            {{ theme.name }}{% if theme.version %} (v{{ theme.version }}){% endif %}
        </option>
        {% endfor %}
    </select>
    <small class="sk-text-muted">Select a theme to change your site's appearance</small>
    {% endif %}

    <label>Favicon</label>
    <div class="sk-favicon-zone" id="sk-favicon-zone">
        <div class="sk-favicon-preview" id="sk-favicon-preview"{% if not current_favicon_url %} hidden{% endif %}>
            <img id="sk-favicon-img" src="{{ current_favicon_url | sized('icon') if current_favicon_url else '' }}" alt="Favicon preview">
            <span class="sk-favicon-filename" id="sk-favicon-filename">{{ "Current favicon" if current_favicon_url else "" }}</span>
            <button type="button" class="sk-favicon-remove" id="sk-favicon-remove" title="Remove">&times;</button>
        </div>
        <div class="sk-favicon-empty" id="sk-favicon-empty"{% if current_favicon_url %} hidden{% endif %}>
            <span class="sk-btn-outline sk-btn-small">Choose image</span>
        </div>
        <input type="file" id="sk-favicon-input" name="favicon" accept="image/*" hidden>
    </div>
    <small class="sk-text-muted">Upload a square image (recommended: 256&times;256 or larger)</small>
    {% endif %}

    <div class="sk-form-actions">
        <button type="submit">Save Settings</button>
    </div>
</form>
{% endblock %}

{% block scripts %}
<script nonce="{{ csp_nonce() }}">
(function() {
    var zone = document.getElementById("sk-favicon-zone");
    var input = document.getElementById("sk-favicon-input");
    var preview = document.getElementById("sk-favicon-preview");
    var img = document.getElementById("sk-favicon-img");
    var fname = document.getElementById("sk-favicon-filename");
    var empty = document.getElementById("sk-favicon-empty");
    var removeBtn = document.getElementById("sk-favicon-remove");
    if (!zone) return;

    function showPreview(file) {
        var reader = new FileReader();
        reader.onload = function(e) {
            img.src = e.target.result;
            fname.textContent = file.name;
            preview.hidden = false;
            empty.hidden = true;
        };
        reader.readAsDataURL(file);
    }

    function clearPreview() {
        img.src = "";
        fname.textContent = "";
        preview.hidden = true;
        empty.hidden = false;
        input.value = "";
    }

    input.addEventListener("change", function() {
        if (input.files.length) showPreview(input.files[0]);
    });

    empty.addEventListener("click", function() { input.click(); });
    preview.addEventListener("click", function(e) {
        if (e.target !== removeBtn && !removeBtn.contains(e.target)) input.click();
    });
    removeBtn.addEventListener("click", function(e) { e.stopPropagation(); clearPreview(); });

    var dragCounter = 0;
    zone.addEventListener("dragenter", function(e) { e.preventDefault(); dragCounter++; zone.classList.add("sk-drag-over"); });
    zone.addEventListener("dragleave", function(e) { e.preventDefault(); dragCounter--; if (dragCounter <= 0) { dragCounter = 0; zone.classList.remove("sk-drag-over"); } });
    zone.addEventListener("dragover", function(e) { e.preventDefault(); });
    zone.addEventListener("drop", function(e) {
        e.preventDefault();
        dragCounter = 0;
        zone.classList.remove("sk-drag-over");
        var files = e.dataTransfer.files;
        if (files.length) {
            var file = files[0];
            if (file.type.startsWith("image/")) {
                var dt = new DataTransfer();
                dt.items.add(file);
                input.files = dt.files;
                showPreview(file);
            }
        }
    });
})();
</script>
<script nonce="{{ csp_nonce() }}">
(function() {
    const dialog = document.getElementById('system-info-dialog');
    const content = document.getElementById('system-info-content');
    const link = document.getElementById('details-link');
    const closeBtn = dialog.querySelector('.sk-dialog-close');

    link.addEventListener('click', function(e) {
        e.preventDefault();
        dialog.showModal();
        content.innerHTML = '<p class="sk-text-muted">Loading...</p>';
        fetch('/admin/system-info')
            .then(r => r.json())
            .then(data => {
                const shortHead = data.alembic_head.length > 12
                    ? data.alembic_head.slice(0, 12)
                    : data.alembic_head;
                let rows = '';
                for (const dep of data.dependencies) {
                    rows += '<tr><td>' + dep.name + '</td><td>' + dep.version + '</td></tr>';
                }
                content.innerHTML =
                    '<table class="sk-admin-table">' +
                    '<tbody>' +
                    '<tr><td>Skrift version</td><td>' + data.version + '</td></tr>' +
                    '<tr><td>Migration head</td><td><code>' + shortHead + '</code></td></tr>' +
                    '</tbody></table>' +
                    '<h4>Dependencies</h4>' +
                    '<table class="sk-admin-table"><thead><tr><th>Package</th><th>Version</th></tr></thead>' +
                    '<tbody>' + rows + '</tbody></table>';
            })
            .catch(() => {
                content.innerHTML = '<p style="color:var(--sk-color-danger)">Failed to load system info.</p>';
            });
    });

    closeBtn.addEventListener('click', () => dialog.close());
    dialog.addEventListener('click', function(e) {
        if (e.target === dialog) dialog.close();
    });
})();
</script>
{% endblock %}
