{% extends "rest_framework/tailwind/base.html" %}
{% load rest_framework %}

{% block content %}
<div class="grid grid-cols-1 xl:grid-cols-3 gap-6">

    {# Main Content Column #}
    <div class="xl:col-span-2 space-y-6">

        {# Endpoint Info Card #}
        {% if description %}
        <div class="card p-6">
            <div class="flex items-start justify-between mb-4">
                <div class="flex-1">
                    <h1 class="text-2xl font-bold mb-2 text-gray-900 dark:text-white">
                        {{ name }}
                    </h1>
                    <div class="prose prose-gray dark:prose-invert max-w-none text-gray-700 dark:text-gray-300">
                        {{ description }}
                    </div>
                </div>

                {# Copy endpoint button #}
                <button @click="navigator.clipboard.writeText('{{ request.build_absolute_uri }}').then(() => showToast('URL copied!', 'success')).catch(() => showToast('Failed to copy', 'error'))"
                        class="btn-icon ml-4"
                        title="Copy URL">
                    <svg class="w-5 h-5 text-gray-600 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                    </svg>
                </button>
            </div>

            {# Endpoint URL with copy functionality #}
            <div class="mt-4 p-4 bg-gray-100 dark:bg-gray-900 rounded-lg">
                <div class="flex items-center justify-between">
                    <code class="text-sm font-mono flex-1 overflow-x-auto text-gray-900 dark:text-gray-100">{{ request.get_full_path }}</code>
                    <button @click="navigator.clipboard.writeText('{{ request.build_absolute_uri }}').then(() => showToast('Endpoint URL copied!', 'success')).catch(() => showToast('Failed to copy', 'error'))"
                            class="btn-icon ml-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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                        </svg>
                    </button>
                </div>
            </div>
        </div>
        {% endif %}

        {# Response Viewer with Tabs #}
        <div class="card overflow-hidden"
             x-data="{ activeTab: 'pretty', expanded: {}, copySuccess: false }">

            {# Tabs Header #}
            <div class="flex items-center justify-between border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
                <div class="flex">
                    <button @click="activeTab = 'pretty'"
                            :class="activeTab === 'pretty' ? 'bg-white dark:bg-gray-800 border-b-2 border-blue-600 text-blue-600 dark:text-blue-400' : 'text-gray-700 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'"
                            class="px-6 py-3 font-medium text-sm transition-all">
                        <div class="flex items-center space-x-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="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"/>
                            </svg>
                            <span>Response</span>
                        </div>
                    </button>

                    <button @click="activeTab = 'raw'"
                            :class="activeTab === 'raw' ? 'bg-white dark:bg-gray-800 border-b-2 border-blue-600 text-blue-600 dark:text-blue-400' : 'text-gray-700 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'"
                            class="px-6 py-3 font-medium text-sm transition-all">
                        <div class="flex items-center space-x-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="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/>
                            </svg>
                            <span>Raw</span>
                        </div>
                    </button>

                    {% if display_edit_forms %}
                    <button @click="activeTab = 'headers'"
                            :class="activeTab === 'headers' ? 'bg-white dark:bg-gray-800 border-b-2 border-blue-600 text-blue-600 dark:text-blue-400' : 'text-gray-700 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'"
                            class="px-6 py-3 font-medium text-sm transition-all">
                        <div class="flex items-center space-x-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 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                            </svg>
                            <span>Headers</span>
                        </div>
                    </button>
                    {% endif %}
                </div>

                {# Response Status Badge #}
                {% if response.status_code %}
                <div class="px-4 py-2">
                    <span class="badge
                               {% if response.status_code < 300 %}status-success
                               {% elif response.status_code < 400 %}status-info
                               {% elif response.status_code < 500 %}status-warning
                               {% else %}status-error{% endif %}">
                        {{ response.status_code }} {{ response.status_text }}
                    </span>
                </div>
                {% endif %}
            </div>

            {# Response Content #}
            <div class="p-6">
                {# Pretty JSON View #}
                <div x-show="activeTab === 'pretty'" class="space-y-4">
                    {% if content %}
                        <div class="relative"
                             x-data="{
                                 jsonData: null,
                                 init() {
                                     try {
                                         this.jsonData = JSON.parse(`{{ content|escapejs }}`);
                                     } catch(e) {
                                         console.error('Failed to parse JSON:', e);
                                     }
                                 }
                             }">
                            {# Toolbar #}
                            <div class="flex items-center justify-between mb-3">
                                <div class="flex items-center space-x-2">
                                    <button @click="$event.target.closest('[x-data]').querySelectorAll('.json-toggle').forEach(el => el.dataset.expanded = 'true'); $event.target.closest('[x-data]').querySelectorAll('.json-content').forEach(el => el.style.display = 'block')"
                                            class="px-3 py-1.5 text-xs rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 transition-all">
                                        Expand All
                                    </button>
                                    <button @click="$event.target.closest('[x-data]').querySelectorAll('.json-toggle').forEach(el => el.dataset.expanded = 'false'); $event.target.closest('[x-data]').querySelectorAll('.json-content').forEach(el => el.style.display = 'none')"
                                            class="px-3 py-1.5 text-xs rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 transition-all">
                                        Collapse All
                                    </button>
                                </div>

                                {# Copy button #}
                                <button @click="navigator.clipboard.writeText(JSON.stringify(jsonData, null, 2)).then(() => { copySuccess = true; showToast('JSON copied!', 'success'); setTimeout(() => copySuccess = false, 2000) }).catch(() => showToast('Failed to copy', 'error'))"
                                        class="px-3 py-1.5 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 text-sm font-medium transition-all">
                                    <div class="flex items-center space-x-1.5">
                                        <svg x-show="!copySuccess" 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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                                        </svg>
                                        <svg x-show="copySuccess" class="w-4 h-4 text-green-500" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
                                        </svg>
                                        <span x-text="copySuccess ? 'Copied!' : 'Copy'"></span>
                                    </div>
                                </button>
                            </div>

                            {# Interactive JSON Tree #}
                            <div class="bg-gray-50 dark:bg-gray-900 rounded-lg p-6 overflow-x-auto border border-gray-200 dark:border-gray-700 font-mono text-sm"
                                 x-html="renderJSON(jsonData, 0)">
                            </div>
                        </div>
                    {% else %}
                        <div class="text-center py-12 text-gray-500 dark:text-gray-400">
                            <svg class="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"/>
                            </svg>
                            <p class="font-medium">No response data</p>
                        </div>
                    {% endif %}
                </div>

                {# Raw View #}
                <div x-show="activeTab === 'raw'">
                    <pre class="bg-gray-50 dark:bg-gray-900 rounded-lg p-6 overflow-x-auto border border-gray-200 dark:border-gray-700 text-sm font-mono text-gray-800 dark:text-gray-300">{{ content }}</pre>
                </div>

                {# Headers View #}
                {% if display_edit_forms %}
                <div x-show="activeTab === 'headers'">
                    <div class="space-y-2">
                        {% for key, val in response.items %}
                        <div class="flex items-start border-b border-gray-200 dark:border-gray-700 pb-2">
                            <span class="font-mono text-sm text-blue-600 dark:text-blue-400 w-1/3">{{ key }}:</span>
                            <span class="font-mono text-sm text-gray-700 dark:text-gray-300 flex-1">{{ val }}</span>
                        </div>
                        {% endfor %}
                    </div>
                </div>
                {% endif %}
            </div>
        </div>

        {# Request Forms #}
        {% if display_edit_forms %}
        <div class="card overflow-hidden">
            <div class="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 px-6 py-4">
                <h2 class="text-lg font-bold flex items-center text-gray-900 dark:text-white">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
                    </svg>
                    Make a Request
                </h2>
            </div>

            <div class="p-6">
                {# Request method tabs #}
                <div x-data="{ method: '{{ request.method|default:'GET' }}' }" class="space-y-6">

                    {# Method selector #}
                    <div class="flex flex-wrap gap-2">
                        {% for method in allowed_methods %}
                            {% if method != "OPTIONS" %}
                            <button @click="method = '{{ method }}'"
                                    :class="method === '{{ method }}' ? 'ring-2 ring-offset-1' : 'opacity-60'"
                                    class="badge px-4 py-2
                                           {% if method == 'GET' %}badge-get ring-blue-500
                                           {% elif method == 'POST' %}badge-post ring-green-500
                                           {% elif method == 'PUT' %}badge-put ring-orange-500
                                           {% elif method == 'PATCH' %}badge-patch ring-purple-500
                                           {% elif method == 'DELETE' %}badge-delete ring-red-500
                                           {% else %}bg-gray-500 text-white ring-gray-500{% endif %}">
                                {{ method }}
                            </button>
                            {% endif %}
                        {% endfor %}
                    </div>

                    {# Forms for each method #}
                    {% for method in allowed_methods %}
                        {% if method != "OPTIONS" %}
                        <div x-show="method === '{{ method }}'" x-transition>
                            {% with form=raw_data_put_or_patch_form %}
                                {% if method == "PUT" or method == "PATCH" %}
                                    {% include "rest_framework/tailwind/forms/raw_data_form.html" %}
                                {% endif %}
                            {% endwith %}

                            {% with form=raw_data_post_form %}
                                {% if method == "POST" %}
                                    {% include "rest_framework/tailwind/forms/raw_data_form.html" %}
                                {% endif %}
                            {% endwith %}

                            {% if method == "DELETE" %}
                                <form method="POST" action="{{ request.get_full_path }}" class="space-y-4">
                                    {% csrf_token %}
                                    <input type="hidden" name="_method" value="DELETE">
                                    <div class="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
                                        <p class="text-red-800 dark:text-red-300 font-medium mb-4">
                                            Are you sure you want to delete this resource?
                                        </p>
                                        <button type="submit"
                                                class="px-6 py-2.5 bg-red-600 hover:bg-red-700 text-white rounded-lg font-medium transition-all shadow-sm hover:shadow-md">
                                            Confirm Delete
                                        </button>
                                    </div>
                                </form>
                            {% endif %}

                            {% if method == "GET" %}
                                <div class="p-4 bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg">
                                    <p class="text-gray-700 dark:text-gray-300">
                                        Use the filters sidebar or query parameters to customize your GET request.
                                    </p>
                                </div>
                            {% endif %}
                        </div>
                        {% endif %}
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}

        {# Pagination #}
        {% if paginator %}
        <div class="flex items-center justify-between card p-4">
            <div class="text-sm text-gray-600 dark:text-gray-400">
                Showing {{ paginator.start_index }} - {{ paginator.end_index }} of {{ paginator.count }} results
            </div>

            <div class="flex items-center space-x-2">
                {% if page.has_previous %}
                    <a href="?page={{ page.previous_page_number }}"
                       class="px-4 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600">
                        Previous
                    </a>
                {% endif %}

                <span class="px-4 py-2 bg-blue-600 text-white rounded-lg font-medium">
                    {{ page.number }}
                </span>

                {% if page.has_next %}
                    <a href="?page={{ page.next_page_number }}"
                       class="px-4 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600">
                        Next
                    </a>
                {% endif %}
            </div>
        </div>
        {% endif %}

    </div>

    {# Sidebar with Info & Filters #}
    <div class="xl:col-span-1 space-y-6">

        {# API Info Card #}
        <div class="card p-6 sticky top-24">
            <h3 class="text-lg font-bold mb-4 flex items-center text-gray-900 dark:text-white">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                API Info
            </h3>

            <div class="space-y-3 text-sm">
                {# Allowed methods #}
                <div>
                    <span class="text-gray-500 dark:text-gray-400 font-medium block mb-2">Allowed Methods</span>
                    <div class="flex flex-wrap gap-2">
                        {% for method in allowed_methods %}
                        <span class="badge px-2 py-0.5 text-xs
                                   {% if method == 'GET' %}badge-get
                                   {% elif method == 'POST' %}badge-post
                                   {% elif method == 'PUT' %}badge-put
                                   {% elif method == 'PATCH' %}badge-patch
                                   {% elif method == 'DELETE' %}badge-delete
                                   {% else %}bg-gradient-to-r from-gray-500 to-gray-600 text-white{% endif %}">
                            {{ method }}
                        </span>
                        {% endfor %}
                    </div>
                </div>

                {# Content type #}
                {% if available_formats %}
                <div>
                    <span class="text-gray-500 dark:text-gray-400 font-medium block mb-2">Response Formats</span>
                    <div class="flex flex-wrap gap-1.5">
                        {% for format in available_formats %}
                        <a href="{% add_query_param request api_settings.URL_FORMAT_OVERRIDE format %}"
                           class="px-2 py-1 rounded text-xs font-mono bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600">
                            {{ format }}
                        </a>
                        {% endfor %}
                    </div>
                </div>
                {% endif %}

                {# Version info if available #}
                {% if api_version %}
                <div>
                    <span class="text-gray-500 dark:text-gray-400 font-medium">API Version</span>
                    <p class="font-mono text-blue-600 dark:text-blue-400">{{ api_version }}</p>
                </div>
                {% endif %}
            </div>
        </div>

        {# Filters #}
        {% if filter_form %}
        <div class="card overflow-hidden">
            <div class="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 px-6 py-4">
                <h3 class="text-lg font-bold flex items-center text-gray-900 dark:text-white">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"/>
                    </svg>
                    Filters
                </h3>
            </div>

            <div class="p-6">
                {% include "rest_framework/tailwind/forms/filter_form.html" %}
            </div>
        </div>
        {% endif %}

    </div>
</div>

{% endblock %}
