{% extends 'main/header.html' %}
{% load static %}

{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <title>Статистика</title>
    <style>
        :root {
            --primary-color: #2e652e;
            --primary-dark: #1f3f1f;
            --light-bg: #f5f5f5;
            --white: #ffffff;
            --text-dark: #333333;
            --text-light: #666666;
            --border-color: #e0e0e0;
        }

        /* Base Styles */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: var(--light-bg);
            color: var(--text-dark);
            line-height: 1.6;
        }

        /* Stats Page Container */
        .stats-wrapper {
            padding: 20px;
            max-width: 1400px;
            margin: 0 auto;
        }

        /* Main Container */
        .stats-container {
            background-color: var(--white);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            overflow: hidden;
            margin-bottom: 30px;
        }

        /* Header Section */
        .stats-header {
            background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),
                url('{% static "images/baner2.jpg" %}') center center / cover no-repeat;
            color: white;
            padding: 40px 20px;
            text-align: center;
        }

        .stats-main-title {
            font-size: 28px;
            font-weight: 700;
            margin: 0;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }

        .stats-subtitle {
            font-size: 16px;
            opacity: 0.9;
            margin-top: 8px;
            text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
        }

        /* Navigation */
        .back-button {
            margin: 20px;
        }

        .back-button a {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            background-color: var(--white);
            color: var(--primary-color);
            border-radius: 30px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(46, 101, 46, 0.2);
        }

        .back-button a:hover {
            background-color: #f0f7f0;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        /* Form Styles */
        .stats-form {
            padding: 0 20px 20px;
        }

        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            flex: 1;
            min-width: 0;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--primary-color);
            font-size: 14px;
        }

        .form-input {
            width: 75%;
            padding: 12px 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-size: 15px;
            background-color: var(--white);
            transition: all 0.2s ease;
        }

        .form-input:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 3px rgba(46, 101, 46, 0.1);
        }

        .form-actions {
            text-align: center;
            margin-top: 30px;
        }

        .action-button {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 14px 30px;
            background-color: var(--primary-color);
            color: var(--white);
            border: none;
            border-radius: 30px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 16px;
        }

        .action-button:hover {
            background-color: var(--primary-dark);
            transform: translateY(-2px);
        }

        /* Results Section */
        .results-container {
            display: flex;
            gap: 30px;
            padding: 20px;
        }

        /* Products List */
        .products-list {
            flex: 1;
            min-width: 300px;
            max-height: 500px;
            overflow-y: auto;
            background-color: var(--white);
            border-radius: 8px;
            padding: 15px;
            border: 1px solid var(--border-color);
        }

        .products-list h3 {
            color: var(--primary-color);
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }

        .product-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 12px;
            margin-bottom: 12px;
            border-radius: 6px;
            transition: all 0.2s ease;
            border: 1px solid var(--border-color);
        }

        .product-item:hover {
            background-color: #f8f8f8;
            border-color: var(--primary-color);
        }

        .product-item img {
            width: 50px;
            height: 50px;
            object-fit: contain;
            border-radius: 4px;
            border: 1px solid var(--border-color);
        }

        .product-info {
            flex: 1;
        }

        .product-info a {
            color: var(--primary-color);
            font-weight: 600;
            text-decoration: none;
        }

        .product-info a:hover {
            text-decoration: underline;
        }

        .product-meta {
            font-size: 12px;
            color: var(--text-light);
            margin-top: 3px;
        }

        /* Chart Container */
        .chart-container {
            flex: 2;
            min-width: 300px;
            background-color: var(--white);
            border-radius: 8px;
            padding: 20px;
            border: 1px solid var(--border-color);
        }

        .chart-container h3 {
            color: var(--primary-color);
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }

        .chart-wrapper {
            position: relative;
            height: 400px;
            width: 100%;
        }

        /* Empty State */
        .no-results {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .no-results i {
            font-size: 40px;
            margin-bottom: 15px;
            color: var(--text-light);
        }

        /* Stats Summary */
        .stats-summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin: 20px;
        }

        .summary-card {
            background-color: var(--white);
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            border: 1px solid var(--border-color);
        }

        .summary-card h4 {
            color: var(--primary-color);
            margin: 0 0 10px;
            font-size: 16px;
        }

        .summary-card .value {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 5px;
        }

        .summary-card .label {
            font-size: 12px;
            color: var(--text-light);
        }

        /* Promo Banner */
        .promo-banner {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: white;
            padding: 15px 20px;
            border-radius: 8px;
            margin: 20px;
            display: flex;
            align-items: center;
        }

        .promo-banner .banner-content {
            flex: 1;
        }

        .promo-banner h2 {
            margin: 0;
            font-size: 20px;
        }

        .promo-banner p {
            margin: 5px 0 0;
            opacity: 0.9;
            font-size: 14px;
        }

        /* Responsive Adjustments */
        @media (max-width: 1200px) {
            .results-container {
                flex-direction: column;
            }

            .products-list {
                max-height: 300px;
            }
        }

        @media (max-width: 768px) {
            .stats-main-title {
                font-size: 24px;
            }

            .stats-subtitle {
                font-size: 14px;
            }

            .form-row {
                flex-direction: column;
                gap: 15px;
            }

            .results-container {
                padding: 15px;
                gap: 20px;
            }

            .chart-wrapper {
                height: 350px;
            }

            .promo-banner {
                flex-direction: column;
                text-align: center;
            }
        }

        @media (max-width: 480px) {
            .stats-wrapper {
                padding: 10px;
            }

            .stats-header {
                padding: 30px 15px;
            }

            .back-button {
                margin: 15px;
            }

            .stats-form {
                padding: 0 15px 15px;
            }

            .action-button {
                width: 100%;
                justify-content: center;
            }

            .product-item {
                padding: 10px;
            }

            .chart-wrapper {
                height: 300px;
            }

            .stats-summary {
                grid-template-columns: 1fr;
            }
        }

        /* Animations */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .stats-container {
            animation: fadeIn 0.4s ease-out;
        }
    </style>
