<!-- Header -->
<%- include('partials/header-sidebar') %>
    <!-- Quill Styles -->
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <!-- Quill JS -->
    <script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>

    <style>
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 25px;
        }

        label {
            font-weight: 600;
            display: block;
            margin: 10px 0 5px;
        }

        input[type="text"],
        textarea {
            width: 100%;
            padding: 10px 14px;
            border: 1px solid #ccc;
            border-radius: 8px;
            font-size: 1rem;
            box-sizing: border-box;
            margin-bottom: 15px;
        }

        textarea {
            min-height: 120px;
            resize: vertical;
        }

        input[type="file"] {
            margin-bottom: 20px;
        }

        .current-images {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }

        .current-images img {
            width: 100px;
            height: 80px;
            object-fit: cover;
            border-radius: 6px;
            border: 1px solid #ddd;
        }

        .form-buttons {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 25px;
        }

        button {
            padding: 10px 18px;
            font-size: 1rem;
            border: none;
            border-radius: 6px;
            cursor: pointer;
        }

        .update-btn {
            background-color: #28a745;
            color: white;
        }

        .delete-icon-btn {
            background: transparent;
            border: none;
            color: #dc3545;
            font-size: 1.4rem;
            cursor: pointer;
        }

        .delete-icon-btn:hover {
            color: #b02a37;
        }

        .back-link {
            display: inline-block;
            margin-top: 25px;
            color: #007bff;
            text-decoration: none;
        }

        .back-link:hover {
            text-decoration: underline;
        }

        .status-delete-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 20px;
        }

        .status-toggle {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .status-toggle input[type="checkbox"] {
            display: none;
        }

        .status-toggle label {
            position: relative;
            display: inline-block;
            width: 42px;
            height: 22px;
            background-color: #ccc;
            border-radius: 22px;
            cursor: pointer;
        }

        .status-toggle label::before {
            content: '';
            position: absolute;
            width: 18px;
            height: 18px;
            border-radius: 50%;
            background-color: white;
            top: 2px;
            left: 2px;
            transition: transform 0.3s ease;
        }

        .status-toggle input[type="checkbox"]:checked+label {
            background-color: #28a745;
        }

        .status-toggle input[type="checkbox"]:checked+label::before {
            transform: translateX(20px);
        }

        .status-toggle span {
            font-size: 0.95rem;
            color: #333;
        }

        @media (max-width: 600px) {
            .form-buttons {
                flex-direction: column;
                gap: 15px;
            }
        }
    </style>

    <div class="page-wrapper" id="toTop">
        <div class="content">
            <div class="container mb-4">
                <h1>Edit News</h1>


                <% if (success_msg && success_msg.length> 0) { %>
                    <div class="alert alert-success">
                        <%= success_msg[0] %>
                    </div>
                    <% } %>

                        <% if (error_msg && error_msg.length> 0) { %>
                            <div class="alert alert-danger">
                                <%= error_msg[0] %>
                            </div>
                            <% } %>


                                <!-- Main Edit Form -->
                                <form action="/news/<%= news._id %>/edit" method="POST" enctype="multipart/form-data">
                                    <label>Title:</label>
                                    <input type="text" name="newsTitle" value="<%= news.title %>" required />

                                    <label>Content:</label>
                                    <div id="quillEditor" style="height: 250px;"></div>

                                    <!-- Hidden input to hold the final content -->
                                    <input type="hidden" name="NewsContent" id="newsContent">
                                    <script id="initialContent" type="text/template">
                        <%- news.content %>
                    </script>


                                    <label>Tag:</label>
                                    <input type="text" name="newsTag" value="<%= news.newsTag %>" />

                                    <label>Current Images:</label>
                                    <div class="current-images">
                                        <% news.images.forEach(img=> { %>
                                            <img src="<%= img.url %>" alt="<%= img.originalName %>" />
                                            <% }) %>
                                    </div>

                                    <label>Upload New Images (optional):</label>
                                    <input type="file" name="upload" id="edit-news-images" />
                                    <div id="editPreviewContainer" class="d-flex gap-2 flex-wrap"></div>

                                    <div class="status-toggle mb-3">
                                        <span>Status:</span>
                                        <input type="checkbox" id="toggle-active" name="isActive" <%=news.isActive
                                            ? "checked" : "" %>>
                                        <label for="toggle-active"></label>
                                        <span>
                                            <%= news.isActive ? "Active" : "Inactive" %>
                                        </span>
                                    </div>

                                    <div class="form-buttons d-flex justify-content-start gap-3">
                                        <button type="submit" class="update-btn">Update News</button>
                                    </div>
                                </form>


                                <script>
                                    // Initialize Quill
                                    const quill = new Quill('#quillEditor', {
                                        theme: 'snow',
                                        placeholder: 'Write news content here...',
                                        modules: {
                                            toolbar: [
                                                [{ header: [1, 2, false] }],
                                                ['bold', 'italic', 'underline'],
                                                ['link', 'image'],
                                                [{ list: 'ordered' }, { list: 'bullet' }],
                                                ['clean']
                                            ]
                                        }
                                    });

                                    // Set initial content from template
                                    const initialHTML = document.getElementById("initialContent").innerHTML;
                                    quill.root.innerHTML = initialHTML;

                                    // Sync content to hidden input on submit
                                    const form = document.querySelector('form');
                                    form.addEventListener('submit', function () {
                                        const html = quill.root.innerHTML;
                                        document.getElementById('newsContent').value = html;
                                    });
                                </script>






                                <!-- Delete Form (separate) -->
                                <form action="/news/<%= news._id %>/delete" method="POST"
                                    onsubmit="return confirm('Are you sure you want to delete this news item?')"
                                    class="mt-3">
                                    <button type="submit" class="delete-icon-btn" title="Delete News">
                                        <i class="fas fa-trash-alt"></i> Delete News
                                    </button>
                                </form>

                                <a href="/news-list" class="back-link"><i class="fas fa-arrow-left"></i> Back to All
                                    News</a>
            </div>
        </div>
    </div>
    </div>

    <%- include("partials/footer") %>

        <script>
            async function toggleStatus(id, isActive) {
                try {
                    const res = await fetch(`/api/news/${id}/status`, {
                        method: 'PATCH',
                        headers: {
                            "Authorization": `Bearer ${"token"}`,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ isActive })
                    });
                    if (res.ok) {
                        alert(`News marked as ${isActive ? 'Active' : 'Inactive'}`);
                        location.reload();
                    } else {
                        alert('Failed to update status.');
                    }
                } catch (err) {
                    console.error(err);
                    alert('Server error');
                }
            }
        </script>

        <script>
            document.getElementById('edit-news-images').addEventListener('change', function () {
                const files = this.files;
                const container = document.getElementById('editPreviewContainer');
                container.innerHTML = '';

                const validFiles = [];

                Array.from(files).forEach((file) => {
                    if (!file.type.startsWith('image/')) return;

                    const img = new Image();
                    img.src = URL.createObjectURL(file);

                    img.onload = function () {

                        validFiles.push(file);

                        const thumb = document.createElement('img');
                        thumb.src = img.src;
                        thumb.style.width = '100px';
                        thumb.style.height = '80px';
                        thumb.style.objectFit = 'cover';
                        thumb.style.border = '1px solid #ccc';
                        thumb.style.borderRadius = '6px';
                        container.appendChild(thumb);

                        URL.revokeObjectURL(img.src);
                    };
                });

                // Reset the input if any image is invalid
                setTimeout(() => {
                    if (validFiles.length !== files.length) {
                        this.value = ""; // Clear invalid selections
                    }
                }, 300);
            });
        </script>

        </body>

        </html>