{% extends "base.html" %}
{% load static %}

{% block content %}
<div class="container-fluid py-2">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="mb-0 fw-bold">{{ title }}</h4>
        <a href="{% url 'new_fit' %}" class="btn btn-sm btn-outline-lavender rounded-pill px-3">
            <i class="fas fa-plus me-1"></i> <span class="d-none d-sm-inline">New Fit</span><span class="d-inline d-sm-none">New</span>
        </a>
    </div>

    <!-- Filter Toggle and Sort Bars -->
    <div class="mb-3">
        <button class="btn btn-outline-secondary btn-sm rounded-pill px-3 mb-2" type="button" data-bs-toggle="collapse" data-bs-target="#filterCollapse" aria-expanded="false">
            <i class="bi bi-filter me-1"></i> Filter
        </button>
        
        <div class="collapse {% if sort != 'recent' %}show{% endif %}" id="filterCollapse">
            <div class="d-flex flex-column gap-2 mt-2">
                <a href="?sort=recent{% if current_folder %}&folder={{ current_folder.id }}{% endif %}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}" 
                   class="btn {% if sort == 'recent' %}btn-lavender{% else %}btn-outline-secondary{% endif %} btn-sm py-2 text-start px-3 rounded-3 border-0 shadow-sm">
                    Most Recently Added
                </a>
                <a href="?sort=alpha{% if current_folder %}&folder={{ current_folder.id }}{% endif %}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}" 
                   class="btn {% if sort == 'alpha' %}btn-lavender{% else %}btn-outline-secondary{% endif %} btn-sm py-2 text-start px-3 rounded-3 border-0 shadow-sm">
                    A-Z
                </a>
            </div>
        </div>
    </div>

    <!-- Category Tabs (Folders) -->
    <div class="category-tabs-container mb-4 overflow-auto">
        <ul class="nav nav-pills flex-nowrap pb-2 gap-2" id="folder-tabs" role="tablist" style="min-width: max-content;">
            <li class="nav-item" role="presentation">
                <a href="{% url 'outfit_list' %}?sort={{ sort }}" class="nav-link rounded-pill {% if not current_folder %}active bg-lavender{% else %}bg-secondary text-white{% endif %} py-1 px-3 small">
                    All Outfits
                </a>
            </li>
            {% for folder in folders %}
            <li class="nav-item" role="presentation">
                <a href="{% url 'outfit_list' %}?folder={{ folder.id }}&sort={{ sort }}" class="nav-link rounded-pill {% if current_folder.id == folder.id %}active bg-lavender{% else %}bg-secondary text-white{% endif %} py-1 px-3 small">
                    {{ folder.name }}
                </a>
            </li>
            {% endfor %}
        </ul>
    </div>

    <!-- Search -->
    <form method="GET" class="mb-4">
        {% if current_folder %}<input type="hidden" name="folder" value="{{ current_folder.id }}">{% endif %}
        <input type="hidden" name="sort" value="{{ sort }}">
        <div class="input-group input-group-sm glass-card p-1">
            <span class="input-group-text bg-transparent border-0 text-dim"><i class="fas fa-search"></i></span>
            <input type="text" name="q" class="form-control bg-transparent border-0 text-white" placeholder="Search outfits..." value="{{ request.GET.q }}">
        </div>
    </form>

    <!-- Outfit Grid -->
    <div class="row g-4">
        {% for outfit in outfits %}
        <div class="col-12 col-md-6 col-lg-4">
            <div class="glass-card outfit-card h-100 overflow-hidden position-relative border border-secondary shadow-lg long-press-target" 
                 data-outfit-id="{{ outfit.id }}" data-outfit-name="{{ outfit.name|default:'Unnamed Outfit' }}">
                
                <div class="outfit-collage-container p-3" data-bs-toggle="modal" data-bs-target="#previewModal{{ outfit.id }}" style="cursor: pointer;">
                    <div class="rounded bg-secondary position-relative overflow-hidden mb-3 shadow-inner d-flex align-items-center justify-content-center p-2" style="height: 180px;">
                        <div class="d-flex align-items-center justify-content-center h-100 w-100 overflow-hidden" style="gap: 8px;">
                            {% for item in outfit.items.all|slice:":4" %}
                                <img src="{{ item.image.url }}" class="outfit-item-square shadow-sm" alt="{{ item.name }}">
                            {% endfor %}
                            {% if outfit.accessories.exists %}
                                {% for acc in outfit.accessories.all|slice:":2" %}
                                    <img src="{{ acc.image.url }}" class="outfit-item-square rounded-circle shadow-sm" alt="{{ acc.name }}">
                                {% endfor %}
                            {% endif %}
                        </div>
                        
                        {% if not outfit.items.exists and not outfit.accessories.exists %}
                        <div class="w-100 h-100 d-flex align-items-center justify-content-center bg-dark">
                            <i class="fas fa-tshirt text-dim fa-3x"></i>
                        </div>
                        {% endif %}
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-start pe-2">
                        <div>
                            <h6 class="fw-bold mb-1 text-white text-truncate" style="max-width: 200px;">{{ outfit.name|default:"Unnamed Outfit" }}</h6>
                            <div class="small text-dim">
                                <i class="fas fa-tshirt me-1"></i> {{ outfit.items.count }}
                                {% if outfit.accessories.exists %}
                                <i class="fas fa-gem ms-2 me-1"></i> {{ outfit.accessories.count }}
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Quick Schedule Button -->
                <div class="p-3 pt-0 border-top border-secondary mt-2">
                    <button class="btn btn-sm btn-lavender w-100 py-2 mt-2" data-bs-toggle="modal" data-bs-target="#scheduleModal{{ outfit.id }}">
                        <i class="far fa-calendar-alt me-2"></i> Schedule
                    </button>
                </div>
            </div>
        </div>

        <!-- Preview Modal -->
        <div class="modal fade" id="previewModal{{ outfit.id }}" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-lg">
                <div class="modal-content bg-dark text-white border-secondary">
                    <div class="modal-header border-secondary">
                        <h5 class="modal-title fw-bold">{{ outfit.name|default:"Outfit Details" }}</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row g-4">
                            <div class="col-md-7">
                                <div class="small text-dim mb-3 text-uppercase tracking-wider fw-bold">Clothing Items</div>
                                <div class="row g-2">
                                    {% for item in outfit.items.all %}
                                    <div class="col-4">
                                        <div class="rounded bg-secondary overflow-hidden shadow-sm" style="aspect-ratio: 1/1;">
                                            <img src="{{ item.image.url }}" class="w-100 h-100 object-fit-contain" title="{{ item.name }}">
                                        </div>
                                        <div class="small text-center mt-1 text-truncate" style="font-size: 0.7rem;">{{ item.name }}</div>
                                    </div>
                                    {% endfor %}
                                </div>
                            </div>
                            <div class="col-md-5">
                                {% if outfit.accessories.exists %}
                                <div class="mb-4">
                                    <div class="small text-dim mb-3 text-uppercase tracking-wider fw-bold">Accessories</div>
                                    <div class="row g-2">
                                        {% for acc in outfit.accessories.all %}
                                        <div class="col-6">
                                            <div class="rounded-circle bg-secondary overflow-hidden shadow-sm" style="aspect-ratio: 1/1;">
                                                <img src="{{ acc.image.url }}" class="w-100 h-100 object-fit-cover" title="{{ acc.name }}">
                                            </div>
                                            <div class="small text-center mt-1 text-truncate" style="font-size: 0.7rem;">{{ acc.name }}</div>
                                        </div>
                                        {% endfor %}
                                    </div>
                                </div>
                                {% endif %}
                                
                                <div class="card bg-secondary border-0 p-3 mb-3">
                                    <div class="small text-dim mb-1">Created on</div>
                                    <div class="fw-bold">{{ outfit.date_created|date:"M d, Y" }}</div>
                                </div>
                                
                                <button class="btn btn-lavender w-100 py-3 fw-bold shadow" data-bs-toggle="modal" data-bs-target="#scheduleModal{{ outfit.id }}">
                                    <i class="far fa-calendar-alt me-2"></i> Schedule Now
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Schedule Modal -->
        <div class="modal fade" id="scheduleModal{{ outfit.id }}" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content bg-dark text-white border-secondary">
                    <div class="modal-header border-secondary">
                        <h5 class="modal-title fw-bold">Schedule Outfit</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-0">
                        <div class="list-group list-group-flush">
                            {% for day in week_data %}
                            <form action="{% url 'assign_outfit' %}" method="post">
                                {% csrf_token %}
                                <input type="hidden" name="outfit_id" value="{{ outfit.id }}">
                                <input type="hidden" name="date" value="{{ day.date }}">
                                <button type="submit" class="list-group-item list-group-item-action bg-dark text-white border-secondary d-flex justify-content-between align-items-center py-3">
                                    <div>
                                        <span class="fw-bold">{{ day.day }}</span>
                                        <span class="small text-dim ms-3">{{ day.date }}</span>
                                    </div>
                                    <i class="fas fa-calendar-plus text-lavender fa-lg"></i>
                                </button>
                            </form>
                            {% endfor %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {% empty %}
        <div class="col-12 text-center py-5">
            <div class="mb-3">
                <i class="fas fa-tshirt fa-4x text-dim opacity-25"></i>
            </div>
            <h5 class="text-white">No outfits found.</h5>
            <p class="text-dim">Create your first stylish combination!</p>
            <a href="{% url 'new_fit' %}" class="btn btn-lavender rounded-pill px-4">Create Outfit</a>
        </div>
        {% endfor %}
    </div>
</div>

<!-- Long Press Options Modal -->
<div class="modal fade" id="optionsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content bg-dark text-white border-secondary">
            <div class="modal-body p-0">
                <div class="list-group list-group-flush">
                    <button type="button" class="list-group-item list-group-item-action bg-dark text-white border-secondary py-3 text-center fw-bold" id="btn-categorize">
                        <i class="fas fa-folder-plus me-2 text-lavender"></i> Categorize
                    </button>
                    <button type="button" class="list-group-item list-group-item-action bg-dark text-white border-secondary py-3 text-center fw-bold text-danger" id="btn-show-delete-confirm">
                        <i class="fas fa-trash-alt me-2"></i> Delete
                    </button>
                    <button type="button" class="list-group-item list-group-item-action bg-dark text-white border-secondary py-3 text-center small text-dim" data-bs-dismiss="modal">
                        Cancel
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Categorize Modal -->
<div class="modal fade" id="categorizeModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark text-white border-secondary">
            <div class="modal-header border-secondary">
                <h5 class="modal-title fw-bold">Categorize Outfit</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="move-outfit-form" method="post">
                    {% csrf_token %}
                    <div class="mb-3">
                        <label class="form-label text-dim small text-uppercase">Select Group</label>
                        <select name="folder_id" class="form-select bg-secondary text-white border-secondary">
                            <option value="">No Group</option>
                            {% for folder in all_folders %}
                            <option value="{{ folder.id }}">{{ folder.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="text-center my-2 text-dim small">- OR -</div>
                    <div class="mb-4">
                        <label class="form-label text-dim small text-uppercase">New Group Name</label>
                        <input type="text" name="new_folder_name" class="form-control bg-secondary text-white border-secondary" placeholder="e.g. Work, Vacation">
                    </div>
                    <button type="submit" class="btn btn-lavender w-100 py-2">Save to Group</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark text-white border-secondary p-3">
            <div class="modal-body text-center py-4">
                <h4 class="fw-bold mb-4">Are you sure?</h4>
                <div class="d-flex gap-3 mt-4">
                    <button type="button" class="btn btn-outline-secondary flex-grow-1 py-3 rounded-3" data-bs-dismiss="modal">Back</button>
                    <form id="delete-outfit-form" method="post" class="flex-grow-1">
                        {% csrf_token %}
                        <button type="submit" class="btn btn-danger w-100 py-3 rounded-3 fw-bold" style="background-color: #dc3545 !important;">Delete</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_css %}
<style>
    .bg-lavender { background-color: var(--accent-lavender) !important; color: #fff !important; }
    .text-lavender { color: var(--accent-lavender); }
    .btn-outline-lavender { color: var(--accent-lavender); border-color: var(--accent-lavender); }
    .btn-outline-lavender:hover { background-color: var(--accent-lavender); color: #fff; }
    .btn-lavender { background-color: var(--accent-lavender); color: #fff; border: none; }
    .btn-lavender:hover { opacity: 0.9; transform: translateY(-1px); }
    .outfit-card { transition: all 0.3s ease; border-radius: 15px !important; }
    .outfit-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.3) !important; }
    .shadow-inner { box-shadow: inset 0 2px 4px rgba(0,0,0,0.5); }
    .border-secondary { border-color: rgba(255,255,255,0.1) !important; }

    .outfit-item-square {
        height: 80%;
        max-width: 25%;
        aspect-ratio: 1/1;
        object-fit: contain;
        background-color: rgba(255,255,255,0.05);
        border-radius: 8px;
        transition: transform 0.2s;
        border: 1px solid rgba(255,255,255,0.1);
    }
    
    .long-press-target {
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
    }
</style>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    let longPressTimer;
    const longPressDuration = 600; // ms
    let currentOutfitId = null;
    let currentOutfitName = '';

    const optionsModal = new bootstrap.Modal(document.getElementById('optionsModal'));
    const categorizeModal = new bootstrap.Modal(document.getElementById('categorizeModal'));
    const deleteConfirmModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));

    const targets = document.querySelectorAll('.long-press-target');

    targets.forEach(target => {
        function startPress(e) {
            longPressTimer = setTimeout(() => {
                currentOutfitId = target.dataset.outfitId;
                currentOutfitName = target.dataset.outfitName;
                optionsModal.show();
                // Add haptic feedback if available
                if (window.navigator && window.navigator.vibrate) {
                    window.navigator.vibrate(50);
                }
            }, longPressDuration);
        }

        function cancelPress() {
            clearTimeout(longPressTimer);
        }

        target.addEventListener('touchstart', startPress);
        target.addEventListener('touchend', cancelPress);
        target.addEventListener('touchmove', cancelPress);
        target.addEventListener('mousedown', startPress);
        target.addEventListener('mouseup', cancelPress);
        target.addEventListener('mouseleave', cancelPress);

        // Also prevent standard context menu on long press for mobile
        target.addEventListener('contextmenu', (e) => {
            e.preventDefault();
        });
    });

    document.getElementById('btn-categorize').addEventListener('click', function() {
        optionsModal.hide();
        const form = document.getElementById('move-outfit-form');
        form.action = `/outfits/${currentOutfitId}/move/`;
        categorizeModal.show();
    });

    document.getElementById('btn-show-delete-confirm').addEventListener('click', function() {
        optionsModal.hide();
        const form = document.getElementById('delete-outfit-form');
        form.action = `/outfits/${currentOutfitId}/delete/`;
        deleteConfirmModal.show();
    });
});
</script>
{% endblock %}