</head>
<body>

<div class="stats-wrapper">
    <div class="stats-container">
        <!-- Header Section -->
        <div class="stats-header">
            <h1 class="stats-main-title">Ценовна историја</h1>
            <p class="stats-subtitle">Анализирајте ги промените на цените низ времето</p>
        </div>

        <div class="back-button">
            <a href="{% url 'home' %}">
                <i class="fas fa-arrow-left"></i> Назад кон почетна
            </a>
        </div>

        <!-- Search Form -->
        <form method="get" class="stats-form" id="statsSearchForm">
            <div class="form-row">
                <div class="form-group">
                    <label for="store-select"><i class="fas fa-store"></i> Продавница:</label>
                    <select name="store" id="store-select" required class="form-input" style="width: 79%">
                        <option value="">Избери продавница...</option>
                        <option value="Vero" {% if store == "Vero" %}selected{% endif %}>Vero</option>
                        <option value="Ramstore" {% if store == "Ramstore" %}selected{% endif %}>Ramstore</option>
                        <option value="Reptil" {% if store == "Reptil" %}selected{% endif %}>Reptil</option>
                        <option value="Zito" {% if store == "Zito" %}selected{% endif %}>Zito</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="product-input"><i class="fas fa-search"></i> Продукт:</label>
                    <input type="text" id="product-input" name="query" placeholder="напр. ВОДА" required
                           value="{{ query|default:'' }}" class="form-input" autocomplete="off">
                    <div id="stats-suggestions" style="position: absolute; background: white; border: 1px solid #ddd; border-radius: 5px; width: 75%; max-height: 200px; overflow-y: auto; display: none; z-index: 2; margin-top: 5px;"></div>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="start-date"><i class="far fa-calendar-alt"></i> Од датум:</label>
                    <input type="date" id="start-date" name="start_date" class="form-input"
                           value="{{ start_date|default:'' }}">
                </div>
                <div class="form-group">
                    <label for="end-date"><i class="far fa-calendar-alt"></i> До датум:</label>
                    <input type="date" id="end-date" name="end_date" class="form-input"
                           value="{{ end_date|default:'' }}">
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" class="action-button">
                    <i class="fas fa-chart-line"></i> Прикажи историја
                </button>
            </div>
        </form>

        {% if similar_products and not exact_match %}
            <!-- Results Section -->
            <div class="results-container">
                <!-- Products List -->
                <div class="products-list">
                    <h3><i class="fas fa-list-ul"></i> Слични производи во {{ store }}:</h3>
                    {% for product, similarity in similar_products %}
                        <div class="product-item">
                            {% if store == "Vero" %}
                                <img src="{% static 'images/vero_logo1.png' %}" alt="{{ product }}">
                            {% elif store == "Ramstore" %}
                                <img src="{% static 'images/ramstore_logo.png' %}" alt="{{ product }}">
                            {% elif store == "Reptil" %}
                                <img src="{% static 'images/reptil_logo.jpg' %}" alt="{{ product }}">
                            {% else %}
                                <img src="{% static 'images/no-image.png' %}" alt="{{ product }}">
                            {% endif %}
                            <div class="product-info">
                                <a href="?store={{ store|urlencode }}&query={{ query|urlencode }}&selected_product={{ product|urlencode }}">
                                    {{ product }}
                                </a>
                                <div class="product-meta">
                                    Сличност: {{ similarity|floatformat:2 }}%
                                </div>
                            </div>
                        </div>
                    {% endfor %}
                </div>

                <!-- Chart Container -->
                <div class="chart-container">
                    {% if matched_name %}
                        <h3><i class="fas fa-chart-line"></i> Ценовна историја за {{ matched_name }}</h3>
                        <div class="chart-wrapper">
                            <canvas id="priceChart"></canvas>
                        </div>
                    {% else %}
                        <div class="no-results">
                            <i class="fas fa-exclamation-circle"></i>
                            <p>Не се пронајдени производи за "{{ query }}" во {{ store }}.</p>
                        </div>
                    {% endif %}
                </div>
            </div>
        {% endif %}

        <!-- Stats Summary -->
        {% if chart_data %}
        <div class="promo-banner">
            <div class="banner-content">
                <h2>Статистички преглед</h2>
                <p>Клучни метрики за вашиот избор</p>
            </div>
            <i class="fas fa-chart-pie"></i>
        </div>

        <div class="stats-summary">
            <div class="summary-card">
                <h4>Тековна цена</h4>
                <div class="value">
                    {% if current_price %}
                        {{ current_price }} ден
                    {% else %}
                        -
                    {% endif %}
                </div>
                <div class="label">Последна забележана</div>
            </div>
            <div class="summary-card">
                <h4>Најниска цена</h4>
                <div class="value">
                    {% if min_price %}
                        {{ min_price }} ден
                    {% else %}
                        -
                    {% endif %}
                </div>
                <div class="label">Во избраниот период</div>
            </div>
            <div class="summary-card">
                <h4>Највисока цена</h4>
                <div class="value">
                    {% if max_price %}
                        {{ max_price }} ден
                    {% else %}
                        -
                    {% endif %}
                </div>
                <div class="label">Во избраниот период</div>
            </div>
            <div class="summary-card">
                <h4>Просечна цена</h4>
                <div class="value">
                    {% if avg_price %}
                        {{ avg_price|floatformat:2 }} ден
                    {% else %}
                        -
                    {% endif %}
                </div>
                <div class="label">Во избраниот период</div>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
     function transliterateLatinToCyrillic(text) {
        const map = {
            'dzh': 'џ', 'dzs': 'џ', 'dsh': 'џ',
            'zh': 'ж', 'ch': 'ч', 'sh': 'ш', 'lj': 'љ', 'nj': 'њ', 'kj': 'ќ', 'dj': 'ѓ',
            'zs': 'ж', 'hs': 'ш', 'cx': 'ч', 'sx': 'ш', 'jx': 'ж',
            'tz': 'ц', 'ts': 'ц', 'tc': 'ц', 'dz': 'џ',
            'a': 'а', 'b': 'б', 'v': 'в', 'g': 'г', 'd': 'д', 'e': 'е', 'z': 'з', 'i': 'и',
            'j': 'ј', 'k': 'к', 'l': 'л', 'm': 'м', 'n': 'н', 'o': 'о', 'p': 'п', 'r': 'р',
            's': 'с', 't': 'т', 'u': 'у', 'f': 'ф', 'h': 'х', 'c': 'ц',
            'y': 'ј', 'w': 'в', 'x': 'кс', 'q': 'к',
            'ia': 'ја', 'ie': 'је', 'io': 'јо', 'iu': 'ју'
        };

        const typoPatterns = [
            {pattern: /sampon/gi, replace: 'shampon'},
            {pattern: /cresi/gi, replace: 'creshi'},
            {pattern: /stipki/gi, replace: 'shtipki'},
            {pattern: /sch/gi, replace: 'sh'},
            {pattern: /ck/gi, replace: 'k'},
            {pattern: /ph/gi, replace: 'f'},
            {pattern: /th/gi, replace: 't'},
            {pattern: /([a-z]),([a-z])/gi, replace: '$1$2'},
            {pattern: /([a-z])\.([a-z])/gi, replace: '$1$2'},
            {pattern: /([a-z])\1/gi, replace: '$1'}
        ];

        let normalizedText = text.toLowerCase();
        for (const {pattern, replace} of typoPatterns) {
            normalizedText = normalizedText.replace(pattern, replace);
        }

        let result = '';
        let i = 0;
        while (i < normalizedText.length) {
            if (map[normalizedText.substring(i, i + 3)]) {
                result += map[normalizedText.substring(i, i + 3)];
                i += 3;
            } else if (map[normalizedText.substring(i, i + 2)]) {
                result += map[normalizedText.substring(i, i + 2)];
                i += 2;
            } else if (map[normalizedText[i]]) {
                result += map[normalizedText[i]];
                i++;
            } else {
                result += normalizedText[i];
                i++;
            }
        }
        return result;
    }

    document.addEventListener('DOMContentLoaded', function() {
        const productInput = document.getElementById('product-input');
        const statsSuggestions = document.getElementById('stats-suggestions');
        const statsSearchForm = document.getElementById('statsSearchForm');
        const storeSelect = document.getElementById('store-select');

        // Handle form submission with transliteration
        statsSearchForm.addEventListener('submit', function(e) {
            e.preventDefault();

            const originalQuery = productInput.value.trim();
            const cyrillicQuery = transliterateLatinToCyrillic(originalQuery);
            const selectedStore = storeSelect.value;

            // Create hidden inputs for the original and transliterated queries
            const originalInput = document.createElement('input');
            originalInput.type = 'hidden';
            originalInput.name = 'original_query';
            originalInput.value = originalQuery;
            statsSearchForm.appendChild(originalInput);

            const cyrillicInput = document.createElement('input');
            cyrillicInput.type = 'hidden';
            cyrillicInput.name = 'cyrillic_query';
            cyrillicInput.value = cyrillicQuery;
            statsSearchForm.appendChild(cyrillicInput);

            statsSearchForm.submit();
        });

        // Handle input for suggestions
        productInput.addEventListener('input', function() {
            const query = this.value.trim();
            const store = storeSelect.value;

            if (query.length < 2 || !store) {
                statsSuggestions.style.display = 'none';
                return;
            }

            fetch(`/search-suggestions/?q=${encodeURIComponent(query)}&store=${encodeURIComponent(store)}`)
                .then(response => response.json())
                .then(data => {
                    statsSuggestions.innerHTML = '';
                    if (data.suggestions.length > 0) {
                        data.suggestions.forEach(suggestion => {
                            const div = document.createElement('div');
                            div.textContent = suggestion;
                            div.style.padding = '8px 12px';
                            div.style.cursor = 'pointer';
                            div.addEventListener('click', function() {
                                productInput.value = suggestion;
                                statsSuggestions.style.display = 'none';
                                statsSearchForm.dispatchEvent(new Event('submit'));
                            });
                            statsSuggestions.appendChild(div);
                        });
                        statsSuggestions.style.display = 'block';
                    } else {
                        statsSuggestions.style.display = 'none';
                    }
                });
        });

        document.addEventListener('click', function(e) {
            if (!productInput.contains(e.target) && !statsSuggestions.contains(e.target)) {
                statsSuggestions.style.display = 'none';
            }
        });

        productInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                statsSuggestions.style.display = 'none';
                statsSearchForm.dispatchEvent(new Event('submit'));
            }
        });

        storeSelect.addEventListener('change', function() {
            statsSuggestions.style.display = 'none';
        });

        {% if chart_data %}
            const ctx = document.getElementById('priceChart').getContext('2d');

            const labels = [
                {% for item in chart_data %}
                    "{{ item.date|date:'d.m.Y' }}"{% if not forloop.last %},{% endif %}
                {% endfor %}
            ];

            const prices = [
                {% for item in chart_data %}
                    {{ item.price }}{% if not forloop.last %},{% endif %}
                {% endfor %}
            ];

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Цена (МКД)',
                        data: prices,
                        borderColor: '#2e652e',
                        backgroundColor: 'rgba(46, 101, 46, 0.1)',
                        borderWidth: 3,
                        tension: 0.1,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return 'Цена: ' + context.parsed.y + ' ден';
                                }
                            }
                        }
                    }
                }
            });
        {% endif %}

        const startDate = document.getElementById('start-date');
        const endDate = document.getElementById('end-date');

        if (startDate && endDate) {
            statsSearchForm.addEventListener('submit', function(e) {
                if (startDate.value && endDate.value && startDate.value > endDate.value) {
                    alert('Крајниот датум мора да биде после почетниот датум.');
                    e.preventDefault();
                }
            });
        }
    });
</script>
</body>
{% endblock %}
</html>