{% extends "filechest/base.html" %}
{% load static filechest_tags %}

{% block title %}{{ filename }} - {{ volume.verbose_name }} - FileChest{% endblock %}

{% block content %}
    <div class="container wide">
        <div class="header">
            <h1>{{ volume.verbose_name }}</h1>
            <div class="user-info">
                {% include "filechest/includes/_user_info.html" %}
            </div>
        </div>

        <div class="file-header">
            <h2>{{ filename }}{% if can_edit %} <button class="btn-rename-inline" onclick="showRenameModal()" title="Rename">✏️</button>{% endif %}</h2>
            <div class="header-actions">
                {% if parent_path %}
                <a href="{% url 'filechest:browse' volume.name parent_path %}" class="btn-back">Back</a>
                {% else %}
                <a href="{% url 'filechest:index' volume.name %}" class="btn-back">Back</a>
                {% endif %}
                {% if preview_type == 'text' or preview_type == 'image' %}
                <button id="btn-copy" class="btn-copy" onclick="copyToClipboard()">📋 Copy</button>
                {% endif %}
                <a href="{% url 'filechest:api_raw' volume.name filepath %}" class="btn-download" download>Download</a>
            </div>
        </div>

        <div class="breadcrumb">
            <a href="{% url 'filechest:index' volume.name %}">{{ volume.verbose_name }}</a>
            {% for item in breadcrumb %}
                <span>/</span>
                <a href="{% url 'filechest:browse' volume.name item.path %}">{{ item.name }}</a>
            {% endfor %}
            <span>/</span>
            <strong>{{ filename }}</strong>
        </div>

        <div class="file-meta">
            <div><strong>Size:</strong> {{ file_size|filesizeformat }}</div>
            <div><strong>Modified:</strong> {{ file_modified|timestamp_to_date }}</div>
            <div><strong>Type:</strong> {{ mime_type }}</div>
        </div>

        <div class="preview-container">
            {% if preview_type == 'image' %}
            <div class="preview-image">
                <img src="{% url 'filechest:api_raw' volume.name filepath %}" alt="{{ filename }}">
            </div>

            {% elif preview_type == 'video' %}
            <div class="preview-video">
                <video controls>
                    <source src="{% url 'filechest:api_raw' volume.name filepath %}" type="{{ mime_type }}">
                    Your browser does not support the video element.
                </video>
            </div>

            {% elif preview_type == 'audio' %}
            <div class="preview-audio">
                <audio controls>
                    <source src="{% url 'filechest:api_raw' volume.name filepath %}" type="{{ mime_type }}">
                    Your browser does not support the audio element.
                </audio>
            </div>

            {% elif preview_type == 'text' %}
            <div class="preview-text">
                <div id="text-content" class="loading">Loading...</div>
            </div>

            {% elif preview_type == 'pdf' %}
            <div class="preview-pdf">
                <iframe src="{% url 'filechest:api_raw' volume.name filepath %}"></iframe>
            </div>

            {% else %}
            <div class="preview-unknown">
                <div class="icon">{{ filename|file_icon:False }}</div>
                <p>Preview not available for this file type.</p>
                <a href="{% url 'filechest:api_raw' volume.name filepath %}" class="btn-download" download>Download File</a>
            </div>
            {% endif %}
        </div>
    </div>

    <!-- Toast -->
    <div id="toast" class="toast"></div>

    {% if can_edit %}
    <!-- Rename Modal -->
    <div id="modal-rename" class="modal">
        <div class="modal-content">
            <h3>Rename</h3>
            <input type="text" id="rename-name" placeholder="New name" oninput="updateRenameButton()">
            <div class="modal-buttons">
                <button class="btn-cancel" onclick="closeModal('modal-rename')">Cancel</button>
                <button id="btn-rename-ok" class="btn-ok" onclick="renameItem()" disabled>Rename</button>
            </div>
        </div>
    </div>
    {% endif %}
{% endblock %}

