{% extends 'layouts/base.html' %}
{% load i18n static %}

{% block title %}{{ template.name }} — PX360{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js">
<style>
    .builder-layout {
        display: grid;
        grid-template-columns: 280px 1fr 360px;
        gap: 0;
        height: calc(100vh - 64px);
        overflow: hidden;
    }
    .builder-sidebar {
        background: #f8fafc;
        border-right: 1px solid #e2e8f0;
        overflow-y: auto;
        padding: 16px;
    }
    .builder-main {
        overflow-y: auto;
        padding: 24px;
        background: white;
    }
    .builder-editor {
        background: #f8fafc;
        border-left: 1px solid #e2e8f0;
        overflow-y: auto;
        padding: 20px;
    }
    .slide-list-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px 12px;
        border: 2px solid transparent;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.15s;
        margin-bottom: 4px;
        background: white;
    }
    .slide-list-item:hover { border-color: #cbd5e1; }
    .slide-list-item.active { border-color: #005696; background: rgba(0,86,150,0.05); }
    .slide-list-item .drag-handle {
        cursor: grab;
        color: #94a3b8;
        font-size: 16px;
    }
    .slide-list-item .slide-order {
        width: 24px;
        height: 24px;
        border-radius: 6px;
        background: #e2e8f0;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 11px;
        font-weight: 700;
        color: #64748b;
        flex-shrink: 0;
    }
    .slide-list-item.active .slide-order {
        background: #005696;
        color: white;
    }
    .slide-list-item .slide-info {
        flex: 1;
        min-width: 0;
    }
    .slide-list-item .slide-info-title {
        font-size: 13px;
        font-weight: 600;
        color: #1e293b;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .slide-list-item .slide-info-layout {
        font-size: 11px;
        color: #94a3b8;
    }
    .layout-badge {
        display: inline-flex;
        align-items: center;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 600;
    }
    .layout-badge--cover { background: #dbeafe; color: #1d4ed8; }
    .layout-badge--section_divider { background: #ede9fe; color: #7c3aed; }
    .layout-badge--kpi_dashboard { background: #dcfce7; color: #16a34a; }
    .layout-badge--data_table { background: #fef3c7; color: #d97706; }
    .layout-badge--chart_metrics { background: #cffafe; color: #0891b2; }
    .layout-badge--full_chart { background: #cffafe; color: #0891b2; }
    .layout-badge--two_column { background: #fce7f3; color: #db2777; }
    .layout-badge--quote { background: #fef9c3; color: #a16207; }
    .layout-badge--team_grid { background: #e0e7ff; color: #4f46e5; }
    .layout-badge--closing { background: #f1f5f9; color: #475569; }
    .repeat-badge {
        display: inline-flex;
        align-items: center;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 10px;
        font-weight: 700;
        background: #fef3c7;
        color: #92400e;
        margin-left: 4px;
    }
    .editor-group { margin-bottom: 16px; }
    .editor-group label {
        display: block;
        font-size: 12px;
        font-weight: 600;
        color: #475569;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }
    .editor-group input, .editor-group select, .editor-group textarea {
        width: 100%;
        border: 1px solid #e2e8f0;
        border-radius: 6px;
        padding: 8px 10px;
        font-size: 13px;
    }
    .editor-group textarea { resize: vertical; min-height: 60px; font-family: monospace; font-size: 12px; }
    .btn-sm {
        padding: 6px 14px;
        border-radius: 6px;
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.15s;
    }
    .hh-btn-primary { background: #005696; color: white; border: none; }
    .hh-btn-primary:hover { background: #004477; }
    .btn-danger { background: #fee2e2; color: #dc2626; border: 1px solid #fecaca; }
    .btn-danger:hover { background: #fecaca; }
    .btn-outline { background: white; color: #475569; border: 1px solid #e2e8f0; }
    .btn-outline:hover { background: #f8fafc; border-color: #cbd5e1; }
    .preview-card {
        background: #f1f5f9;
        border-radius: 12px;
        padding: 40px 24px;
        text-align: center;
        color: #94a3b8;
        min-height: 200px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    .top-bar {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 24px;
        background: white;
        border-bottom: 1px solid #e2e8f0;
    }
</style>
{% endblock %}

{% block content %}
<div class="top-bar">
    <div class="flex items-center gap-3">
        <a href="{% url 'presentations:template_list' %}" class="text-gray-400 hover:text-gray-600">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
        </a>
        <h1 class="text-lg font-bold text-gray-800">{{ template.name }}</h1>
        <span class="layout-badge layout-badge--{{ template.data_source }}">{{ data_source_info.label|default:template.data_source }}</span>
        {% if not template.active %}<span class="text-xs text-red-500 font-bold">INACTIVE</span>{% endif %}
    </div>
    <div class="flex items-center gap-3">
        {% if template.reference_pdf %}
        <button onclick="triggerParse()" class="btn-sm btn-outline">Re-parse PDF</button>
        {% endif %}
        <a href="{% url 'presentations:template_generate' template.pk %}" class="btn-sm btn-primary inline-flex items-center gap-2">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
            Generate Report
        </a>
        <form method="post" action="{% url 'presentations:template_delete' template.pk %}" onsubmit="return confirm('Delete this template?')">
            {% csrf_token %}
            <button type="submit" class="btn-sm btn-danger">Delete</button>
        </form>
    </div>
</div>

<div class="builder-layout">
    <div class="builder-sidebar">
        <div class="flex items-center justify-between mb-3">
            <span class="text-sm font-semibold text-gray-600">{{ template_slides|length }} Slides</span>
            <button onclick="addSlide()" class="btn-sm btn-primary text-xs" style="padding:4px 10px;">+ Add</button>
        </div>
        <div id="slide-list">
            {% for ts in template_slides %}
            <div class="slide-list-item" data-id="{{ ts.id }}" onclick="selectSlide('{{ ts.id }}')">
                <span class="drag-handle">&#8942;&#8942;</span>
                <span class="slide-order">{{ ts.order }}</span>
                <div class="slide-info">
                    <div class="slide-info-title">{{ ts.title_template|default:ts.get_layout_display }}</div>
                    <div class="slide-info-layout">
                        <span class="layout-badge layout-badge--{{ ts.layout }}">{{ ts.get_layout_display }}</span>
                        {% if ts.repeat_source %}<span class="repeat-badge">REPEAT: {{ ts.repeat_source }}</span>{% endif %}
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

    <div class="builder-main">
        <div id="slide-preview" class="preview-card">
            <svg class="w-12 h-12 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6z"/></svg>
            <p>Select a slide to edit</p>
        </div>
    </div>

    <div class="builder-editor">
        <div id="slide-editor">
            <p class="text-sm text-gray-400 text-center py-12">Select a slide from the list to edit its properties</p>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
const CSRF = '{{ csrf_token }}';
const templatePk = '{{ template.pk }}';
const layoutChoices = [
    {% for val, label in layout_choices %}['{{ val }}', '{{ label }}'],{% endfor %}
];
const slidesData = {};

{% for ts in template_slides %}
slidesData['{{ ts.id }}'] = {
    id: '{{ ts.id }}',
    order: {{ ts.order }},
    layout: '{{ ts.layout }}',
    section_label: '{{ ts.section_label|escapejs }}',
    title_template: '{{ ts.title_template|escapejs }}',
    subtitle_template: '{{ ts.subtitle_template|escapejs }}',
    content_mapping: {{ ts.content_mapping|default:"{}"|safe }},
    repeat_source: '{{ ts.repeat_source|escapejs }}',
    repeat_title_key: '{{ ts.repeat_title_key|escapejs }}',
    repeat_subtitle_template: '{{ ts.repeat_subtitle_template|escapejs }}',
    max_rows: {{ ts.max_rows }},
    style_overrides: {{ ts.style_overrides|default:"{}"|safe }},
    speaker_notes_template: '{{ ts.speaker_notes_template|escapejs }}',
};
{% endfor %}

let activeSlideId = null;

new Sortable(document.getElementById('slide-list'), {
    animation: 200,
    handle: '.drag-handle',
    onEnd: function(evt) {
        const items = document.querySelectorAll('.slide-list-item');
        const order = [];
        items.forEach((el, i) => {
            el.querySelector('.slide-order').textContent = i + 1;
            order.push({ id: el.dataset.id, order: i + 1 });
        });
        fetch('{% url "presentations:template_slide_reorder" template.pk %}', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRFToken': CSRF },
            body: JSON.stringify({ order }),
        });
    },
});

function selectSlide(id) {
    activeSlideId = id;
    document.querySelectorAll('.slide-list-item').forEach(el => el.classList.remove('active'));
    document.querySelector(`.slide-list-item[data-id="${id}"]`).classList.add('active');
    renderEditor(id);
    renderPreview(id);
}

function renderEditor(id) {
    const s = slidesData[id];
    if (!s) return;
    const layoutOptions = layoutChoices.map(([val, label]) =>
        `<option value="${val}" ${val === s.layout ? 'selected' : ''}>${label}</option>`
    ).join('');

    document.getElementById('slide-editor').innerHTML = `
        <form id="slide-form" onsubmit="saveSlide(event)">
            <div class="editor-group">
                <label>Layout</label>
                <select name="layout">${layoutOptions}</select>
            </div>
            <div class="editor-group">
                <label>Section Label</label>
                <input name="section_label" value="${esc(s.section_label)}" placeholder="e.g. 01">
            </div>
            <div class="editor-group">
                <label>Title Template</label>
                <input name="title_template" value="${esc(s.title_template)}" placeholder="{{ variable }} supported">
            </div>
            <div class="editor-group">
                <label>Subtitle Template</label>
                <input name="subtitle_template" value="${esc(s.subtitle_template)}" placeholder="{{ variable }} supported">
            </div>
            <div class="editor-group">
                <label>Content Mapping (JSON)</label>
                <textarea name="content_mapping" rows="8">${esc(JSON.stringify(s.content_mapping, null, 2))}</textarea>
            </div>
            <div class="editor-group">
                <label>Repeat Source</label>
                <input name="repeat_source" value="${esc(s.repeat_source)}" placeholder="e.g. by_department (empty = no repeat)">
            </div>
            <div class="editor-group">
                <label>Repeat Title Key</label>
                <input name="repeat_title_key" value="${esc(s.repeat_title_key)}" placeholder="e.g. department_name">
            </div>
            <div class="editor-group">
                <label>Repeat Subtitle Template</label>
                <input name="repeat_subtitle_template" value="${esc(s.repeat_subtitle_template)}" placeholder="{{ manager }} | {{ item_count }} physicians">
            </div>
            <div class="editor-group">
                <label>Max Rows Per Slide</label>
                <input name="max_rows" type="number" value="${s.max_rows}" min="1" max="30">
            </div>
            <div class="editor-group">
                <label>Style Overrides (JSON)</label>
                <textarea name="style_overrides" rows="4">${esc(JSON.stringify(s.style_overrides, null, 2))}</textarea>
            </div>
            <div class="editor-group">
                <label>Speaker Notes Template</label>
                <textarea name="speaker_notes_template" rows="3">${esc(s.speaker_notes_template)}</textarea>
            </div>
            <div class="flex gap-2 mt-4">
                <button type="submit" class="btn-sm btn-primary flex-1">Save Slide</button>
                <button type="button" onclick="deleteSlide('${id}')" class="btn-sm btn-danger">Delete</button>
            </div>
        </form>
    `;
}

function renderPreview(id) {
    const s = slidesData[id];
    if (!s) return;
    document.getElementById('slide-preview').innerHTML = `
        <div style="text-align:left; width:100%; max-width:500px;">
            <div style="font-size:11px; color:#94a3b8; margin-bottom:8px;">${s.get_layout_display || s.layout}</div>
            <div style="font-size:20px; font-weight:700; color:#1e293b; margin-bottom:8px;">${s.title_template || '(no title)'}</div>
            <div style="font-size:14px; color:#64748b; margin-bottom:16px;">${s.subtitle_template || ''}</div>
            ${s.repeat_source ? `<div style="font-size:12px; color:#d97706; font-weight:600;">REPEAT: ${s.repeat_source}</div>` : ''}
            <pre style="font-size:10px; color:#94a3b8; background:#f1f5f9; padding:12px; border-radius:8px; max-height:300px; overflow:auto;">${esc(JSON.stringify(s.content_mapping, null, 2))}</pre>
        </div>
    `;
}

async function saveSlide(e) {
    e.preventDefault();
    if (!activeSlideId) return;
    const form = document.getElementById('slide-form');
    const fd = new FormData(form);

    try {
        const cm = fd.get('content_mapping');
        const so = fd.get('style_overrides');
        JSON.parse(cm);
        JSON.parse(so);
    } catch (err) {
        alert('Invalid JSON: ' + err.message);
        return;
    }

    const resp = await fetch(`/presentations/templates/${templatePk}/slides/${activeSlideId}/update/`, {
        method: 'POST',
        headers: { 'X-CSRFToken': CSRF },
        body: fd,
    });
    if (resp.ok) {
        const s = slidesData[activeSlideId];
        s.layout = fd.get('layout');
        s.title_template = fd.get('title_template');
        s.subtitle_template = fd.get('subtitle_template');
        s.content_mapping = JSON.parse(fd.get('content_mapping'));
        s.repeat_source = fd.get('repeat_source');
        s.max_rows = parseInt(fd.get('max_rows'));
        renderPreview(activeSlideId);
        const item = document.querySelector(`.slide-list-item[data-id="${activeSlideId}"] .slide-info-title`);
        if (item) item.textContent = s.title_template || s.layout;
        alert('Saved!');
    } else {
        alert('Error saving slide');
    }
}

async function deleteSlide(id) {
    if (!confirm('Delete this slide?')) return;
    const resp = await fetch(`/presentations/templates/${templatePk}/slides/${id}/delete/`, {
        method: 'POST',
        headers: { 'X-CSRFToken': CSRF },
    });
    if (resp.ok) {
        document.querySelector(`.slide-list-item[data-id="${id}"]`).remove();
        if (activeSlideId === id) {
            activeSlideId = null;
            document.getElementById('slide-editor').innerHTML = '<p class="text-sm text-gray-400 text-center py-12">Select a slide from the list to edit its properties</p>';
            document.getElementById('slide-preview').innerHTML = '<p>Select a slide to preview</p>';
        }
        delete slidesData[id];
    }
}

async function addSlide() {
    const fd = new FormData();
    fd.append('layout', 'cover');
    fd.append('title_template', '');
    fd.append('content_mapping', '{}');
    fd.append('max_rows', '18');
    fd.append('repeat_source', '');

    const resp = await fetch(`/presentations/templates/${templatePk}/slides/create/`, {
        method: 'POST',
        headers: { 'X-CSRFToken': CSRF, 'X-Requested-With': 'XMLHttpRequest' },
        body: fd,
    });
    if (resp.ok) {
        const data = await resp.json();
        location.reload();
    }
}

async function triggerParse() {
    if (!confirm('Re-parse the reference PDF? This will replace all current slides.')) return;
    const resp = await fetch(`/presentations/templates/${templatePk}/parse/`, {
        method: 'POST',
        headers: { 'X-CSRFToken': CSRF },
    });
    const data = await resp.json();
    if (data.status === 'ok') {
        alert(data.message);
        location.reload();
    } else {
        alert('Error: ' + data.message);
    }
}

function esc(str) {
    if (str === null || str === undefined) return '';
    const d = document.createElement('div');
    d.textContent = String(str);
    return d.innerHTML;
}
</script>
{% endblock %}
