<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <title>SynergyMed – Производи</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <th:block th:replace="fragments/header :: headerStyles"></th:block>
    <style>
        :root { --teal-1:#20b2aa; --teal-2:#48d1cc; --muted:#6c757d; --text:#1f2937;
            --shadow:0 20px 40px rgba(0,0,0,0.10); --shadow-sm:0 6px 18px rgba(0,0,0,0.08); }
        *{margin:0;padding:0;box-sizing:border-box}
        body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;min-height:100vh;
            background:linear-gradient(135deg,#a4ecba 0%,#fefeff 100%);color:var(--text)}
        .site-header{position:sticky;top:0;left:0;right:0;width:100%;border-radius:0;z-index:1000;background:#fff;box-shadow:0 2px 10px rgba(0,0,0,.1)}
        .page{width:100%;max-width:1200px;margin:0 auto;padding:24px}
        .card{background:#fff;border-radius:18px;box-shadow:var(--shadow);overflow:hidden;margin-bottom:28px}
        .card-header{background:linear-gradient(135deg,var(--teal-1),var(--teal-2));color:#fff;padding:20px 24px;
            display:flex;align-items:center;justify-content:space-between}
        .card-body{padding:22px}
        .btn{display:inline-block;border:none;cursor:pointer;text-decoration:none;padding:10px 16px;border-radius:12px;font-weight:600}
        .btn-primary{background:linear-gradient(135deg,var(--teal-1),var(--teal-2));color:#fff;box-shadow:0 10px 20px rgba(32,178,170,.25)}
        .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:18px}
        .item{background:#fff;border-radius:16px;box-shadow:var(--shadow-sm);overflow:hidden;display:flex;flex-direction:column}
        .thumb{width:100%;height:160px;object-fit:cover;display:block}
        .thumb-link{display:block; line-height:0}
        .content{padding:14px 16px;display:flex;flex-direction:column;gap:10px}
        .title{font-weight:700;margin-bottom:4px}
        .muted{color:var(--muted);font-size:.92rem;margin-bottom:6px}
        .price{font-weight:800}
        .btn-outline{background:#fff;border:2px solid rgba(32,178,170,.25);color:#20b2aa;padding:10px 14px;border-radius:10px;text-decoration:none;font-weight:600;transition:.2s ease;text-align:center}
        .btn-outline:hover{border-color:#20b2aa;box-shadow:0 6px 14px rgba(32,178,170,.18);background:#f8fffe}
        .toast-container{position:fixed;top:80px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:10px}
        .toast{background:linear-gradient(135deg,var(--teal-1),var(--teal-2));color:#fff;padding:16px 20px;border-radius:12px;box-shadow:var(--shadow);min-width:300px;transform:translateX(400px);opacity:0;transition:all .3s ease;display:flex;align-items:center;gap:10px}
        .toast.show{transform:translateX(0);opacity:1}
        .toast-close{background:none;border:none;color:#fff;font-size:1.2rem;cursor:pointer;padding:0;opacity:.8;transition:opacity .2s ease}
        .toast-close:hover{opacity:1}
        @media (max-width:560px){.page{padding:16px}.grid{grid-template-columns:1fr}.toast-container{right:10px;left:10px}.toast{min-width:auto}}
    </style>
</head>
<body>
<th:block th:replace="fragments/header :: siteHeader('Каталог')"></th:block>

<div class="toast-container" id="toastContainer"></div>

<div class="page">
    <div class="card">
        <div class="card-header">
            <span>Производи</span>
            <a sec:authorize="hasAnyRole('PHARMACIST','ADMIN')" class="btn btn-primary" th:href="@{/catalog/edit}">Измени ги достапните производи</a>
        </div>
        <div class="card-body">
            <div th:if="${#lists.isEmpty(medicines)}" class="muted">Нема достапни производи.</div>
            <div class="grid" th:unless="${#lists.isEmpty(medicines)}">
                <div class="item" th:each="m : ${medicines}">
                    <!-- Wrap the image in a link to details /catalog/{id} -->
                    <a class="thumb-link" th:href="@{/catalog/{id}(id=${m.id})}" aria-label="Детали за [[${m.name}]]">
                        <img class="thumb" th:if="${firstImageById != null}" th:src="${firstImageById[m.id]}" alt="слика">
                        <img class="thumb" th:if="${firstImageById == null}" src="/images/default-medicine.png" alt="слика">
                    </a>

                    <div class="content">
                        <div>
                            <div class="title" th:text="${m.name}">Лек</div>
                            <div class="muted" th:text="${m.dosageForm}">Форма</div>
                        </div>
                        <div class="price" th:text="${#numbers.formatDecimal(m.price, 1, 'COMMA', 2, 'POINT') + ' ден.'}">0.00 ден.</div>

                        <div style="display:flex; gap:8px; align-items:center;">
                            <a class="btn-outline" th:href="@{/catalog/{id}(id=${m.id})}">Детали</a>
                            <form th:action="@{/cart/add/{id}(id=${m.id})}" method="post" style="display:inline;">
                                <input type="hidden" th:if="${_csrf != null}" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">
                                <button type="submit" sec:authorize="hasRole('CLIENT')" class="btn-outline add-to-cart-btn" th:data-name="${m.name}">Додај во кошничка</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<th:block th:replace="fragments/header :: headerScripts"></th:block>
<script>
    function showToast(title, message, type = 'success') {
        const toastContainer = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = 'toast';
        const icon = type === 'success' ? '✅' : '❌';
        toast.innerHTML = `
          <div>${icon}</div>
          <div style="flex:1">
            <div style="font-weight:700;margin-bottom:2px;">${title}</div>
            <div style="opacity:.9">${message}</div>
          </div>
          <button class="toast-close" onclick="removeToast(this.parentElement)">×</button>
        `;
        toastContainer.appendChild(toast);
        setTimeout(() => toast.classList.add('show'), 100);
        setTimeout(() => removeToast(toast), 4000);
    }
    function removeToast(t){ t.classList.remove('show'); setTimeout(()=>t?.parentElement?.removeChild(t),300); }

    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('form[action*="/cart/add/"]').forEach(form => {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                const button = form.querySelector('.add-to-cart-btn');
                const name = button.getAttribute('data-name');
                const original = button.textContent;
                button.textContent = 'Се додава...';
                button.disabled = true;

                const fd = new FormData(form);
                fetch(form.action, {
                    method: 'POST',
                    body: fd,
                    credentials: 'same-origin',
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                })
                    .then(r => {
                        const ok = r.ok || r.redirected || (r.status >= 200 && r.status < 400);
                        if (!ok) throw new Error(`HTTP ${r.status}`);
                        showToast('Додадено во кошничката!', `${name} е додаден во кошничката.`, 'success');
                    })
                    .catch(() => showToast('Грешка','Неуспешно додавање во кошничката. Обидете се повторно.','error'))
                    .finally(() => { button.textContent = original; button.disabled = false; });
            });
        });
    });
</script>
</body>
</html>
