{
{% extends "base.html" %}

{% block title %}{{ bookmark.title|default:bookmark.url }} - Knowledge Base{% endblock %}

{% block content %}
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="{% url 'home' %}">My Bookmarks</a></li>
    <li class="breadcrumb-item active" aria-current="page">Details</li>
  </ol>
</nav>

<div class="row">
    <div class="col-md-8">
        <div class="card p-4 mb-4">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <h1 class="h2" id="bookmark-title">{{ bookmark.title|default:bookmark.url }}</h1>
                {% if bookmark.user == request.user %}
                    <div class="d-flex gap-2">
                        <form action="{% url 'bookmark-regenerate' bookmark.pk %}" method="post">
                            {% csrf_token %}
                            <button type="submit" class="btn btn-outline-primary btn-sm" title="Regenerate Summary and Content">
                                <i class="bi bi-arrow-clockwise"></i> Regenerate
                            </button>
                        </form>
                        <div class="dropdown">
                            <button class="btn btn-outline-secondary btn-sm" type="button" data-bs-toggle="dropdown">
                                <i class="bi bi-three-dots"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><a class="dropdown-item" href="{% url 'bookmark-edit' bookmark.pk %}">Edit Metadata</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li>
                                    <form action="{% url 'bookmark-delete' bookmark.pk %}" method="post" onsubmit="return confirm('Are you sure?');">
                                        {% csrf_token %}
                                        <button type="submit" class="dropdown-item text-danger">Delete Bookmark</button>
                                    </form>
                                </li>
                            </ul>
                        </div>
                    </div>
                {% endif %}
            </div>
            
            <p class="text-muted mb-4">
                <i class="bi bi-link-45deg"></i> <a href="{{ bookmark.url }}" target="_blank" class="text-break">{{ bookmark.url }}</a>
            </p>

            {% if bookmark.notes %}
                <div class="mb-4">
                    <h5 class="text-uppercase small fw-bold text-muted mb-2">My Notes</h5>
                    <div class="p-3 bg-light rounded border-start border-4 border-primary">
                        {{ bookmark.notes|linebreaks }}
                    </div>
                </div>
            {% endif %}

            <div class="mb-4">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h5 class="text-uppercase small fw-bold text-muted mb-0">AI Summary</h5>
                    <div id="summary-actions" class="{% if not bookmark.summary %}d-none{% endif %}">
                        {% if bookmark.user == request.user %}
                            <button class="btn btn-link btn-sm p-0 text-decoration-none" onclick="toggleEdit('summary')">Edit</button>
                        {% endif %}
                    </div>
                </div>
                
                <div id="summary-container">
                    {% if bookmark.summary %}
                        <div id="summary-display" class="p-3 border rounded shadow-sm bg-white">
                            {{ bookmark.summary.content }}
                        </div>
                        {% if bookmark.user == request.user %}
                        <div id="summary-edit" class="d-none">
                            <form action="{% url 'summary-update' bookmark.pk %}" method="post">
                                {% csrf_token %}
                                <textarea name="content" class="form-control mb-2" rows="4">{{ bookmark.summary.content }}</textarea>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary btn-sm">Save</button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="toggleEdit('summary')">Cancel</button>
                                </div>
                            </form>
                        </div>
                        {% endif %}
                    {% else %}
                        <div id="summary-loading" class="alert alert-light border text-center small py-3">
                            <div class="spinner-border spinner-border-sm text-primary me-2" role="status"></div>
                            AI Summary is being generated...
                        </div>
                    {% endif %}
                </div>
            </div>

            <div class="mt-4">
                {% for tag in bookmark.tags.all %}
                    <span class="badge bg-light text-dark border p-2 me-1">#{{ tag.name }}</span>
                {% endfor %}
            </div>
        </div>

        <div class="card p-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="text-uppercase small fw-bold text-muted mb-0">Extracted Text Content</h5>
                <div id="extraction-actions" class="{% if not bookmark.extraction %}d-none{% endif %}">
                    {% if bookmark.user == request.user %}
                        <button class="btn btn-link btn-sm p-0 text-decoration-none" onclick="toggleEdit('extraction')">Edit</button>
                    {% endif %}
                </div>
            </div>

            <div id="extraction-container">
                {% if bookmark.extraction %}
                    <div id="extraction-display" class="extraction-content text-muted small" style="max-height: 500px; overflow-y: auto;">
                        {{ bookmark.extraction.content_text|linebreaks }}
                    </div>
                    {% if bookmark.user == request.user %}
                    <div id="extraction-edit" class="d-none">
                        <form action="{% url 'extraction-update' bookmark.pk %}" method="post">
                            {% csrf_token %}
                            <textarea name="content_text" class="form-control mb-2" rows="15">{{ bookmark.extraction.content_text }}</textarea>
                            <div class="d-flex gap-2">
                                <button type="submit" class="btn btn-primary btn-sm">Save</button>
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="toggleEdit('extraction')">Cancel</button>
                            </div>
                        </form>
                    </div>
                    {% endif %}
                {% else %}
                    <div id="extraction-loading" class="alert alert-light border text-center small py-3">
                        <div class="spinner-border spinner-border-sm text-primary me-2" role="status"></div>
                        Content is being extracted...
                    </div>
                {% endif %}
            </div>
        </div>
    </div>

    <div class="col-md-4">
        {% if bookmark.user == request.user %}
        <div class="card p-4 mb-4">
            <h5 class="h6 mb-3">Share with Teams</h5>
            <div class="list-group list-group-flush">
                {% for team in user.teams.all %}
                <div class="list-group-item d-flex justify-content-between align-items-center px-0">
                    <div>
                        <div class="fw-bold">{{ team.name }}</div>
                        <div class="small text-muted">{{ team.members.count }} members</div>
                    </div>
                    <button class="btn btn-sm btn-outline-primary share-toggle" 
                            data-url="{% url 'bookmark-share-toggle' bookmark.pk team.pk %}"
                            data-team-id="{{ team.pk }}">
                        {% with shared=False %}
                            {% for share in bookmark.shares.all %}
                                {% if share.team == team %}{% with shared=True %}Shared{% endwith %}{% endif %}
                            {% endfor %}
                            {% if not shared %}Share{% endif %}
                        {% endwith %}
                    </button>
                </div>
                {% empty %}
                <p class="small text-muted mb-0">You are not a member of any teams. <a href="{% url 'team-list' %}">Explore teams</a>.</p>
                {% endfor %}
            </div>
        </div>
        {% endif %}

        <div class="card p-4">
            <h5 class="h6 mb-3">Information</h5>
            <ul class="list-unstyled small mb-0">
                <li class="mb-2"><span class="text-muted">Saved on:</span> {{ bookmark.created_at|date:"F d, Y H:i" }}</li>
                <li class="mb-2"><span class="text-muted">Last updated:</span> {{ bookmark.updated_at|date:"F d, Y H:i" }}</li>
                <li><span class="text-muted">Saved by:</span> {{ bookmark.user.username }}</li>
            </ul>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function toggleEdit(type) {
    const display = document.getElementById(type + '-display');
    const edit = document.getElementById(type + '-edit');
    if (!display || !edit) return;
    
    if (display.classList.contains('d-none')) {
        display.classList.remove('d-none');
        edit.classList.add('d-none');
    } else {
        display.classList.add('d-none');
        edit.classList.remove('d-none');
    }
}

document.querySelectorAll('.share-toggle').forEach(button => {
    button.addEventListener('click', async function() {
        const url = this.getAttribute('data-url');
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token }}',
                'Content-Type': 'application/json'
            }
        });
        const data = await response.json();
        if (data.shared) {
            this.textContent = 'Shared';
            this.classList.remove('btn-outline-primary');
            this.classList.add('btn-primary');
        } else {
            this.textContent = 'Share';
            this.classList.remove('btn-primary');
            this.classList.add('btn-outline-primary');
        }
    });
});

