{% extends "core/base.html" %}
{% load static %}
{% block title %}Business Insights - SwiftPOS{% endblock %}
{% block topbar_title %}Business Insights{% endblock %}

{% block content %}
<div class="container-fluid py-4">

    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <div>
            <h5 class="mb-0 fw-bold">💡 Business Insights</h5>
            <p class="text-muted small mb-0">Auto-generated insights based on your company data.</p>
        </div>
        <div class="d-flex gap-2 align-items-center">
            {% if unread_count > 0 %}
            <span class="badge bg-danger rounded-pill" style="font-size:.75rem;">{{ unread_count }} unread</span>
            {% endif %}
            {% if high_priority > 0 %}
            <span class="badge bg-warning text-dark rounded-pill" style="font-size:.75rem;">{{ high_priority }} urgent</span>
            {% endif %}
            {% if user_role in 'admin manager' %}
            <form method="post" action="{% url 'analytics:mark_all_read' %}">
                {% csrf_token %}
                <button type="submit" class="btn btn-sm btn-outline-secondary">
                    <i class="fas fa-check-double me-1"></i> Mark All Read
                </button>
            </form>
            {% endif %}
        </div>
    </div>

    <!-- Filters -->
    <div class="mb-3">
        <form method="get" class="d-flex gap-2 flex-wrap align-items-center">
            <select name="category" class="form-select form-select-sm" style="max-width:180px;" onchange="this.form.submit()">
                <option value="">All Categories</option>
                {% for val, label in categories %}
                    <option value="{{ val }}" {% if category_filter == val %}selected{% endif %}>{{ label }}</option>
                {% endfor %}
            </select>
            <select name="priority" class="form-select form-select-sm" style="max-width:150px;" onchange="this.form.submit()">
                <option value="">All Priorities</option>
                {% for val, label in priorities %}
                    <option value="{{ val }}" {% if priority_filter == val %}selected{% endif %}>{{ label }}</option>
                {% endfor %}
            </select>
            {% if category_filter or priority_filter %}
            <a href="{% url 'analytics:insights' %}" class="btn btn-sm btn-outline-secondary">Clear</a>
            {% endif %}
        </form>
    </div>

    <!-- Insight Cards -->
    {% if page_obj %}
    <div class="row g-3">
        {% for insight in page_obj %}
        <div class="col-md-6 col-xl-4">
            <div class="card border-0 shadow-sm h-100 sp-insight-card border-start border-4
                {% if insight.color == 'green' %}border-success{% elif insight.color == 'red' %}border-danger{% elif insight.color == 'yellow' %}border-warning{% else %}border-primary{% endif %}
                {% if insight.is_read %}opacity-60{% endif %}"
                data-insight-id="{{ insight.id }}">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="d-flex align-items-center gap-2">
                            <div class="insight-icon rounded-circle d-flex align-items-center justify-content-center
                                {% if insight.color == 'green' %}bg-success-subtle text-success{% elif insight.color == 'red' %}bg-danger-subtle text-danger{% elif insight.color == 'yellow' %}bg-warning-subtle text-warning{% else %}bg-primary-subtle text-primary{% endif %}"
                                style="width:36px;height:36px;min-width:36px;">
                                <i class="fas {{ insight.icon|default:'fa-lightbulb' }} fa-sm"></i>
                            </div>
                            <span class="badge rounded-pill
                                {% if insight.priority == 'high' %}bg-danger{% elif insight.priority == 'medium' %}bg-warning text-dark{% else %}bg-secondary{% endif %}">
                                {{ insight.get_priority_display }}
                            </span>
                        </div>
                        <div class="d-flex align-items-center gap-1">
                            <span class="badge bg-light text-muted border">{{ insight.get_category_display }}</span>
                            {% if not insight.is_read %}
                            <span class="badge bg-primary rounded-pill fs-small" title="Unread">●</span>
                            {% endif %}
                        </div>
                    </div>
                    <h6 class="fw-bold mb-1">{{ insight.title }}</h6>
                    <p class="text-muted small mb-2">{{ insight.description }}</p>
                    <div class="d-flex justify-content-between align-items-center mt-auto">
                        <small class="text-muted">{{ insight.created_at|timesince }} ago</small>
                        <button class="btn btn-sm btn-outline-secondary mark-read-btn"
                                data-id="{{ insight.id }}"
                                data-url="{% url 'analytics:insight_read' insight.id %}">
                            <i class="fas {% if insight.is_read %}fa-eye-slash{% else %}fa-eye{% endif %} fa-xs me-1"></i>
                            {% if insight.is_read %}Unread{% else %}Read{% endif %}
                        </button>
                    </div>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>

    <!-- Pagination -->
    {% if page_obj.has_other_pages %}
    <nav class="mt-4">
        <ul class="pagination justify-content-center mb-0">
            {% if page_obj.has_previous %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.previous_page_number }}&category={{ category_filter }}&priority={{ priority_filter }}">&laquo;</a>
            </li>
            {% endif %}
            <li class="page-item disabled">
                <span class="page-link">{{ page_obj.number }} / {{ page_obj.paginator.num_pages }}</span>
            </li>
            {% if page_obj.has_next %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.next_page_number }}&category={{ category_filter }}&priority={{ priority_filter }}">&raquo;</a>
            </li>
            {% endif %}
        </ul>
    </nav>
    {% endif %}

    {% else %}
    <div class="card border-0 shadow-sm">
        <div class="card-body text-center py-5">
            <i class="fas fa-lightbulb fa-3x text-muted opacity-25 d-block mb-3"></i>
            <h6 class="text-muted">No insights yet</h6>
            <p class="text-muted small mb-0">Insights are generated automatically every day. Run <code>python manage.py generate_insights</code> to generate them now.</p>
        </div>
    </div>
    {% endif %}
</div>

<style>
.sp-insight-card { transition: transform 0.2s, box-shadow 0.2s; }
.sp-insight-card:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,.1) !important; }
.opacity-60 { opacity: 0.6; }
.fs-small { font-size: 0.6rem; }
</style>

<script>
document.querySelectorAll('.mark-read-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const id = this.dataset.id;
        const url = this.dataset.url;
        const card = document.querySelector(`[data-insight-id="${id}"]`);
        fetch(url, {
            method: 'POST',
            headers: {'X-CSRFToken': '{{ csrf_token }}', 'Content-Type': 'application/json'}
        })
        .then(r => r.json())
        .then(data => {
            card.classList.toggle('opacity-60', data.is_read);
            this.innerHTML = data.is_read
                ? '<i class="fas fa-eye-slash fa-xs me-1"></i>Unread'
                : '<i class="fas fa-eye fa-xs me-1"></i>Read';
        });
    });
});
</script>
{% endblock %}
