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

{% block content %}
<div class="container mx-auto px-2 py-2">
    <div class="bg-white shadow-md rounded-lg overflow-hidden mb-8">
        <div class="px-2 py-5 sm:px-6 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
            <h1 class="text-2xl font-bold text-gray-900 flex items-center">
                {% trans "Link Details" %}
                {% if '{' in link.original_url and '}' in link.original_url %}
                    <span class="ml-2 bg-purple-100 text-purple-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded-full flex items-center">
                        <i class="fas fa-magic mr-1"></i>{% trans "Template" %}
                    </span>
                {% elif link.link_type == 'LINK' %}
                    <span class="ml-2 bg-blue-100 text-blue-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded-full flex items-center">
                        <i class="fas fa-link mr-1"></i>{% trans "Link" %}
                    </span>
                {% else %}
                    <span class="ml-2 bg-green-100 text-green-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded-full flex items-center">
                        <i class="fas fa-code mr-1"></i>{% trans "Custom" %}
                    </span>
                {% endif %}
            </h1>
            <div class="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-2">
                <a href="{% url 'redirect_to_original' link.alias %}" target="_blank" class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-2 rounded text-sm sm:text-base inline-flex items-center justify-center">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <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"></path>
                    </svg>
                    {% trans "Go to link" %}
                </a>
                <a href="{% url 'link_update' link.pk %}" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-2 rounded text-sm sm:text-base inline-flex items-center justify-center">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <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"></path>
                    </svg>
                    {% trans "Edit" %}
                </a>
            </div>
        </div>
        <div class="px-2 py-5 sm:p-6">
            <dl class="grid grid-cols-1 gap-x-4 gap-y-8 sm:grid-cols-2">
                <div class="sm:col-span-1">
                    <dt class="text-sm font-medium text-gray-500">{% trans "Alias" %}</dt>
                    <dd class="mt-1 text-sm text-gray-900">{{ link.alias }}</dd>
                </div>
                <div class="sm:col-span-1">
                    <dt class="text-sm font-medium text-gray-500">{% trans "Click Count" %}</dt>
                    <dd class="mt-1 text-sm text-gray-900">{{ link.click_count }}</dd>
                </div>
                <div class="sm:col-span-1">
                    <dt class="text-sm font-medium text-gray-500">{% trans "Created At" %}</dt>
                    <dd class="mt-1 text-sm text-gray-900">{{ link.created_at|date:"Y-m-d H:i" }}</dd>
                </div>
                <div class="sm:col-span-1">
                    <dt class="text-sm font-medium text-gray-500">{% trans "Updated At" %}</dt>
                    <dd class="mt-1 text-sm text-gray-900">{{ link.updated_at|date:"Y-m-d H:i" }}</dd>
                </div>
                {% if link.link_type == 'LINK' %}
                    <div class="sm:col-span-2">
                        <dt class="text-sm font-medium text-gray-500">{% trans "Original URL" %}</dt>
                        <dd class="mt-1 text-sm text-gray-900">
                            <a href="{{ link.original_url }}" target="_blank" class="text-blue-600 hover:underline">{{ link.original_url }}</a>
                        </dd>
                    </div>
                {% endif %}
                {% if link.description %}
                <div class="sm:col-span-2">
                    <dt class="text-sm font-medium text-gray-500">{% trans "Description" %}</dt>
                    <dd class="mt-1 text-sm text-gray-900">{{ link.description }}</dd>
                </div>
                {% endif %}
                {% if link.tags.exists %}
                <div class="sm:col-span-2">
                    <dt class="text-sm font-medium text-gray-500">{% trans "Tags" %}</dt>
                    <dd class="mt-1">
                        <div class="flex flex-wrap gap-2 mt-2">
                            {% for tag in link.tags.all %}
                            {% with number=forloop.counter %}
                            <a href="{% url 'tag-detail' tag.slug %}"
                               class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium transition duration-150 {% if number|divisibleby:10 %}tag-10{% elif number|divisibleby:9 %}tag-9{% elif number|divisibleby:8 %}tag-8{% elif number|divisibleby:7 %}tag-7{% elif number|divisibleby:6 %}tag-6{% elif number|divisibleby:5 %}tag-5{% elif number|divisibleby:4 %}tag-4{% elif number|divisibleby:3 %}tag-3{% elif number|divisibleby:2 %}tag-2{% else %}tag-1{% endif %}">
                                {{ tag.name }}
                            </a>
                            {% endwith %}
                            {% endfor %}
                        </div>
                    </dd>
                </div>
                {% endif %}
            </dl>
        </div>
    </div>

    {% if link.link_type == 'CUSTOM' %}
    <div class="bg-white shadow-md rounded-lg overflow-hidden mb-8">
        <div class="px-2 py-5 sm:px-6 bg-gray-50 border-b border-gray-200">
            <h2 class="text-xl font-bold text-gray-900">{% trans "Custom Content" %}</h2>
        </div>
        <div class="px-2 py-5 sm:p-6">
            <div class="prose prose-sm sm:prose lg:prose-lg xl:prose-xl max-w-none">
                {{ rendered_text|safe }}
            </div>
        </div>
    </div>
    {% endif %}

    <div class="bg-white shadow-md rounded-lg overflow-hidden">
        <div class="px-2 py-5 sm:px-6 bg-gray-50 border-b border-gray-200">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center space-y-4 sm:space-y-0">
                <h2 class="text-xl font-bold text-gray-900">{% trans "Click Statistics" %} - {{ period_name }}</h2>
                <div class="flex flex-wrap gap-2">
                    <button onclick="changePeriod('3m')" class="period-btn {% if current_period == '3m' %}active{% endif %}" data-period="3m">
                        {% trans "3 Months" %}
                    </button>
                    <button onclick="changePeriod('6m')" class="period-btn {% if current_period == '6m' %}active{% endif %}" data-period="6m">
                        {% trans "6 Months" %}
                    </button>
                    <button onclick="changePeriod('1y')" class="period-btn {% if current_period == '1y' %}active{% endif %}" data-period="1y">
                        {% trans "1 Year" %}
                    </button>
                    <button onclick="changePeriod('all')" class="period-btn {% if current_period == 'all' %}active{% endif %}" data-period="all">
                        {% trans "All Time" %}
                    </button>
                </div>
            </div>
        </div>
        <div class="px-2 py-5 sm:p-6">
            <div style="height: 400px; position: relative;">
                <canvas id="clickChart"></canvas>
            </div>
        </div>
    </div>

    <div class="bg-white shadow-md rounded-lg overflow-hidden mt-8">
        <div class="px-2 py-5 sm:px-6 bg-gray-50 border-b border-gray-200">
            <h2 class="text-xl font-bold text-gray-900">{% trans "Change History" %}</h2>
        </div>
        <div class="px-2 py-5 sm:p-6">
            {% if change_logs %}
                <ul class="divide-y divide-gray-200">
                {% for log in change_logs %}
                    <li class="py-3">
                        {% if log.change_type == 'url_change' %}
                            <div class="flex items-center mb-2">
                                <svg class="w-5 h-5 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path>
                                </svg>
                                <p class="text-sm font-medium text-gray-900">
                                    {% trans "URL Changed" %}
                                </p>
                                <span class="ml-2 text-xs text-gray-500">{{ log.changed_at|date:"Y-m-d H:i" }}</span>
                            </div>
                            {% if log.old_url %}
                                <p class="mt-1 text-sm text-red-600 line-through ml-7">{{ log.old_url }}</p>
                            {% endif %}
                            {% if log.new_url %}
                                <p class="mt-1 text-sm text-green-600 ml-7">{{ log.new_url }}</p>
                            {% endif %}
                        {% elif log.change_type == 'task_toggle' %}
                            <div class="flex items-center mb-2">
                                <svg class="w-5 h-5 text-purple-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path>
                                </svg>
                                <p class="text-sm font-medium text-gray-900">
                                    {% trans "Task Toggled" %}
                                </p>
                                <span class="ml-2 text-xs text-gray-500">{{ log.changed_at|date:"Y-m-d H:i" }}</span>
                            </div>
                            {% if log.metadata %}
                                <div class="ml-7 text-sm">
                                    {% if log.metadata.task_text %}
                                        <p class="text-gray-700 font-medium mb-1">
                                            "{{ log.metadata.task_text }}"
                                        </p>
                                    {% endif %}
                                    <p class="text-gray-600">
                                        <span class="{% if log.metadata.old_state %}text-green-600{% else %}text-gray-400{% endif %}">
                                            {% if log.metadata.old_state %}☑{% else %}☐{% endif %}
                                        </span>
                                        →
                                        <span class="{% if log.metadata.new_state %}text-green-600{% else %}text-gray-400{% endif %}">
                                            {% if log.metadata.new_state %}☑{% else %}☐{% endif %}
                                        </span>
                                        <span class="ml-1">{% if log.metadata.new_state %}{% trans "checked" %}{% else %}{% trans "unchecked" %}{% endif %}</span>
                                    </p>
                                </div>
                            {% endif %}
                        {% elif log.change_type == 'content_edit' %}
                            <div class="flex items-center mb-2">
                                <svg class="w-5 h-5 text-green-500 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"></path>
                                </svg>
                                <p class="text-sm font-medium text-gray-900">
                                    {% trans "Content Edited" %}
                                </p>
                                <span class="ml-2 text-xs text-gray-500">{{ log.changed_at|date:"Y-m-d H:i" }}</span>
                            </div>
                            {% if log.metadata %}
                                <div class="ml-7 text-sm text-gray-600">
                                    {{ log.metadata|safe }}
                                </div>
                            {% endif %}
                        {% else %}
                            <div class="flex items-center mb-2">
                                <svg class="w-5 h-5 text-gray-500 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"></path>
                                </svg>
                                <p class="text-sm font-medium text-gray-900">
                                    {% trans "Change" %}
                                </p>
                                <span class="ml-2 text-xs text-gray-500">{{ log.changed_at|date:"Y-m-d H:i" }}</span>
                            </div>
                        {% endif %}
                    </li>
                {% endfor %}
                </ul>
            {% else %}
                <p class="text-sm text-gray-600">{% trans "No changes recorded." %}</p>
            {% endif %}
        </div>
    </div>

