{% extends "base.html" %}

{% block title %}My Bookmarks - Knowledge Base{% endblock %}

{% block content %}
<div class="row">
    <!-- Sidebar -->
    <div class="col-md-3">
        <div class="card p-3 mb-4 shadow-sm border-0 bg-white rounded-3">
            <h5 class="h6 text-uppercase fw-bold text-muted mb-3">Filter by Tag</h5>
            <div class="d-flex flex-wrap gap-2">
                <a href="{% url 'home' %}" class="badge {% if not request.GET.tag %}bg-primary{% else %}bg-light text-dark border{% endif %} text-decoration-none p-2">All</a>
                {% for tag in all_tags %}
                    <a href="?tag={{ tag.name }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}" 
                       class="badge {% if request.GET.tag == tag.name %}bg-primary{% else %}bg-light text-dark border{% endif %} text-decoration-none p-2">
                        #{{ tag.name }}
                    </a>
                {% endfor %}
            </div>
        </div>

        <div class="card p-3 mb-4 shadow-sm border-0 bg-white rounded-3">
            <h5 class="h6 text-uppercase fw-bold text-muted mb-3">My Teams</h5>
            <div class="list-group list-group-flush small">
                {% for team in teams %}
                    <a href="{% url 'team-detail' team.pk %}" class="list-group-item list-group-item-action border-0 px-0 d-flex justify-content-between align-items-center">
                        <span><i class="bi bi-people me-2"></i>{{ team.name }}</span>
                    </a>
                {% empty %}
                    <p class="text-muted small mb-0">No teams yet. <a href="{% url 'team-list' %}">Explore</a></p>
                {% endfor %}
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="col-md-9">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0">{% if request.GET.tag %}Tag: #{{ request.GET.tag }}{% else %}My Bookmarks{% endif %}</h1>
            <a href="{% url 'bookmark-add' %}" class="btn btn-primary rounded-pill px-4">
                <i class="bi bi-plus-lg me-1"></i> New Bookmark
            </a>
        </div>

        <form method="get" class="mb-4">
            <div class="input-group input-group-lg shadow-sm">
                <span class="input-group-text bg-white border-end-0"><i class="bi bi-search text-muted"></i></span>
                <input type="text" name="q" class="form-control border-start-0 ps-0 {% if request.GET.q %}border-end-0{% endif %}" placeholder="Search by title, url, notes or content..." value="{{ request.GET.q|default:'' }}">
                {% if request.GET.q %}
                    <a href="{% url 'home' %}{% if request.GET.tag %}?tag={{ request.GET.tag }}{% endif %}" class="input-group-text bg-white border-start-0 text-decoration-none" title="Clear search">
                        <i class="bi bi-x-lg text-muted"></i>
                    </a>
                {% endif %}
                {% if request.GET.tag %}
                    <input type="hidden" name="tag" value="{{ request.GET.tag }}">
                {% endif %}
                <button type="submit" class="btn btn-primary px-4">Search</button>
            </div>
        </form>

        <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4" id="bookmarks-container">
            {% for bookmark in bookmarks %}
            <div class="col bookmark-item" data-id="{{ bookmark.id }}">
                <div class="card h-100 border-0 shadow-sm hover-elevate overflow-hidden">
                    <div class="card-body d-flex flex-column">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                             <h5 class="card-title h6 fw-bold mb-0 text-truncate w-100" title="{{ bookmark.title|default:bookmark.url }}">
                                <a href="{% url 'bookmark-detail' bookmark.pk %}" class="text-decoration-none text-dark bookmark-title-link stretched-link">
                                    {% if bookmark.title %}
                                        {{ bookmark.title|truncatechars:50 }}
                                    {% else %}
                                        {{ bookmark.url|truncatechars:50 }}
                                    {% endif %}
                                </a>
                            </h5>
                            {% if bookmark.is_favorite %}
                                <i class="bi bi-star-fill text-warning ms-2 flex-shrink-0" title="Favorite"></i>
                            {% endif %}
                        </div>

                        <div class="mb-3">
                             <small class="text-muted d-block text-truncate">
                                <i class="bi bi-link-45deg me-1"></i>{{ bookmark.url }}
                            </small>
                        </div>
                        
                        <div class="mb-3 flex-grow-1">
                            {% if bookmark.notes %}
                                <p class="card-text small text-secondary mb-2">{{ bookmark.notes|truncatewords:20 }}</p>
                            {% endif %}

                            <div class="summary-preview">
                                {% if bookmark.summary %}
                                    <p class="card-text small text-dark bg-light p-2 rounded border-start border-3 border-primary">
                                        {{ bookmark.summary.content|truncatewords:20 }}
                                    </p>
                                {% else %}
                                    <div class="text-muted small loading-indicator">
                                        <div class="spinner-border spinner-border-sm text-primary me-1" role="status"></div>
                                        Generating...
                                    </div>
                                {% endif %}
                            </div>
                        </div>

                        <div class="mt-auto">
                            <div class="d-flex flex-wrap gap-1 mb-3" style="max-height: 50px; overflow: hidden;">
                                {% for tag in bookmark.tags.all|slice:":3" %}
                                    <span class="badge bg-light text-muted border small">#{{ tag.name }}</span>
                                {% endfor %}
                                {% if bookmark.tags.all.count > 3 %}
                                    <span class="badge bg-light text-muted border small">+{{ bookmark.tags.all.count|add:"-3" }}</span>
                                {% endif %}
                            </div>

                            <div class="d-flex justify-content-between align-items-center pt-2 border-top">
                                <small class="text-muted" style="font-size: 0.75rem;">
                                    {{ bookmark.created_at|date:"M d, Y" }}
                                </small>
                                
                                <div class="dropdown position-static">
                                    <button class="btn btn-link text-muted p-0" type="button" data-bs-toggle="dropdown" style="z-index: 2; position: relative;">
                                        <i class="bi bi-three-dots"></i>
                                    </button>
                                    <ul class="dropdown-menu dropdown-menu-end shadow">
                                        <li><a class="dropdown-item" href="{% url 'bookmark-detail' bookmark.pk %}">View Details</a></li>
                                        <li><a class="dropdown-item" href="{% url 'bookmark-edit' bookmark.pk %}">Edit</a></li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li>
                                            <form action="{% url 'bookmark-delete' bookmark.pk %}" method="post" style="display: inline;">
                                                {% csrf_token %}
                                                <button type="submit" class="dropdown-item text-danger" onclick="return confirm('Are you sure?')">Delete</button>
                                            </form>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {% empty %}
            <div class="col-12 text-center py-5">
                <div class="card border-0 shadow-sm p-5 bg-white">
                    <div class="display-1 text-light mb-3"><i class="bi bi-bookmark-plus"></i></div>
                    <h3 class="h4">No bookmarks found</h3>
                    <p class="text-muted">Start building your knowledge base by adding your first bookmark.</p>
                    <div class="mt-3">
                        <a href="{% url 'bookmark-add' %}" class="btn btn-primary rounded-pill px-4">Add Bookmark</a>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>

        {% if is_paginated %}
        <nav class="mt-5">
            <ul class="pagination justify-content-center">
                {% if page_obj.has_previous %}
                    <li class="page-item"><a class="page-link rounded-circle me-2 border-0 shadow-sm" href="?page={{ page_obj.previous_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}{% if request.GET.tag %}&tag={{ request.GET.tag }}{% endif %}"><i class="bi bi-chevron-left"></i></a></li>
                {% endif %}
                
                {% for i in paginator.page_range %}
                    {% if page_obj.number == i %}
                        <li class="page-item active"><span class="page-link rounded-circle me-2 border-0 shadow-sm">{{ i }}</span></li>
                    {% elif i > page_obj.number|add:'-3' and i < page_obj.number|add:'3' %}
                        <li class="page-item"><a class="page-link rounded-circle me-2 border-0 shadow-sm text-dark" href="?page={{ i }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}{% if request.GET.tag %}&tag={{ request.GET.tag }}{% endif %}">{{ i }}</a></li>
                    {% endif %}
                {% endfor %}

                {% if page_obj.has_next %}
                    <li class="page-item"><a class="page-link rounded-circle border-0 shadow-sm" href="?page={{ page_obj.next_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}{% if request.GET.tag %}&tag={{ request.GET.tag }}{% endif %}"><i class="bi bi-chevron-right"></i></a></li>
                {% endif %}
            </ul>
        </nav>
        {% endif %}
    </div>
