{% extends 'base.html' %}
{% load i18n %}
{% load markdown_extras %}
{% load static %}

{% block extra_head %}
<style>
    [x-cloak] { display: none !important; }
</style>
{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <!-- Back Button -->
    <div class="mb-6">
        <a href="{% url 'page-list' %}"
           class="inline-flex items-center p-2 text-gray-600 hover:text-gray-800 hover:bg-gray-50 rounded-md"
           title="{% trans 'Back to List' %}">
            <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="M10 19l-7-7m0 0l7-7m-7 7h18"/>
            </svg>
            <span class="ml-1 text-sm">{% trans "Back to List" %}</span>
        </a>
    </div>

    <div class="bg-white shadow-sm rounded-lg overflow-hidden">
        <div class="px-4 py-5 sm:p-6">
            <!-- Header with actions -->
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-3xl font-bold text-gray-900">{{ page.title|default:"Untitled" }}</h1>
                <div class="flex space-x-2">
                    <a href="{% url 'page-update' page.pk %}"
                       class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <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>
                        {% trans "Edit" %}
                    </a>
                    <a href="{{ page.url }}"
                       target="_blank"
                       rel="noopener noreferrer"
                       class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-500 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                        <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="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"/>
                        </svg>
                        {% trans "Visit URL" %}
                    </a>
                    <button type="button"
                            onclick="deletePage({{ page.id }})"
                            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                        <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                        </svg>
                        {% trans "Delete" %}
                    </button>
                </div>
            </div>
            <!-- Page Status -->
            <div class="mb-6 flex items-center">
                <span class="text-sm font-medium text-gray-500 mr-2">{% trans "Status" %}:</span>
                {% if page.process_status == 'completed' %}
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                        {% trans "Completed" %}
                    </span>
                {% elif page.process_status == 'processing' %}
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                        {% trans "Processing" %}
                    </span>
                {% elif page.process_status == 'failed' %}
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                        {% trans "Failed" %}
                    </span>
                {% else %}
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                        {% trans "Pending" %}
                    </span>
                {% endif %}
                {% if page.retry_count > 0 %}
                    <span class="ml-2 text-sm text-gray-500">
                        ({% trans "Retries" %}: {{ page.retry_count }}/3)
                    </span>
                {% endif %}
            </div>

            <!-- URL -->
            <div class="mb-6">
                <h2 class="text-sm font-medium text-gray-500 mb-1">{% trans "URL" %}</h2>
                <a href="{{ page.url }}" target="_blank" rel="noopener noreferrer"
                class="text-blue-600 hover:text-blue-800 break-all">
                    {{ page.url }}
                </a>
            </div>

            <!-- Tags -->
            <div class="mb-6">
                <div class="flex items-center justify-between mb-2">
                    <h2 class="text-sm font-medium text-gray-500">{% trans "Tags" %}</h2>
                </div>
                <div class="flex flex-wrap gap-2">
                    {% for tag in page.tags.all %}
                    <a href="{% url 'tag-detail' tag.slug %}" class="tag-card inline-flex items-center px-3 py-1 rounded-full text-sm font-medium transition-colors duration-200">
                        {{ tag.name }}
                    </a>
                    {% empty %}
                    <span class="text-sm text-gray-500">{% trans "No tags" %}</span>
                    {% endfor %}
                </div>
            </div>

            <!-- Timestamps -->
            <div class="mb-6 space-y-2">
                <div class="flex items-center text-sm">
                    <span class="font-medium text-gray-500 w-24">{% trans "Created" %}:</span>
                    <span class="text-gray-900">{{ page.created_at|date:"Y-m-d H:i:s" }}</span>
                </div>
                <div class="flex items-center text-sm">
                    <span class="font-medium text-gray-500 w-24">{% trans "Updated" %}:</span>
                    <span class="text-gray-900">{{ page.updated_at|date:"Y-m-d H:i:s" }}</span>
                </div>
                {% if page.last_retry_at %}
                <div class="flex items-center text-sm">
                    <span class="font-medium text-gray-500 w-24">{% trans "Last Retry" %}:</span>
                    <span class="text-gray-900">{{ page.last_retry_at|date:"Y-m-d H:i:s" }}</span>
                </div>
                {% endif %}
            </div>

            <!-- Summary -->
            {% if page.summary %}
            <div class="mb-6">
                <h2 class="text-sm font-medium text-gray-500 mb-1">{% trans "Summary" %}</h2>
                <div class="bg-gray-50 rounded-lg p-4 text-gray-700">
                    {{ page.summary }}
                </div>
            </div>
            {% endif %}

            <!-- Content -->
            {% if page.content %}
            <div class="mb-6">
                <h2 class="text-sm font-medium text-gray-500 mb-1">{% trans "Content" %}</h2>
                <div class="prose prose-sm sm:prose lg:prose-lg xl:prose-xl w-full">
                    {{ page.content|markdown|safe }}
                </div>
            </div>
            {% endif %}

            <!-- Error Message -->
            {% if page.error_message %}
            <div class="mb-6">
                <h2 class="text-sm font-medium text-red-500 mb-1">{% trans "Error Message" %}</h2>
                <div class="bg-red-50 text-red-700 p-4 rounded-lg">
                    {{ page.error_message }}
                </div>
            </div>
            {% endif %}

            <!-- Screenshot Section -->
            <div class="mt-8">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-medium text-gray-900">{% trans "Screenshots" %}</h3>
                    <button
                        id="takeScreenshotBtn"
                        type="button"
                        onclick="takeNewScreenshot({{ page.id }})"
                        class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <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 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"/>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                  d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"/>
                        </svg>
                        {% trans "Take Another Screenshot" %}
                    </button>
                </div>

                <!-- Latest Screenshot -->
                {% with latest_screenshot=page.screenshots.first %}
                    {% if latest_screenshot %}
                        <div class="mb-6">
                            <h4 class="text-sm font-medium text-gray-700 mb-2">{% trans "Latest Screenshot" %}</h4>
                            <div class="relative">
                                {% if latest_screenshot.path %}
                                    <img src="{{ latest_screenshot.get_url }}"
                                         alt="Latest screenshot"
                                         class="rounded-lg shadow-sm max-w-full h-auto">
                                {% else %}
                                    <img src="{% static 'images/default-screenshot.png' %}"
                                         alt="Pending screenshot"
                                         class="rounded-lg shadow-sm max-w-full h-auto">
                                {% endif %}
                                <div class="">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                        {% if latest_screenshot.status == 'completed' %}bg-green-100 text-green-800
                                        {% elif latest_screenshot.status == 'processing' %}bg-yellow-100 text-yellow-800
                                        {% elif latest_screenshot.status == 'failed' %}bg-red-100 text-red-800
                                        {% else %}bg-gray-100 text-gray-800{% endif %}">
                                        {{ latest_screenshot.get_status_display }}
                                    </span>
                                </div>
                                {% if latest_screenshot.error %}
                                    <div class="mt-2 text-sm text-red-600">
                                        {{ latest_screenshot.error }}
                                    </div>
                                {% endif %}
                            </div>
                            <div class="mt-1 text-sm text-gray-500">
                                {% trans "Taken" %}:
                                <span class="local-datetime" data-timestamp="{{ latest_screenshot.created_at|date:'c' }}">
                                    {{ latest_screenshot.created_at|date:"Y-m-d H:i" }}
                                </span>
                            </div>
                        </div>
                    {% endif %}
                {% endwith %}

                <!-- Previous Screenshots -->
                {% with previous_screenshots=page.screenshots.all|slice:"1:" %}
                    {% if previous_screenshots %}
                        <div>
                            <h4 class="text-sm font-medium text-gray-700 mb-2">{% trans "Previous Screenshots" %}</h4>
                            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
                                {% for screenshot in previous_screenshots %}
                                    <div class="relative flex flex-col">
                                        <!-- Image Container with Overlay -->
                                        <div class="relative w-48 h-48 group rounded-lg overflow-hidden">
                                            <!-- Image -->
                                            <a href="{{ screenshot.get_url }}" target="_blank" class="block h-full">
                                                {% if screenshot.path %}
                                                    <img src="{{ screenshot.get_url }}"
                                                         alt="Screenshot {{ forloop.counter }}"
                                                         class="w-full h-full object-cover">
                                                {% else %}
                                                    <img src="{% static 'images/default-screenshot.png' %}"
                                                         alt="Pending screenshot {{ forloop.counter }}"
                                                         class="w-full h-full object-cover">
                                                {% endif %}
                                            </a>

                                            <!-- Top Overlay for Delete Button -->
                                            <div class="absolute top-0 left-0 right-0 p-2 bg-gradient-to-b from-black/40 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                                                <div class="flex justify-end">
                                                    <button type="button"
                                                            onclick="deleteScreenshot({{ screenshot.id }})"
                                                            class="p-1.5 bg-red-100 text-red-600 rounded-full hover:bg-red-200 transition-colors duration-200"
                                                            title="{% trans 'Delete Screenshot' %}">
                                                        <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="M6 18L18 6M6 6l12 12"/>
                                                        </svg>
                                                    </button>
                                                </div>
                                            </div>

                                            <!-- Bottom Overlay for Status and Time -->
                                            <div class="absolute bottom-0 left-0 right-0 p-2 bg-gradient-to-t from-black/60 to-transparent">
                                                <div class="flex flex-col space-y-1.5">
                                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium
                                                        {% if screenshot.status == 'completed' %}bg-green-100 text-green-800
                                                        {% elif screenshot.status == 'processing' %}bg-yellow-100 text-yellow-800
                                                        {% elif screenshot.status == 'failed' %}bg-red-100 text-red-800
                                                        {% else %}bg-gray-100 text-gray-800{% endif %}">
                                                        {{ screenshot.get_status_display }}
                                                    </span>
                                                    <span class="text-xs text-white font-medium">
                                                        <span class="local-datetime" data-timestamp="{{ screenshot.created_at|date:'c' }}">
                                                            {{ screenshot.created_at|date:"Y-m-d H:i" }}
                                                        </span>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                {% endfor %}
                            </div>
                        </div>
                    {% endif %}
                {% endwith %}
            </div>


        </div>
    </div>
</div>

<!-- Add this to your JavaScript section -->
<script>
function takeNewScreenshot(pageId) {
    const button = document.getElementById('takeScreenshotBtn');
    button.disabled = true;
    button.classList.add('opacity-50', 'cursor-not-allowed');

    fetch(`/api/pages/${pageId}/take-screenshot`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        if (data.status === 'success') {
            location.reload();
        } else {
            alert(data.error || 'Failed to take screenshot');
            button.disabled = false;
            button.classList.remove('opacity-50', 'cursor-not-allowed');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to take screenshot');
        button.disabled = false;
        button.classList.remove('opacity-50', 'cursor-not-allowed');
    });
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function deleteScreenshot(screenshotId) {
    if (confirm('{% trans "Are you sure you want to delete this screenshot?" %}')) {
        fetch(`/api/pages/screenshots/${screenshotId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            location.reload();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to delete screenshot');
        });
    }
}

// Tag colors
const colors = [
    'bg-blue-50 hover:bg-blue-100 text-blue-700',
    'bg-green-50 hover:bg-green-100 text-green-700',
    'bg-yellow-50 hover:bg-yellow-100 text-yellow-700',
    'bg-red-50 hover:bg-red-100 text-red-700',
    'bg-indigo-50 hover:bg-indigo-100 text-indigo-700',
    'bg-purple-50 hover:bg-purple-100 text-purple-700',
    'bg-pink-50 hover:bg-pink-100 text-pink-700',
    'bg-cyan-50 hover:bg-cyan-100 text-cyan-700',
    'bg-orange-50 hover:bg-orange-100 text-orange-700',
    'bg-teal-50 hover:bg-teal-100 text-teal-700',
    'bg-lime-50 hover:bg-lime-100 text-lime-700',
    'bg-emerald-50 hover:bg-emerald-100 text-emerald-700',
    'bg-sky-50 hover:bg-sky-100 text-sky-700',
    'bg-violet-50 hover:bg-violet-100 text-violet-700',
    'bg-rose-50 hover:bg-rose-100 text-rose-700',
    'bg-amber-50 hover:bg-amber-100 text-amber-700'
];

document.querySelectorAll('.tag-card').forEach(tag => {
    const randomColor = colors[Math.floor(Math.random() * colors.length)];
    tag.classList.add(...randomColor.split(' '));
});
</script>
{% endblock %}