{% block extra_js %}
    <script>
        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = `toast ${type} active`;
            setTimeout(() => toast.classList.remove('active'), 5000);
        }
    </script>

    {% if preview_type == 'text' %}
    <script>
        let textContent = null;

        (async function() {
            const container = document.getElementById('text-content');
            try {
                const response = await fetch("{% url 'filechest:api_raw' volume.name filepath %}");
                if (!response.ok) throw new Error('Failed to load');
                const text = await response.text();
                textContent = text;
                const pre = document.createElement('pre');
                pre.textContent = text;
                container.innerHTML = '';
                container.appendChild(pre);
            } catch (e) {
                container.textContent = 'Failed to load file content.';
            }
        })();

        async function copyToClipboard() {
            if (!textContent) {
                showToast('Content not loaded yet', 'error');
                return;
            }
            try {
                await navigator.clipboard.writeText(textContent);
                showToast('Copied to clipboard');
            } catch (e) {
                showToast('Failed to copy', 'error');
            }
        }
    </script>
    {% elif preview_type == 'image' %}
    <script>
        async function copyToClipboard() {
            const img = document.querySelector('.preview-image img');
            if (!img) {
                showToast('Image not found', 'error');
                return;
            }
            try {
                const response = await fetch(img.src);
                const blob = await response.blob();
                // Convert to PNG if needed (clipboard API requires PNG for images)
                let pngBlob = blob;
                if (blob.type !== 'image/png') {
                    pngBlob = await convertToPng(img);
                }
                await navigator.clipboard.write([
                    new ClipboardItem({ 'image/png': pngBlob })
                ]);
                showToast('Image copied to clipboard');
            } catch (e) {
                showToast('Failed to copy image', 'error');
            }
        }

        function convertToPng(img) {
            return new Promise((resolve) => {
                const canvas = document.createElement('canvas');
                canvas.width = img.naturalWidth;
                canvas.height = img.naturalHeight;
                const ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0);
                canvas.toBlob(resolve, 'image/png');
            });
        }
    </script>
    {% endif %}

    {% if can_edit %}
    <script>
        const volumeName = "{{ volume.name }}";
        const filepath = "{{ filepath|escapejs }}";
        const filename = "{{ filename|escapejs }}";
        const parentPath = "{{ parent_path|escapejs }}";
        const apiBase = "{% url 'filechest:api_list' volume.name %}".replace(/list\/$/, '');

        function getCsrfToken() {
            const cookie = document.cookie.split('; ').find(row => row.startsWith('csrftoken='));
            return cookie ? cookie.split('=')[1] : '';
        }

        async function apiCall(endpoint, data) {
            const response = await fetch(`${apiBase}${endpoint}/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCsrfToken()
                },
                body: JSON.stringify(data)
            });
            return response.json();
        }

        function showModal(id) {
            document.getElementById(id).classList.add('active');
        }

        function closeModal(id) {
            document.getElementById(id).classList.remove('active');
        }

        function updateRenameButton() {
            const newName = document.getElementById('rename-name').value.trim();
            const btn = document.getElementById('btn-rename-ok');
            btn.disabled = !newName || newName === filename;
        }

        function showRenameModal() {
            document.getElementById('rename-name').value = filename;
            updateRenameButton();
            showModal('modal-rename');
            document.getElementById('rename-name').focus();
        }

        async function renameItem() {
            const newName = document.getElementById('rename-name').value.trim();
            if (!newName || newName === filename) {
                closeModal('modal-rename');
                return;
            }

            const result = await apiCall('rename', { path: filepath, new_name: newName });
            closeModal('modal-rename');

            if (result.success) {
                // Redirect to the new file path
                const newPath = parentPath ? `${parentPath}/${newName}` : newName;
                window.location.href = "{% url 'filechest:preview' volume.name 'PLACEHOLDER' %}".replace('PLACEHOLDER', encodeURIComponent(newPath).replace(/%2F/g, '/'));
            } else {
                showToast(result.error || 'Rename failed', 'error');
            }
        }

        // Enter key for modal
        document.getElementById('rename-name')?.addEventListener('keyup', (e) => {
            if (e.key === 'Enter') renameItem();
        });

        // Escape key to close modal
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                document.querySelectorAll('.modal.active').forEach(modal => {
                    closeModal(modal.id);
                });
            }
        });
    </script>
    {% endif %}
{% endblock %}
