<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <title th:text="${mode=='create' ? 'Креирај нов брендиран лек' : 'Измени Брендиран Лек'}">SynergyMed – Брендиран Лек</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Global header styles (fragment) -->
    <th:block th:replace="fragments/header :: headerStyles"></th:block>

    <style>
        :root {
            --teal-1:#20b2aa; --teal-2:#48d1cc;
            --bg:#fefeff; --card:#ffffff;
            --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);
        }

        /* Full-width global header - FIXED STYLING (override fragment defaults) */
        .site-header{
            position:sticky;
            top:0;
            left:0;
            right:0;
            width:100%;
            border-radius:0;
            margin:0;
            z-index:1000;
            background:#ffffff !important;
            box-shadow:0 2px 10px rgba(0,0,0,0.1);
        }

        .page{width:100%; max-width:1200px; padding:28px; margin:0 auto}

        /* Card wrapper */
        .card{
            background:var(--card);
            border-radius:18px;
            box-shadow:var(--shadow);
            margin-bottom:28px;
            overflow:hidden;
        }
        .card-header{
            background:linear-gradient(135deg,var(--teal-1),var(--teal-2));
            color:#fff;
            padding:20px 24px;
            display:flex; justify-content:space-between; align-items:center;
            font-size:1.3rem; font-weight:600;
        }
        .card-body{padding:22px}

        .btn{
            display:inline-block; border:none; cursor:pointer; text-decoration:none;
            padding:12px 16px; border-radius:12px; font-weight:600;
            letter-spacing:.5px; transition:.2s ease;
        }
        .btn-primary{
            background:linear-gradient(135deg,var(--teal-1),var(--teal-2));
            color:#fff;
            box-shadow:0 10px 20px rgba(32,178,170,.25);
        }
        .btn-primary:hover{transform:translateY(-2px)}
        .btn-secondary{
            background:#fff; color:#111; border:2px solid rgba(32,178,170,.25);
        }

        /* Form layout */
        .row{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px}
        .row-1{display:grid;grid-template-columns:1fr;gap:16px;margin-bottom:6px}
        label{display:block;margin-bottom:8px;color:#334155;font-weight:600;font-size:.95rem}
        input,select,textarea{width:100%;padding:14px 12px;border:2px solid #e6ebf0;border-radius:12px;background:#f8fafc;transition:.2s ease;font-size:1rem}
        textarea{min-height:110px}
        input:focus,select:focus,textarea:focus{outline:none;border-color:var(--teal-1);background:#fff;box-shadow:0 0 0 3px rgba(32,178,170,.12)}
        .hint{color:var(--muted);font-size:.86rem;margin-top:4px}
        .actions{display:flex;gap:12px;padding-top:12px;flex-wrap:wrap}

        /* Images grid */
        .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:12px}
        .img-card{position:relative;background:#f8fafc;border:1px solid #e6ebf0;border-radius:12px;padding:8px}
        .thumb{width:100%;height:110px;object-fit:cover;border-radius:8px;display:block}

        @media (max-width:720px){.row{grid-template-columns:1fr}}
        @media (max-width:560px){.page{padding:16px}}
    </style>
</head>
<body>

<!-- Global header (fragment with parameters) -->
<th:block th:replace="fragments/header :: siteHeader('Брендирани лекови')"></th:block>

<div class="page">
    <div class="card">
        <div class="card-header">
            <span th:text="${mode=='create' ? 'Креирај нов брендиран лек' : 'Измени Брендиран Лек'}">Формулар</span>
        </div>

        <div class="card-body">
            <form th:action="@{/admin/branded-medicines/save}" method="post" enctype="multipart/form-data" id="saveForm">
                <input type="hidden" name="id" th:if="${mode=='edit'}" th:value="${bm.id}"/>

                <div class="row">
                    <div>
                        <label>Производител</label>
                        <select name="manufacturerId" required>
                            <option th:if="${mode=='create'}" value="" disabled selected>Избери производител</option>
                            <option th:each="m : ${manufacturers}"
                                    th:value="${m.id}"
                                    th:text="${m.company.companyName}"
                                    th:selected="${mode=='edit' and bm.manufacturer != null and m.id == bm.manufacturer.id}">
                                Производител
                            </option>
                        </select>
                        <div class="hint">Избери ја компанијата производител на Брендираниот Лек</div>
                    </div>
                    <div>
                        <label>Цена</label>
                        <input type="number" step="0.01" name="price" th:value="${mode=='edit' ? bm.price : ''}" required/>
                    </div>
                </div>

                <div class="row">
                    <div>
                        <label>Форма на лекот</label>
                        <input type="text" name="dosageForm" th:value="${mode=='edit' ? bm.dosageForm : ''}" required/>
                    </div>
                    <div>
                        <label>Јачина</label>
                        <input type="text" name="strength" th:value="${mode=='edit' ? bm.strength : ''}" required/>
                    </div>
                </div>

                <div class="row">
                    <div>
                        <label>Земја на потекло</label>
                        <input type="text" name="originCountry" th:value="${mode=='edit' ? bm.originCountry : ''}"/>
                    </div>
                    <div>
                        <label>Име</label>
                        <input type="text" name="name" th:value="${mode=='edit' ? bm.name : ''}" required/>
                    </div>
                </div>

                <div class="row-1">
                    <div>
                        <label>Опис</label>
                        <textarea name="description" th:text="${mode=='edit' ? bm.description : ''}"></textarea>
                    </div>
                    <div>
                        <label>Нови слики</label>
                        <input type="file" id="newImages" name="images" multiple accept="image/*"/>
                        <div class="hint">Изберете повеќе слики да ги прикачите, се зачувуваат само по кликнување на копчето „Зачувај“</div>
                        <div id="preview" class="grid" style="margin-top:12px;"></div>
                    </div>
                </div>

                <!-- Existing images (edit mode) -->
                <div th:if="${mode=='edit' and images != null and !images.isEmpty()}" style="margin-top:18px;">
                    <div class="grid">
                        <div class="img-card" th:each="img : ${images}">
                            <img class="thumb" th:src="@{${img.image}}" alt="слика">
                            <input type="hidden" name="removeImageIds" th:value="${img.id}" disabled>
                            <div style="display:flex;justify-content:space-between;align-items:center;margin-top:6px;">
                                <button type="button" class="btn-remove-existing"
                                        th:attr="data-id=${img.id}"
                                        style="background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:4px 8px;cursor:pointer;">
                                    Одстрани
                                </button>
                                <label style="margin-left:8px;">
                                    <input type="radio" name="mainPick" th:value="${'existing:'+img.id}"
                                           th:checked="${img.mainImage}">
                                    Главна слика
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Hidden fields managed by JS -->
                <input type="hidden" id="mainExistingId" name="mainExistingId">
                <input type="hidden" id="mainNewIndex"   name="mainNewIndex">

                <div class="actions">
                    <button class="btn btn-primary" type="submit">Зачувај</button>
                    <a class="btn btn-secondary" th:href="@{/admin/branded-medicines}">Откажи</a>
                </div>
            </form>

            <script>
                // Hidden fields for the server (avoid "undefined")
                const mainExistingId = document.getElementById('mainExistingId');
                const mainNewIndex   = document.getElementById('mainNewIndex');

                // 1) Existing remove buttons toggle hidden remove ids
                function wireExistingRemoveButtons() {
                    document.querySelectorAll('.btn-remove-existing').forEach(btn => {
                        btn.addEventListener('click', () => {
                            const card = btn.closest('.img-card');
                            const hidden = card.querySelector('input[type="hidden"][name="removeImageIds"]');
                            const wasEnabled = !hidden.disabled;
                            hidden.disabled = wasEnabled ? true : false;
                            btn.textContent = wasEnabled ? 'Отстрани' : 'Врати';
                            btn.style.borderColor = wasEnabled ? '#e5e7eb' : '#f0caca';
                            btn.style.color = wasEnabled ? '#111' : '#b3261e';

                            // If this was main and now removed, clear main and pick a fallback below
                            const radio = card.querySelector('input[type="radio"][name="mainPick"]');
                            if (!hidden.disabled && radio && radio.checked) {
                                radio.checked = false;
                                mainExistingId.value = '';
                                chooseFallbackMain();
                            }
                        });
                    });
                }
                wireExistingRemoveButtons();

                // 2) One radio group across existing and new
                document.addEventListener('change', (e) => {
                    const t = e.target;
                    if (t && t.name === 'mainPick' && t.type === 'radio') {
                        const v = String(t.value || '');
                        if (v.startsWith('existing:')) {
                            mainExistingId.value = v.split(':')[1] || '';
                            mainNewIndex.value = '';
                        } else if (v.startsWith('new:')) {
                            mainNewIndex.value = v.split(':')[1] || '';
                            mainExistingId.value = '';
                        }
                    }
                });

                // 3) Aggregate multiple selections with DataTransfer + FileReader previews
                const fileInput = document.getElementById('newImages');
                const preview   = document.getElementById('preview');
                const saveForm  = document.getElementById('saveForm');
                let aggregated  = [];

                function syncInputFiles() {
                    const dt = new DataTransfer();
                    aggregated.forEach(f => dt.items.add(f));
                    fileInput.files = dt.files;
                }

                function buildPreviewCard(dataUrl, fileName, idx) {
                    const card = document.createElement('div');
                    card.className = 'img-card';
                    card.innerHTML = `
        <img class="thumb" src="${dataUrl}" alt="${fileName}">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-top:6px;">
          <label>
            <input type="radio" name="mainPick" value="new:${idx}"> Главна (нова)
          </label>
          <button type="button" class="remove-new-btn" data-index="${idx}"
                  style="background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:4px 8px;cursor:pointer;">
            Отстрани
          </button>
        </div>
      `;
                    return card;
                }

                function renderPreview() {
                    preview.innerHTML = '';
                    aggregated.forEach((file, idx) => {
                        const reader = new FileReader();
                        reader.onload = e => {
                            const card = buildPreviewCard(e.target.result, file.name, idx);
                            preview.appendChild(card);
                            const removeBtn = card.querySelector('.remove-new-btn');
                            removeBtn.addEventListener('click', () => {
                                const i = parseInt(removeBtn.getAttribute('data-index'), 10);
                                if (mainNewIndex.value === String(i)) mainNewIndex.value = '';
                                aggregated.splice(i, 1);
                                syncInputFiles();
                                renderPreview();
                                if (!mainExistingId.value && !mainNewIndex.value) chooseFallbackMain();
                            });
                        };
                        reader.readAsDataURL(file);
                    });

                    if (!mainExistingId.value && !mainNewIndex.value && aggregated.length > 0) {
                        mainNewIndex.value = '0';
                        const first = preview.querySelector('input[type="radio"][name="mainPick"][value="new:0"]');
                        if (first) first.checked = true;
                    }
                }

                function chooseFallbackMain() {
                    const existingCards = document.querySelectorAll('.img-card input[type="hidden"][name="removeImageIds"]');
                    for (const hidden of existingCards) {
                        if (hidden.disabled) {
                            const card = hidden.closest('.img-card');
                            const r = card.querySelector('input[type="radio"][name="mainPick"][value^="existing:"]');
                            if (r) {
                                r.checked = true;
                                const v = r.value.split(':')[1] || '';
                                mainExistingId.value = v;
                                mainNewIndex.value = '';
                                return;
                            }
                        }
                    }
                    const newRadio = preview.querySelector('input[type="radio"][name="mainPick"][value^="new:"]');
                    if (newRadio) {
                        newRadio.checked = true;
                        mainExistingId.value = '';
                        mainNewIndex.value = newRadio.value.split(':')[1] || '';
                    } else {
                        mainExistingId.value = '';
                        mainNewIndex.value = '';
                    }
                }

                fileInput?.addEventListener('change', function () {
                    const files = Array.from(this.files || []);
                    files.forEach(f => { if (/^image\//.test(f.type)) aggregated.push(f); });
                    this.value = ''; // allow re-selecting same file
                    syncInputFiles();
                    renderPreview();
                    if (!mainExistingId.value && !mainNewIndex.value) chooseFallbackMain();
                });

                (function initMainFromExisting() {
                    const checked = document.querySelector('input[type="radio"][name="mainPick"]:checked');
                    if (checked) {
                        const v = checked.value || '';
                        if (v.startsWith('existing:')) mainExistingId.value = v.split(':')[1] || '';
                        if (v.startsWith('new:'))      mainNewIndex.value   = v.split(':')[1] || '';
                    }
                })();

                saveForm?.addEventListener('submit', () => {
                    if (mainExistingId.value === 'undefined') mainExistingId.value = '';
                    if (mainNewIndex.value   === 'undefined') mainNewIndex.value   = '';
                });
            </script>
        </div>
    </div>
</div>

<!-- Header dropdown behavior (fragment) -->
<th:block th:replace="fragments/header :: headerScripts"></th:block>
</body>
</html>
