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

{% block title %}{{ theme.label }} カスタマイズ{% endblock %}

{% block content %}
<div class="page-header">
    <div class="page-header-left">
        <a href="/admin/themes" class="btn btn-ghost">&larr; テーマ一覧</a>
        <h1>{{ theme.label }} カスタマイズ</h1>
    </div>
    <div class="page-header-actions">
        <button type="button" class="btn btn-outline" id="resetBtn">リセット</button>
        <button type="button" class="btn btn-primary" id="saveBtn">保存</button>
    </div>
</div>

{% if message %}
<div class="alert alert-success" style="margin-bottom: 1rem; padding: 0.75rem 1rem; background: var(--success); color: white; border-radius: 0.5rem;">
    {{ message }}
</div>
{% endif %}

<div class="customize-layout">
    <div class="customize-sidebar">
        <!-- Site Identity -->
        {% if grouped_settings.site_identity %}
        <div class="customize-section">
            <h3>サイトID</h3>
            {% for setting in grouped_settings.site_identity %}
            <div class="customize-field">
                <label for="{{ setting.id }}">{{ setting.label }}</label>
                {% if setting.description %}
                <p class="field-description">{{ setting.description }}</p>
                {% endif %}
                <div class="image-input-wrapper">
                    <div class="image-preview" id="{{ setting.id }}_preview">
                        {% if setting.value %}
                        <img src="{{ setting.value }}" alt="{{ setting.label }}">
                        {% else %}
                        <span class="no-image">画像未設定</span>
                        {% endif %}
                    </div>
                    <input type="url"
                           id="{{ setting.id }}"
                           name="{{ setting.id }}"
                           value="{{ setting.value }}"
                           data-default="{{ setting.default }}"
                           class="customize-input image-url-input"
                           placeholder="https://example.com/image.png">
                    <div class="image-actions">
                        <button type="button" class="btn btn-sm btn-outline" onclick="clearImageInput('{{ setting.id }}')">クリア</button>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
        {% endif %}

        <!-- Header Images -->
        {% if grouped_settings.header %}
        <div class="customize-section">
            <h3>ヘッダー・背景</h3>
            {% for setting in grouped_settings.header %}
            <div class="customize-field">
                <label for="{{ setting.id }}">{{ setting.label }}</label>
                {% if setting.description %}
                <p class="field-description">{{ setting.description }}</p>
                {% endif %}
                <div class="image-input-wrapper">
                    <div class="image-preview" id="{{ setting.id }}_preview">
                        {% if setting.value %}
                        <img src="{{ setting.value }}" alt="{{ setting.label }}">
                        {% else %}
                        <span class="no-image">画像未設定</span>
                        {% endif %}
                    </div>
                    <input type="url"
                           id="{{ setting.id }}"
                           name="{{ setting.id }}"
                           value="{{ setting.value }}"
                           data-default="{{ setting.default }}"
                           class="customize-input image-url-input"
                           placeholder="https://example.com/image.png">
                    <div class="image-actions">
                        <button type="button" class="btn btn-sm btn-outline" onclick="clearImageInput('{{ setting.id }}')">クリア</button>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
        {% endif %}

        <!-- Colors -->
        {% if grouped_settings.colors %}
        <div class="customize-section">
            <h3>カラー</h3>
            {% for setting in grouped_settings.colors %}
            <div class="customize-field">
                <label for="{{ setting.id }}">{{ setting.label }}</label>
                <div class="color-input-wrapper">
                    <input type="color"
                           id="{{ setting.id }}"
                           name="{{ setting.id }}"
                           value="{{ setting.value }}"
                           data-default="{{ setting.default }}"
                           class="customize-input color-input">
                    <input type="text"
                           id="{{ setting.id }}_text"
                           value="{{ setting.value }}"
                           class="color-text-input"
                           pattern="^#[0-9A-Fa-f]{6}$">
                </div>
            </div>
            {% endfor %}
        </div>
        {% endif %}

        <!-- Fonts -->
        {% if grouped_settings.fonts %}
        <div class="customize-section">
            <h3>フォント</h3>
            {% for setting in grouped_settings.fonts %}
            <div class="customize-field">
                <label for="{{ setting.id }}">{{ setting.label }}</label>
                <input type="text"
                       id="{{ setting.id }}"
                       name="{{ setting.id }}"
                       value="{{ setting.value }}"
                       data-default="{{ setting.default }}"
                       class="customize-input font-input">
            </div>
            {% endfor %}
        </div>
        {% endif %}

        <!-- Spacing -->
        {% if grouped_settings.spacing %}
        <div class="customize-section">
            <h3>スペーシング</h3>
            {% for setting in grouped_settings.spacing %}
            <div class="customize-field">
                <label for="{{ setting.id }}">{{ setting.label }}</label>
                <input type="text"
                       id="{{ setting.id }}"
                       name="{{ setting.id }}"
                       value="{{ setting.value }}"
                       data-default="{{ setting.default }}"
                       class="customize-input spacing-input">
            </div>
            {% endfor %}
        </div>
        {% endif %}

        <!-- Custom CSS -->
        {% if grouped_settings.custom_css %}
        <div class="customize-section">
            <h3>カスタムCSS</h3>
            {% for setting in grouped_settings.custom_css %}
            <div class="customize-field">
                <label for="{{ setting.id }}">{{ setting.label }}</label>
                {% if setting.description %}
                <p class="field-description">{{ setting.description }}</p>
                {% endif %}
                <textarea id="{{ setting.id }}"
                          name="{{ setting.id }}"
                          data-default="{{ setting.default }}"
                          class="customize-input code-input"
                          rows="10"
                          placeholder="/* CSSを入力 */&#10;.my-class {&#10;  color: red;&#10;}">{{ setting.value }}</textarea>
            </div>
            {% endfor %}
        </div>
        {% endif %}
    </div>

    <div class="customize-preview">
        <div class="preview-header">
            <span>プレビュー</span>
            <div class="preview-controls">
                <button type="button" class="preview-device active" data-width="100%">Desktop</button>
                <button type="button" class="preview-device" data-width="768px">Tablet</button>
                <button type="button" class="preview-device" data-width="375px">Mobile</button>
            </div>
        </div>
        <div class="preview-container">
            <iframe id="previewFrame" src="/" class="preview-frame"></iframe>
        </div>
    </div>