// Polling for summary and extraction
const bookmarkId = "{{ bookmark.id }}";
const apiUrl = `/api/bookmarks/${bookmarkId}/`;
let pollInterval;

async function checkStatus() {
    try {
        const response = await fetch(apiUrl);
        if (!response.ok) return;
        
        const data = await response.json();
        let allDone = true;

        // Check Summary
        if (data.summary && data.summary.content) {
            const container = document.getElementById('summary-container');
            const actions = document.getElementById('summary-actions');
            if (document.getElementById('summary-loading')) {
                container.innerHTML = `
                    <div id="summary-display" class="p-3 border rounded shadow-sm bg-white">
                        ${data.summary.content}
                    </div>
                    {% if bookmark.user == request.user %}
                    <div id="summary-edit" class="d-none">
                        <form action="{% url 'summary-update' bookmark.pk %}" method="post">
                            {% csrf_token %}
                            <textarea name="content" class="form-control mb-2" rows="4">${data.summary.content}</textarea>
                            <div class="d-flex gap-2">
                                <button type="submit" class="btn btn-primary btn-sm">Save</button>
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="toggleEdit('summary')">Cancel</button>
                            </div>
                        </form>
                    </div>
                    {% endif %}
                `;
                actions.classList.remove('d-none');
            }
        } else {
            allDone = false;
        }

        // Check Extraction
        if (data.extraction && data.extraction.content_text) {
            const container = document.getElementById('extraction-container');
            const actions = document.getElementById('extraction-actions');
            if (document.getElementById('extraction-loading')) {
                // Convert newlines to <br> for simple display, or use linebreaks style
                const formattedContent = data.extraction.content_text.replace(/\n/g, '<br>');
                container.innerHTML = `
                    <div id="extraction-display" class="extraction-content text-muted small" style="max-height: 500px; overflow-y: auto;">
                        ${formattedContent}
                    </div>
                    {% if bookmark.user == request.user %}
                    <div id="extraction-edit" class="d-none">
                        <form action="{% url 'extraction-update' bookmark.pk %}" method="post">
                            {% csrf_token %}
                            <textarea name="content_text" class="form-control mb-2" rows="15">${data.extraction.content_text}</textarea>
                            <div class="d-flex gap-2">
                                <button type="submit" class="btn btn-primary btn-sm">Save</button>
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="toggleEdit('extraction')">Cancel</button>
                            </div>
                        </form>
                    </div>
                    {% endif %}
                `;
                actions.classList.remove('d-none');
            }
        } else {
            allDone = false;
        }

        // Update Title if it was empty
        const titleEl = document.getElementById('bookmark-title');
        if (data.title && (titleEl.textContent === data.url || titleEl.textContent === '')) {
            titleEl.textContent = data.title;
        }

        if (allDone) {
            clearInterval(pollInterval);
        }
    } catch (error) {
        console.error('Error polling status:', error);
    }
}

// Start polling if anything is missing
if (document.getElementById('summary-loading') || document.getElementById('extraction-loading')) {
    pollInterval = setInterval(checkStatus, 3000);
}
</script>
{% endblock %}