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

{% block title %}Widgets - Focomy{% endblock %}

{% block header_title %}Widgets{% endblock %}

{% block content %}
<div class="card">
    <div class="card-header">
        <div class="flex items-center gap-2">
            <h2 class="card-title">Widget Editor</h2>
            <div class="area-tabs">
                {% for a in areas %}
                <a href="/admin/widgets?area={{ a.value }}"
                   class="btn {% if current_area == a.value %}btn-primary{% else %}btn-secondary{% endif %}">
                    {{ a.label }}
                </a>
                {% endfor %}
            </div>
        </div>
        <button type="button" class="btn btn-primary" onclick="showAddModal()">
            Add Widget
        </button>
    </div>

    {% if widgets %}
    <div class="widget-list" id="widget-list">
        {% for widget in widgets %}
        <div class="widget-item" data-id="{{ widget.id }}">
            <span class="drag-handle">&#9776;</span>
            <div class="widget-info">
                <span class="widget-title">{{ widget.title or "(No title)" }}</span>
                <span class="widget-type badge badge-info">{{ widget.widget_type }}</span>
                {% if not widget.is_active %}
                <span class="badge badge-warning">Inactive</span>
                {% endif %}
            </div>
            <div class="widget-actions">
                <button type="button" class="btn btn-secondary btn-sm" onclick="editWidget('{{ widget.id }}')">Edit</button>
                <button type="button" class="btn btn-danger btn-sm"
                        hx-delete="/admin/widgets/{{ widget.id }}"
                        hx-confirm="Delete this widget?"
                        hx-target="closest .widget-item"
                        hx-swap="outerHTML">Delete</button>
            </div>
        </div>
        {% endfor %}
    </div>
    {% else %}
    <div class="empty-state">
        <p class="text-muted">No widgets in this area.</p>
        <p class="text-muted mt-1">Click "Add Widget" to create one.</p>
    </div>
    {% endif %}
</div>

<!-- Add/Edit Modal -->
<div id="widget-modal" class="modal" style="display: none;">
    <div class="modal-overlay" onclick="hideModal()"></div>
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modal-title">Add Widget</h3>
            <button type="button" class="modal-close" onclick="hideModal()">&times;</button>
        </div>
        <form id="widget-form" method="POST" action="/admin/widgets">
            <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
            <input type="hidden" name="area" value="{{ current_area }}">
            <input type="hidden" id="widget-id" name="widget_id" value="">

            <div class="form-group">
                <label class="form-label" for="title">Title (optional)</label>
                <input type="text" id="title" name="title" class="form-input">
            </div>

            <div class="form-group">
                <label class="form-label" for="widget_type">Widget Type</label>
                <select id="widget_type" name="widget_type" class="form-select" onchange="toggleCustomHtml()">
                    {% for wt in widget_types %}
                    <option value="{{ wt.value }}">{{ wt.label }}</option>
                    {% endfor %}
                </select>
            </div>

            <div class="form-group" id="custom-html-group" style="display: none;">
                <label class="form-label" for="custom_html">Custom HTML</label>
                <textarea id="custom_html" name="custom_html" class="form-textarea" rows="6"></textarea>
            </div>

            <div class="form-group">
                <label class="form-label">
                    <input type="checkbox" id="is_active" name="is_active" value="true" checked>
                    Active
                </label>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="hideModal()">Cancel</button>
                <button type="submit" class="btn btn-primary">Save</button>
            </div>
        </form>
    </div>
</div>

<style>
.area-tabs {
    display: flex;
    gap: 0.5rem;
}

.widget-list {
    padding: 1rem;
}

.widget-item {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem;
    background: var(--bg);
    border-radius: 0.375rem;
    border: 1px solid var(--border);
    margin-bottom: 0.5rem;
}

.widget-item.sortable-ghost {
    opacity: 0.4;
}

.drag-handle {
    cursor: grab;
    color: var(--text-muted);
}

.widget-info {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.widget-title {
    font-weight: 500;
}

.widget-type {
    font-size: 0.75rem;
}

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

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

.empty-state {
    padding: 3rem;
    text-align: center;
}

/* Modal */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: center;
}

.modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
}

.modal-content {
    position: relative;
    background: var(--card);
    border-radius: 0.5rem;
    width: 100%;
    max-width: 500px;
    max-height: 90vh;
    overflow-y: auto;
}

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

.modal-header h3 {
    margin: 0;
}

.modal-close {
    background: none;
    border: none;
    font-size: 1.5rem;
    cursor: pointer;
    color: var(--text-muted);
}

#widget-form {
    padding: 1.5rem;
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 0.75rem;
    padding-top: 1rem;
    border-top: 1px solid var(--border);
    margin-top: 1rem;
}
</style>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
const widgetsData = {{ widgets | tojson | safe }};

document.addEventListener('DOMContentLoaded', function() {
    const list = document.getElementById('widget-list');
    if (list) {
        new Sortable(list, {
            animation: 150,
            handle: '.drag-handle',
            ghostClass: 'sortable-ghost',
            onEnd: function() {
                saveOrder();
            }
        });
    }
});

function saveOrder() {
    const items = [];
    let order = 0;
    document.querySelectorAll('.widget-item').forEach(item => {
        items.push({
            id: item.dataset.id,
            sort_order: order++
        });
    });

    fetch('/admin/widgets/reorder', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': '{{ csrf_token }}'
        },
        body: JSON.stringify({
            area: '{{ current_area }}',
            items: items
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'ok') {
            Toast.success('Widget order saved');
        }
    });
}

function showAddModal() {
    document.getElementById('modal-title').textContent = 'Add Widget';
    document.getElementById('widget-form').action = '/admin/widgets';
    document.getElementById('widget-form').reset();
    document.getElementById('widget-id').value = '';
    document.getElementById('is_active').checked = true;
    toggleCustomHtml();
    document.getElementById('widget-modal').style.display = 'flex';
}

function editWidget(widgetId) {
    const widget = widgetsData.find(w => w.id === widgetId);
    if (!widget) return;

    document.getElementById('modal-title').textContent = 'Edit Widget';
    document.getElementById('widget-form').action = '/admin/widgets/' + widgetId;
    document.getElementById('widget-id').value = widgetId;
    document.getElementById('title').value = widget.title || '';
    document.getElementById('widget_type').value = widget.widget_type || 'custom_html';
    document.getElementById('custom_html').value = widget.custom_html || '';
    document.getElementById('is_active').checked = widget.is_active !== false;
    toggleCustomHtml();
    document.getElementById('widget-modal').style.display = 'flex';
}

function hideModal() {
    document.getElementById('widget-modal').style.display = 'none';
}

function toggleCustomHtml() {
    const type = document.getElementById('widget_type').value;
    const group = document.getElementById('custom-html-group');
    group.style.display = type === 'custom_html' ? 'block' : 'none';
}

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        hideModal();
    }
});
</script>
{% endblock %}