</div>

<style>
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
}

.page-header-left {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.page-header-left h1 {
    margin: 0;
}

.page-header-actions {
    display: flex;
    gap: 0.5rem;
}

.customize-layout {
    display: grid;
    grid-template-columns: 320px 1fr;
    gap: 1.5rem;
    height: calc(100vh - 180px);
}

.customize-sidebar {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 0.5rem;
    padding: 1rem;
    overflow-y: auto;
}

.customize-section {
    margin-bottom: 1.5rem;
}

.customize-section h3 {
    font-size: 0.875rem;
    font-weight: 600;
    text-transform: uppercase;
    color: var(--text-muted);
    margin-bottom: 0.75rem;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid var(--border);
}

.customize-field {
    margin-bottom: 1rem;
}

.customize-field label {
    display: block;
    font-size: 0.875rem;
    font-weight: 500;
    margin-bottom: 0.25rem;
}

.customize-input {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid var(--border);
    border-radius: 0.375rem;
    font-size: 0.875rem;
}

.color-input-wrapper {
    display: flex;
    gap: 0.5rem;
}

.color-input {
    width: 48px;
    height: 36px;
    padding: 2px;
    cursor: pointer;
}

.color-text-input {
    flex: 1;
    padding: 0.5rem;
    border: 1px solid var(--border);
    border-radius: 0.375rem;
    font-size: 0.875rem;
    font-family: monospace;
}

.field-description {
    font-size: 0.75rem;
    color: var(--text-muted);
    margin-bottom: 0.5rem;
}

.code-input {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 0.8125rem;
    line-height: 1.5;
    resize: vertical;
    min-height: 150px;
    background: #1e1e1e;
    color: #d4d4d4;
    padding: 0.75rem;
}

.image-input-wrapper {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.image-preview {
    width: 100%;
    height: 80px;
    border: 2px dashed var(--border);
    border-radius: 0.375rem;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--bg);
    overflow: hidden;
}

.image-preview img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

.image-preview .no-image {
    color: var(--text-muted);
    font-size: 0.75rem;
}

.image-url-input {
    font-size: 0.8125rem;
}

.image-actions {
    display: flex;
    gap: 0.5rem;
}

.btn-sm {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
}

.customize-preview {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 0.5rem;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.75rem 1rem;
    border-bottom: 1px solid var(--border);
    background: var(--bg);
}

.preview-controls {
    display: flex;
    gap: 0.25rem;
}

.preview-device {
    padding: 0.25rem 0.75rem;
    border: 1px solid var(--border);
    background: var(--card);
    border-radius: 0.25rem;
    font-size: 0.75rem;
    cursor: pointer;
}

.preview-device.active {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}

.preview-container {
    flex: 1;
    display: flex;
    justify-content: center;
    padding: 1rem;
    background: #f0f0f0;
    overflow: auto;
}

.preview-frame {
    width: 100%;
    height: 100%;
    border: none;
    background: white;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    transition: width 0.3s ease;
}

@media (max-width: 1024px) {
    .customize-layout {
        grid-template-columns: 1fr;
        height: auto;
    }

    .customize-preview {
        height: 500px;
    }
}
</style>

<script>
(function() {
    const themeName = '{{ theme.name }}';
    const csrfToken = '{{ csrf_token }}';
    let debounceTimer = null;

    // Get all customize inputs
    const inputs = document.querySelectorAll('.customize-input');
    const colorTextInputs = document.querySelectorAll('.color-text-input');
    const previewFrame = document.getElementById('previewFrame');
    const saveBtn = document.getElementById('saveBtn');
    const resetBtn = document.getElementById('resetBtn');
    const deviceButtons = document.querySelectorAll('.preview-device');

    // Collect current values
    function getValues() {
        const values = {};
        inputs.forEach(input => {
            values[input.name] = input.value;
        });
        return values;
    }

    // Update preview CSS
    async function updatePreview() {
        const values = getValues();

        try {
            const response = await fetch('/admin/api/theme/preview-css', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-Token': csrfToken
                },
                body: JSON.stringify({
                    theme_name: themeName,
                    values: values
                })
            });

            if (response.ok) {
                const css = await response.text();
                injectPreviewCSS(css);
            }
        } catch (error) {
            console.error('Preview update failed:', error);
        }
    }

    // Inject CSS into preview iframe
    function injectPreviewCSS(css) {
        try {
            const iframeDoc = previewFrame.contentDocument || previewFrame.contentWindow.document;
            let styleEl = iframeDoc.getElementById('customize-preview-style');

            if (!styleEl) {
                styleEl = iframeDoc.createElement('style');
                styleEl.id = 'customize-preview-style';
                iframeDoc.head.appendChild(styleEl);
            }

            styleEl.textContent = css;
        } catch (error) {
            console.error('Could not inject CSS:', error);
        }
    }

    // Debounced preview update
    function debouncedUpdate() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(updatePreview, 300);
    }

    // Sync color picker with text input
    function syncColorInputs(colorInput, textInput) {
        colorInput.addEventListener('input', () => {
            textInput.value = colorInput.value;
            debouncedUpdate();
        });

        textInput.addEventListener('input', () => {
            if (/^#[0-9A-Fa-f]{6}$/.test(textInput.value)) {
                colorInput.value = textInput.value;
                debouncedUpdate();
            }
        });
    }

    // Setup color input sync
    document.querySelectorAll('.color-input').forEach(colorInput => {
        const textInput = document.getElementById(colorInput.id + '_text');
        if (textInput) {
            syncColorInputs(colorInput, textInput);
        }
    });

    // Listen for input changes
    inputs.forEach(input => {
        if (!input.classList.contains('color-input')) {
            input.addEventListener('input', debouncedUpdate);
        }
        // Add image preview update for image-url-input
        if (input.classList.contains('image-url-input')) {
            input.addEventListener('input', () => {
                updateImagePreview(input.id, input.value);
            });
        }
    });

    // Update image preview
    function updateImagePreview(inputId, url) {
        const previewEl = document.getElementById(inputId + '_preview');
        if (!previewEl) return;

        if (url && url.trim()) {
            previewEl.innerHTML = `<img src="${url}" alt="Preview" onerror="this.parentElement.innerHTML='<span class=\\'no-image\\'>読み込みエラー</span>'">`;
        } else {
            previewEl.innerHTML = '<span class="no-image">画像未設定</span>';
        }
    }

    // Clear image input (global function for onclick)
    window.clearImageInput = function(inputId) {
        const input = document.getElementById(inputId);
        if (input) {
            input.value = '';
            updateImagePreview(inputId, '');
            debouncedUpdate();
        }
    };

    // Save button
    saveBtn.addEventListener('click', async () => {
        const values = getValues();

        try {
            saveBtn.disabled = true;
            saveBtn.textContent = '保存中...';

            const response = await fetch('/admin/api/theme/settings', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-Token': csrfToken
                },
                body: JSON.stringify({
                    theme_name: themeName,
                    values: values
                })
            });

            const result = await response.json();

            if (result.success) {
                window.location.href = '/admin/themes/' + themeName + '/customize?message=' + encodeURIComponent(result.message);
            } else {
                alert('保存に失敗しました: ' + (result.detail || result.message));
            }
        } catch (error) {
            alert('保存に失敗しました: ' + error.message);
        } finally {
            saveBtn.disabled = false;
            saveBtn.textContent = '保存';
        }
    });

    // Reset button
    resetBtn.addEventListener('click', () => {
        if (!confirm('カスタマイズをデフォルトに戻しますか？')) return;

        inputs.forEach(input => {
            const defaultValue = input.dataset.default || '';
            input.value = defaultValue;

            // Sync color text input
            if (input.classList.contains('color-input')) {
                const textInput = document.getElementById(input.id + '_text');
                if (textInput) textInput.value = defaultValue;
            }

            // Update image preview
            if (input.classList.contains('image-url-input')) {
                updateImagePreview(input.id, defaultValue);
            }
        });

        updatePreview();
    });

    // Device preview buttons
    deviceButtons.forEach(btn => {
        btn.addEventListener('click', () => {
            deviceButtons.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            previewFrame.style.width = btn.dataset.width;
        });
    });

    // Initial preview update after iframe loads
    previewFrame.addEventListener('load', () => {
        updatePreview();
    });
})();
</script>
{% endblock %}
