{% extends 'admin/layout.twig' %}
{% block title %}#{{ ticket.number }} — {{ ticket.subject }}{% endblock %}
{% block content %}
    <div class="admin-page-head">
        <p class="breadcrumbs"><a href="{{ app_url('/admin/tickets') }}">Tickets</a> / {{ ticket.number }}</p>
        <h1>{{ ticket.subject }}</h1>
        <p class="muted">
            Opened by {{ ticket.customer_name ?: ticket.customer_email }} ({{ ticket.customer_email }}) · {{ ticket.created_at|time_ago }}
        </p>
        {% if ticket_tags %}
            <p class="ticket-tags">
                {% for t in ticket_tags %}
                    <span class="tag-chip" style="background: {{ t.color }};">{{ t.name }}</span>
                {% endfor %}
            </p>
        {% endif %}
    </div>

    <div class="ticket-grid">
        <div class="ticket-main">
            <div class="ticket-thread">
                {% for entry in timeline %}
                    {% if entry._kind == 'reply' %}
                        <article class="reply {{ entry.is_internal ? 'reply-internal' : (entry.user_role in ['admin','agent'] ? 'reply-staff' : 'reply-customer') }}">
                            <header class="reply-head">
                                <strong>{{ entry.user_name ?: entry.from_name ?: entry.from_email }}</strong>
                                <span class="muted small">&lt;{{ entry.user_email ?: entry.from_email }}&gt;</span>
                                <span class="muted small">{{ entry.created_at }}</span>
                                {% if entry.source == 'email' %}<span class="badge">via email</span>{% endif %}
                                {% if entry.is_internal %}<span class="badge badge-warning">Internal note</span>{% endif %}
                            </header>
                            <div class="reply-body prose">{{ entry.body_html|md }}</div>
                            {% if entry.attachments %}
                                <div class="attachments">
                                    {% for a in entry.attachments %}
                                        <a class="attachment" href="{{ app_url(a.path) }}" target="_blank" rel="noopener">📎 {{ a.original_name }} <span class="muted small">({{ a.size|bytes }})</span></a>
                                    {% endfor %}
                                </div>
                            {% endif %}
                        </article>
                    {% else %}
                        <div class="activity-entry">
                            <span class="activity-dot"></span>
                            <span class="activity-text">{{ entry._text|raw }}</span>
                            <span class="muted small">{{ entry.created_at|time_ago }}</span>
                        </div>
                    {% endif %}
                {% endfor %}
            </div>

            <h2 class="section-title">Reply</h2>
            <form method="post" action="{{ app_url('/admin/tickets/' ~ ticket.id ~ '/reply') }}" enctype="multipart/form-data" class="form">
                {{ csrf_field()|raw }}
                {% if saved_replies %}
                    <div class="form-row inline">
                        <label class="muted small">Insert saved reply:</label>
                        <select id="saved-reply-picker">
                            <option value="">— Choose —</option>
                            {% for r in saved_replies %}
                                <option value="{{ r.id }}" data-content="{{ r.content|e('html_attr') }}">
                                    {{ r.name }}{% if r.is_global %} (global){% endif %}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                {% endif %}
                <div class="form-row">
                    <textarea name="body" id="reply-body" rows="10" required></textarea>
                </div>
                <div class="form-row inline">
                    <label class="checkbox"><input type="checkbox" name="is_internal" value="1"> Internal note (not sent to customer)</label>
                </div>
                <div class="form-row">
                    <input type="file" name="attachments[]" multiple>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">Send reply</button>
                </div>
            </form>
        </div>

        <aside class="ticket-side">
            <form method="post" action="{{ app_url('/admin/tickets/' ~ ticket.id ~ '/update') }}" class="form card">
                {{ csrf_field()|raw }}
                <h3>Properties</h3>

                <div class="form-row">
                    <label>Status</label>
                    <select name="status">
                        {% for s in statuses %}
                            <option value="{{ s }}" {{ ticket.status == s ? 'selected' : '' }}>{{ s }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="form-row">
                    <label>Priority</label>
                    <select name="priority">
                        {% for p in priorities %}
                            <option value="{{ p }}" {{ ticket.priority == p ? 'selected' : '' }}>{{ p }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="form-row">
                    <label>Assigned</label>
                    <select name="assigned_to">
                        <option value="">Unassigned</option>
                        {% for a in agents %}
                            <option value="{{ a.id }}" {{ ticket.assigned_to == a.id ? 'selected' : '' }}>{{ a.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="form-row">
                    <label>Department</label>
                    <select name="department_id">
                        <option value="">—</option>
                        {% for d in departments %}
                            <option value="{{ d.id }}" {{ ticket.department_id == d.id ? 'selected' : '' }}>{{ d.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="form-row">
                    <label>Subject</label>
                    <input type="text" name="subject" value="{{ ticket.subject }}">
                </div>
                {% if tags %}
                <div class="form-row">
                    <label>Tags</label>
                    {% set ticket_tag_ids = ticket_tags|map(t => t.id) %}
                    {% for t in tags %}
                        <label class="checkbox" style="font-size: 13px;">
                            <input type="checkbox" name="tag_ids[]" value="{{ t.id }}" {{ t.id in ticket_tag_ids ? 'checked' : '' }}>
                            <span class="tag-chip" style="background: {{ t.color }};">{{ t.name }}</span>
                        </label>
                    {% endfor %}
                </div>
                {% endif %}
                <button type="submit" class="btn btn-primary block">Save</button>
            </form>

            <div class="card">
                <h3>Customer</h3>
                <p><strong>{{ ticket.customer_name ?: '—' }}</strong></p>
                <p class="muted small">{{ ticket.customer_email }}</p>
                <p class="muted small">Source: {{ ticket.source }}</p>
            </div>

            {% if current_user().role == 'admin' %}
            <form method="post" action="{{ app_url('/admin/tickets/' ~ ticket.id ~ '/delete') }}" onsubmit="return confirm('Delete this ticket and all replies?');" class="card">
                {{ csrf_field()|raw }}
                <button type="submit" class="btn btn-danger block">Delete ticket</button>
            </form>
            {% endif %}
        </aside>
    </div>
{% endblock %}
{% block scripts %}
    {% include 'partials/tinymce.twig' with {selector: '#reply-body', allow_images: true} %}
    <script>
        // Wire saved-replies dropdown to insert into TinyMCE
        document.addEventListener('DOMContentLoaded', () => {
            const picker = document.getElementById('saved-reply-picker');
            if (!picker) return;
            picker.addEventListener('change', (e) => {
                const opt = picker.options[picker.selectedIndex];
                const content = opt.dataset.content;
                if (!content) return;
                if (window.tinymce && window.tinymce.activeEditor) {
                    window.tinymce.activeEditor.execCommand('mceInsertContent', false, content);
                } else {
                    const ta = document.getElementById('reply-body');
                    ta.value = (ta.value || '') + content;
                }
                picker.value = '';
            });
        });
    </script>
{% endblock %}