</div>
{% endblock %}

{% block extra_js %}
<!-- Chart.js (CDN — page-specific, benefits from edge proximity) -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        var ctx = document.getElementById('clickChart').getContext('2d');
        var clickData = {{ click_stats|safe }};
        var intervalDays = {{ interval_days }};

        var chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: clickData.map(item => {
                    // Use custom label if available, otherwise format date based on interval
                    if (item.label) {
                        return item.label;
                    }

                    const date = new Date(item.date);
                    if (intervalDays === 1) {
                        // Daily: show "Jan 15"
                        return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
                    } else if (intervalDays <= 14) {
                        // Weekly/Bi-weekly: show "1/15"
                        return date.toLocaleDateString('en-US', { month: 'numeric', day: 'numeric' });
                    } else {
                        // Monthly: show "Jan 2025"
                        return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
                    }
                }),
                datasets: [{
                    label: '{% trans "Clicks" %}',
                    data: clickData.map(item => item.count),
                    backgroundColor: 'rgba(99, 102, 241, 0.1)',
                    borderColor: 'rgba(99, 102, 241, 1)',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: 'rgba(99, 102, 241, 1)',
                    pointBorderColor: '#ffffff',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6,
                    pointHoverBackgroundColor: 'rgba(99, 102, 241, 1)',
                    pointHoverBorderColor: '#ffffff',
                    pointHoverBorderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)',
                            borderDash: [2, 2]
                        },
                        ticks: {
                            stepSize: 1,
                            color: '#6b7280',
                            font: {
                                size: 12
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            color: '#6b7280',
                            font: {
                                size: 12
                            },
                            maxTicksLimit: intervalDays === 1 ? 15 : 10
                        }
                    }
                },
                elements: {
                    line: {
                        borderJoinStyle: 'round'
                    }
                }
            }
        });

        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(' '));
        });
    });

    // Function to change time period
    function changePeriod(period) {
        const url = new URL(window.location.href);
        url.searchParams.set('period', period);
        window.location.href = url.toString();
    }

    // Task checkbox functionality
    document.querySelectorAll('.task-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', async function(e) {
            const taskHash = this.getAttribute('data-hash');
            const linkId = {{ link.id }};

            try {
                const response = await fetch(`/link/${linkId}/toggle_task/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ task_hash: taskHash })
                });

                if (!response.ok) {
                    this.checked = !this.checked;
                    console.error('Failed to update task state');
                }
            } catch (error) {
                this.checked = !this.checked;
                console.error('Error updating task:', error);
            }
        });
    });
</script>
{% endblock %}

{% block extra_css %}
<style>
    .prose {
        color: #374151;
        max-width: 65ch;
    }
    .prose p {
        margin-top: 1.25em;
        margin-bottom: 1.25em;
    }
    .prose a {
        color: #2563eb;
        text-decoration: underline;
    }
    .prose strong {
        font-weight: 600;
    }
    .prose ul {
        margin-top: 1.25em;
        margin-bottom: 1.25em;
        list-style-type: disc;
        padding-left: 1.625em;
    }
    .prose ol {
        margin-top: 1.25em;
        margin-bottom: 1.25em;
        list-style-type: decimal;
        padding-left: 1.625em;
    }
    .prose h1 {
        font-size: 2.25em;
        margin-top: 0;
        margin-bottom: 0.8888889em;
        line-height: 1.1111111;
    }
    .prose h2 {
        font-size: 1.5em;
        margin-top: 2em;
        margin-bottom: 1em;
        line-height: 1.3333333;
    }
    .prose h3 {
        font-size: 1.25em;
        margin-top: 1.6em;
        margin-bottom: 0.6em;
        line-height: 1.6;
    }
    .prose img {
        margin-top: 2em;
        margin-bottom: 2em;
    }
    .prose code {
        color: #111827;
        font-weight: 600;
    }
    .prose pre {
        color: #e5e7eb;
        background-color: #1f2937;
        overflow-x: auto;
        font-size: 0.875em;
        line-height: 1.7142857;
        margin-top: 1.7142857em;
        margin-bottom: 1.7142857em;
        border-radius: 0.375rem;
        padding-top: 0.8571429em;
        padding-right: 1.1428571em;
        padding-bottom: 0.8571429em;
        padding-left: 1.1428571em;
    }

    /* Chart container styling */
    #clickChart {
        border-radius: 8px;
    }

    /* Period selection buttons */
    .period-btn {
        padding: 0.375rem 0.75rem;
        font-size: 0.875rem;
        font-weight: 500;
        border-radius: 0.375rem;
        border: 1px solid #d1d5db;
        background-color: #ffffff;
        color: #374151;
        cursor: pointer;
        transition: all 0.2s ease-in-out;
    }

    .period-btn:hover {
        background-color: #f9fafb;
        border-color: #9ca3af;
    }

    .period-btn.active {
        background-color: #6366f1;
        border-color: #6366f1;
        color: #ffffff;
    }

    .period-btn.active:hover {
        background-color: #5b21b6;
        border-color: #5b21b6;
    }

    /* Task List Styles */
    .task-item {
        list-style: none;
        padding-left: 0;
    }

    .task-checkbox {
        margin-right: 0.5rem;
        cursor: pointer;
        width: 1.1em;
        height: 1.1em;
        vertical-align: middle;
    }

    .task-checkbox:hover {
        opacity: 0.7;
    }
</style>
{% endblock %}
