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

{% block title %}{{ title }} - Zebra Day{% endblock %}

{% block content %}
<div class="page-header">
    <h1 class="page-title">{{ title }}</h1>
    <div class="header-actions">
        <a href="/config" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Back</a>
        {% if mode == 'edit' %}
        <button type="button" class="btn btn-outline" onclick="resetConfig()"><i class="fas fa-undo"></i> Reset</button>
        <button type="button" class="btn btn-outline" onclick="clearConfig()"><i class="fas fa-trash"></i> Clear</button>
        {% endif %}
    </div>
</div>

{% if error_msg %}
<div class="alert alert-error mb-lg">
    <i class="fas fa-exclamation-circle"></i> {{ error_msg }}
</div>
{% endif %}

<div class="card">
    <div class="card-header">
        <h3 class="card-title"><i class="fas fa-file-code"></i> Printer Configuration JSON</h3>
        {% if mode == 'edit' %}
        <span class="badge badge-warning">Editing</span>
        {% else %}
        <span class="badge badge-info">Read Only</span>
        {% endif %}
    </div>
    <form method="post" action="/config/save">
        <div class="form-group">
            <textarea name="json_data" id="json-editor" class="form-control code-editor" rows="30" {% if mode != 'edit' %}readonly{% endif %}>{{ config_json }}</textarea>
        </div>
        {% if mode == 'edit' %}
        <div class="form-actions">
            <button type="submit" class="btn btn-primary" onclick="showLoading('Saving configuration...')">
                <i class="fas fa-save"></i> Save Configuration
            </button>
        </div>
        {% endif %}
    </form>
</div>

<style>
.code-editor {
    font-family: 'JetBrains Mono', 'Consolas', monospace;
    font-size: 0.875rem;
    line-height: 1.5;
    background: var(--color-gray-700);
    border: 1px solid var(--color-gray-600);
    padding: 1rem;
    resize: vertical;
    min-height: 400px;
}
.code-editor:read-only {
    background: var(--color-gray-800);
    cursor: default;
}
.form-actions {
    display: flex;
    gap: 1rem;
    padding: 1rem;
    border-top: 1px solid var(--color-gray-600);
}
</style>

<script>
async function resetConfig() {
    if (confirm('Reset configuration to template defaults? This will backup the current config.')) {
        showLoading('Resetting configuration...');
        window.location.href = '/config/reset';
    }
}

async function clearConfig() {
    if (confirm('Clear all printer configuration? This will backup the current config.')) {
        showLoading('Clearing configuration...');
        window.location.href = '/config/clear';
    }
}

// Auto-format JSON on blur
document.getElementById('json-editor')?.addEventListener('blur', function() {
    try {
        const parsed = JSON.parse(this.value);
        this.value = JSON.stringify(parsed, null, 4);
    } catch (e) {
        // Invalid JSON, leave as-is
    }
});
</script>
{% endblock %}