</div>

<style>
    .hover-elevate:hover {
        transform: translateY(-4px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.08) !important;
        transition: all 0.3s ease;
    }
    .bookmark-item .card {
        transition: all 0.3s ease;
    }
</style>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const bookmarksToPoll = Array.from(document.querySelectorAll('.bookmark-item')).filter(item => {
            return item.querySelector('.loading-indicator') !== null;
        }).map(item => ({
            element: item,
            id: item.getAttribute('data-id'),
            retries: 0
        }));

        if (bookmarksToPoll.length === 0) return;

        const MAX_RETRIES = 60; // 3 minutes at 3s interval
        let pollInterval = setInterval(async function() {
            let stillLoading = false;
            
            for (let i = 0; i < bookmarksToPoll.length; i++) {
                const item = bookmarksToPoll[i];
                const loadingIndicator = item.element.querySelector('.loading-indicator');
                if (!loadingIndicator) continue;

                if (item.retries >= MAX_RETRIES) {
                    loadingIndicator.innerHTML = '<span class="text-danger"><i class="bi bi-exclamation-triangle me-1"></i> Summarization timed out.</span>';
                    continue;
                }

                item.retries++;
                try {
                    const response = await fetch(`/api/bookmarks/${item.id}/`);
                    if (response.ok) {
                        const data = await response.json();
                        
                        // Update title if it was changed from URL to actual title
                        const titleLink = item.element.querySelector('.bookmark-title-link');
                        if (data.title && (titleLink.textContent.includes('://') || titleLink.textContent.trim().length === 0)) {
                            titleLink.textContent = data.title.length > 50 ? data.title.substring(0, 50) + '...' : data.title;
                        }

                        if (data.summary && data.summary.content) {
                            const summaryPreview = item.element.querySelector('.summary-preview');
                            const truncatedSummary = data.summary.content.split(' ').slice(0, 20).join(' ') + (data.summary.content.split(' ').length > 20 ? '...' : '');
                            summaryPreview.innerHTML = `<p class="card-text small text-dark bg-light p-2 rounded border-start border-3 border-primary">${truncatedSummary}</p>`;
                        } else {
                            stillLoading = true;
                        }
                    } else if (response.status === 404) {
                        loadingIndicator.innerHTML = '<span class="text-danger">Bookmark not found.</span>';
                    } else {
                        stillLoading = true;
                    }
                } catch (error) {
                    console.error('Error polling bookmark:', item.id, error);
                    stillLoading = true;
                }
            }

            if (!stillLoading) {
                clearInterval(pollInterval);
            }
        }, 3000);
    });
</script>
{% endblock %}