<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>IMTMA | Upload Event Images</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            background: #f4f7fc;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            font-size: 23px;
            color: #0a2540;
            overflow-x: hidden;
        }
        :root {
            --primary: #0066cc;
            --primary-dark: #004d99;
            --primary-soft: #e6f2ff;
            --gray-50: #f8fafc;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-600: #475569;
            --gray-800: #1e293b;
            --radius-lg: 20px;
            --radius-md: 14px;
            --shadow-sm: 0 8px 20px rgba(0,0,0,0.05), 0 2px 4px rgba(0,0,0,0.02);
            --shadow-md: 0 20px 30px -12px rgba(0,0,0,0.1);
        }

        .sidebar {
            position: fixed; left: 0; top: 0; width: 170px; height: 100vh;
            background: white; border-right: 1px solid var(--gray-200);
            display: flex; flex-direction: column; align-items: center;
            padding: 32px 16px; z-index: 200;
            transition: transform 0.3s ease;
        }
        .sidebar-logo { width: 100px; height: 100px; object-fit: contain; background: white; border-radius: 18px; padding: 8px; border: 1px solid var(--gray-200); box-shadow: var(--shadow-sm); }
        .sidebar-spacer { flex: 1; }
        .sidebar-bottom { width: 100%; display: flex; flex-direction: column; gap: 14px; align-items: center; }
        .sidebar-counter { background: var(--primary); border: none; width: 100%; padding: 12px 0; border-radius: 60px; color: white; font-weight: 700; font-size: 15px; cursor: pointer; transition: background 0.2s; }
        .sidebar-counter:hover { background: var(--primary-dark); }
        .sidebar-username { font-size: 13px; font-weight: 600; background: var(--gray-100); padding: 8px 12px; border-radius: 60px; width: 100%; text-align: center; color: var(--primary); border: 1px solid var(--gray-200); }
        .sidebar-logout-icon { display: flex; flex-direction: column; align-items: center; gap: 4px; font-size: 11px; font-weight: 700; color: #dc2626; cursor: pointer; padding: 8px; border-radius: 14px; transition: background 0.2s; width: 100%; }
        .sidebar-logout-icon svg { width: 24px; height: 24px; stroke: #dc2626; }
        .sidebar-logout-icon:hover { background: #fee2e2; }

        .page { margin-left: 170px; padding: 24px 32px; transition: margin 0.2s; }
        .shell { background: white; border-radius: 28px; border: 1px solid var(--gray-200); overflow: hidden; box-shadow: var(--shadow-md); }

        .header-image-container { width: 100%; background: #0a2a3b; overflow: hidden; display: block; line-height: 0; }
        .header-image-container img { width: 100%; height: auto; object-fit: cover; object-position: center; display: block; }

        .content { padding: 32px 36px; }

        .event-details { background: linear-gradient(145deg,#ffffff,#fafcff); border-radius: 24px; padding: 28px 32px; margin-bottom: 32px; text-align: center; border: 1px solid #eef2ff; box-shadow: 0 6px 14px rgba(0,0,0,0.02); }
        .event-title { font-size: 2rem; font-weight: 800; color: #0f172a; letter-spacing: -0.02em; margin-bottom: 12px; }
        .event-subtitle { color: var(--gray-600); font-size: 1rem; margin-bottom: 16px; }
        .event-meta { display: flex; justify-content: center; gap: 24px; flex-wrap: wrap; }
        .event-meta-item { display: flex; align-items: center; gap: 8px; background: var(--gray-100); padding: 6px 18px; border-radius: 60px; font-weight: 500; color: #2c3e66; font-size: 0.85rem; }

        .event-selector { margin-bottom: 32px; }
        .event-selector label { font-weight: 700; color: #334155; margin-bottom: 8px; display: flex; align-items: center; gap: 6px; text-transform: uppercase; font-size: 12px; letter-spacing: 0.5px; }
        .event-select-wrap { position: relative; }
        .event-selector select { width: 100%; padding: 16px 24px; border-radius: 20px; border: 1px solid #cbd5e1; background: white; font-weight: 600; font-size: 16px; cursor: pointer; appearance: none; background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="%234b5563" stroke-width="2"><polyline points="6 9 12 15 18 9"></polyline></svg>'); background-repeat: no-repeat; background-position: right 20px center; transition: all 0.2s; }
        .event-selector select:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(0,102,204,0.2); outline: none; }
        .event-selector select optgroup { font-weight: 800; color: var(--primary); background: var(--gray-50); }

        .button-row { display: flex; gap: 18px; margin: 28px 0 32px; flex-wrap: wrap; }
        .btn { padding: 14px 28px; border-radius: 40px; font-weight: 700; border: none; cursor: pointer; transition: all 0.2s; font-size: 14px; }
        .btn-file, .btn-folder { background: var(--gray-100); color: #1e293b; border: 1px solid var(--gray-200); flex: 1; }
        .btn-upload { background: var(--primary); color: white; flex: 1.5; box-shadow: 0 2px 8px rgba(0,102,204,0.3); }
        .btn:hover { transform: translateY(-2px); filter: brightness(0.97); }

        .workspace { display: grid; grid-template-columns: 1fr 340px; gap: 28px; align-items: start; }
        .dropzone { background: #ffffff; border: 2px dashed #cbd5e1; border-radius: 28px; padding: 48px 28px; text-align: center; cursor: pointer; transition: all 0.2s; margin-bottom: 24px; }
        .dropzone.dragging { border-color: var(--primary); background: #f0f9ff; }
        .floating-icon { font-size: 58px; margin-bottom: 12px; }
        .dropzone h2 { font-size: 1.6rem; font-weight: 700; margin: 12px 0 6px; }
        .hint-row { display: flex; gap: 8px; justify-content: center; margin-top: 20px; flex-wrap: wrap; }
        .hint { background: var(--gray-100); padding: 6px 14px; border-radius: 30px; font-size: 12px; font-weight: 500; }

        .req-card { border-radius: 24px; border: 1px solid var(--gray-200); background: white; margin-top: 8px; overflow: hidden; }
        .req-title { background: var(--gray-100); padding: 16px 20px; font-weight: 800; letter-spacing: 0.3px; border-bottom: 1px solid var(--gray-200); font-size: 13px; }
        .req-section { padding: 16px 20px; }
        .req-section.preferred { background: #f6fafe; border-top: 1px solid #d9e8ff; }
        .req-section-title { font-size: 12px; font-weight: 800; color: #0f172a; margin-bottom: 10px; }
        .req-items { display: flex; flex-direction: column; gap: 12px; }
        .req-item { display: flex; gap: 12px; font-size: 13px; align-items: flex-start; }

        .panel { background: white; border-radius: 24px; border: 1px solid var(--gray-200); padding: 18px; margin-bottom: 20px; }
        .panel-head { display: flex; justify-content: space-between; margin-bottom: 18px; border-bottom: 1px solid #eef2ff; padding-bottom: 12px; font-size: 13px; font-weight: 700; }
        .list { max-height: 280px; overflow-y: auto; display: flex; flex-direction: column; gap: 10px; }
        .item { background: var(--gray-50); border-radius: 18px; padding: 12px 14px; border: 1px solid var(--gray-200); }
        .item-name { font-weight: 600; word-break: break-word; font-size: 13px; display: flex; align-items: center; gap: 6px; }
        .item-meta { display: flex; justify-content: space-between; font-size: 11px; color: #5b6e8c; margin-top: 8px; }
        .progress-bar { margin-top: 12px; height: 6px; background: #e2e8f0; border-radius: 10px; overflow: hidden; }
        .progress-fill { width: 0%; height: 100%; background: var(--primary); transition: width 0.25s; border-radius: 10px; }
        .progress-fill.done { background: #22c55e; }
        .progress-fill.failed { background: #ef4444; }
        .empty { color: #94a3b8; text-align: center; padding: 28px 12px; font-size: 13px; }

        .upload-modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); display: none; align-items: center; justify-content: center; z-index: 1000; }
        .upload-modal-overlay.open { display: flex; }
        .upload-modal { background: white; width: min(680px,90vw); border-radius: 32px; max-height: 80vh; display: flex; flex-direction: column; overflow: hidden; box-shadow: 0 30px 50px rgba(0,0,0,0.3); }
        .upload-modal-header { padding: 20px 24px; border-bottom: 1px solid var(--gray-200); display: flex; justify-content: space-between; background: white; align-items: center; }
        .upload-modal-counter { background: var(--primary); color: white; padding: 6px 20px; border-radius: 40px; font-weight: 800; font-size: 1.4rem; }
        .upload-modal-close { background: none; border: none; font-size: 28px; cursor: pointer; opacity: 0.6; }
        .upload-modal-body { padding: 20px 24px; overflow-y: auto; flex: 1; }

        .toast-wrap { position: fixed; bottom: 24px; right: 24px; z-index: 1200; display: flex; flex-direction: column; gap: 8px; }
        .toast { background: #dc2626; color: white; padding: 12px 20px; border-radius: 60px; font-weight: 600; box-shadow: 0 6px 12px rgba(0,0,0,0.1); animation: fadein 0.2s; }
        @keyframes fadein { from { opacity:0; transform: translateX(20px); } to { opacity:1; transform: translateX(0); } }

        .popup-overlay { position: fixed; inset:0; background: rgba(0,0,0,0.6); display: flex; align-items: center; justify-content: center; z-index: 2000; opacity:0; visibility:hidden; transition:0.2s; }
        .popup-overlay.show { opacity:1; visibility:visible; }
        .popup { background: white; border-radius: 40px; padding: 36px 48px; text-align:center; max-width: 360px; width: 85%; }
        .popup-message { font-size: 1.5rem; font-weight: 800; margin: 12px 0; }
        .popup-ok-btn { background: var(--primary); color: white; border: none; padding: 12px 32px; border-radius: 60px; margin-top: 20px; font-weight: 700; cursor: pointer; }

        .sidebar-toggle { display: none; position: fixed; top: 16px; left: 16px; z-index: 301; background: white; border: 1px solid var(--gray-200); border-radius: 12px; padding: 10px 12px; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.1); flex-direction: column; gap: 5px; }
        .sidebar-toggle span { display: block; width: 22px; height: 2px; background: #1e293b; border-radius: 2px; }
        .sidebar-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.4); z-index: 199; }
        .sidebar-overlay.open { display: block; }
        .footer-banner { display: none; }

        @media (max-width: 880px) {
            .sidebar-toggle { display: flex; }
            .sidebar { transform: translateX(-100%); }
            .sidebar.open { transform: translateX(0); }
            .page { margin-left: 0; padding: 70px 16px 24px 16px; }
            .workspace { grid-template-columns: 1fr; }
            .button-row { flex-direction: column; }
            .btn { width: 100%; }
            .content { padding: 20px; }
            .event-title { font-size: 1.5rem; }
        }
        @media (max-width: 480px) {
            .page { padding: 70px 12px 20px 12px; }
            .content { padding: 16px; }
            .event-title { font-size: 1.3rem; }
        }
    </style>
</head>
<body>
<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>
<div class="sidebar-toggle" id="sidebarToggleBtn" onclick="toggleSidebar()">
    <span></span><span></span><span></span>
</div>

<div class="sidebar" id="sidebar">
    <img id="sidebarLogo" class="sidebar-logo" src="" alt="Logo" style="display:none;">
    <div id="sidebarLogoFallback" style="width:100px;height:100px;background:#eef2ff;border-radius:18px;display:flex;align-items:center;justify-content:center;font-size:48px;">📷</div>
    <div class="sidebar-spacer"></div>
    <div class="sidebar-bottom">
        <button class="sidebar-counter" onclick="openUploadModal()"><span id="sidebarCounter">0 / 0</span></button>
        <div class="sidebar-username">{{ session.get('username', 'photographer') }}</div>
        <div class="sidebar-logout-icon" onclick="document.getElementById('logoutForm').submit()">
            <svg viewBox="0 0 24 24" fill="none" stroke-width="2"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
            Logout
        </div>
    </div>
</div>

<div class="page">
    <div class="shell">
        <div class="header-image-container">
            <img id="dynamicHeader" src="" alt="Event header">
        </div>
        <div class="content">
            <div id="eventDetails" class="event-details" style="display:none;">
                <h1 class="event-title" id="eventTitle">Loading...</h1>
                <p class="event-subtitle" id="eventSubtitle"></p>
                <div class="event-meta">
                    <div class="event-meta-item">📍 <span id="eventVenue">Venue</span></div>
                </div>
            </div>

            <div class="event-selector">
                <label>🎯 SELECT DAY <span style="color:#e11d48;">*</span></label>
                <div class="event-select-wrap">
                    <select id="eventSelect" required>
                        <option value="" disabled selected>— Choose an active day —</option>
                    </select>
                </div>
            </div>

            <form id="uploadForm">
                <div class="button-row">
                    <button type="button" class="btn btn-file" onclick="selectFiles()">📁 Choose Files</button>
                    <button type="button" class="btn btn-folder" onclick="selectFolder()">🗂️ Choose Folder</button>
                    <button type="submit" class="btn btn-upload">🚀 Start Upload</button>
                </div>
                <div class="workspace">
                    <div class="main-pane">
                        <div class="dropzone" id="dropZone">
                            <div class="floating-icon">📸</div>
                            <h2>Drop images or folders</h2>
                            <p>Drag & drop anywhere or click to browse</p>
                            <div class="hint-row">
                                <div class="hint">⬆️ Bulk upload</div>
                                <div class="hint">✅ Auto dedup</div>
                                <div class="hint">⚡ Parallel uploads</div>
                            </div>
                        </div>
                        <div class="req-card">
                            <div class="req-title">📋 Photographer Requirements</div>
                            <div class="req-section">
                                <div class="req-items">
                                    <div class="req-item"><span>💻</span><div><strong>16GB RAM + SSD</strong><br>Reliable laptop</div></div>
                                    <div class="req-item"><span>🌐</span><div><strong>50+ Mbps upload</strong><br>Stable connection</div></div>
                                    <div class="req-item"><span>💾</span><div><strong>UHS-II Memory Card</strong><br>High speed required</div></div>
                                    <div class="req-item"><span>🗄️</span><div><strong>External SSD</strong><br>For backup storage</div></div>
                                </div>
                            </div>
                            <div class="req-section preferred">
                                <div class="req-section-title">🚀 Recommended</div>
                                <div class="req-items">
                                    <div class="req-item"><span>🔥</span><div><strong>Fiber / 200 Mbps+</strong><br>Faster uploads</div></div>
                                    <div class="req-item"><span>🖥️</span><div><strong>32GB RAM</strong><br>High performance</div></div>
                                    <div class="req-item"><span>📡</span><div><strong>5G Hotspot backup</strong><br>Secondary network</div></div>
                                    <div class="req-item"><span>💿</span><div><strong>Dual SSD setup</strong><br>Primary + backup</div></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="side-pane">
                        <div class="panel">
                            <div class="panel-head"><h3>📎 Selected Files</h3><span id="selectedCount">0 items</span></div>
                            <div id="selectedList" class="list"><div class="empty">No files chosen</div></div>
                        </div>
                        <div class="panel">
                            <div class="panel-head"><h3>⏳ Upload Queue</h3><span>live</span></div>
                            <div id="progressArea" class="list"><div class="empty">Progress appears here</div></div>
                        </div>
                    </div>
                </div>
                <input type="file" id="fileInput" multiple accept="image/*" style="display:none;">
                <input type="file" id="folderInput" webkitdirectory directory multiple style="display:none;">
            </form>
        </div>
    </div>
</div>

<div id="uploadModalOverlay" class="upload-modal-overlay">
    <div class="upload-modal">
        <div class="upload-modal-header">
            <div style="display:flex;align-items:center;gap:14px;">
                <div class="upload-modal-counter" id="modalCounter">0/0</div>
                <span style="font-weight:800;">📤 Upload Progress</span>
            </div>
            <button class="upload-modal-close" onclick="closeUploadModal()">✕</button>
        </div>
        <div class="upload-modal-body">
            <div id="uploadList"><div class="empty">Uploads will appear here</div></div>
        </div>
    </div>
</div>

<div id="toastWrap" class="toast-wrap"></div>

<div id="popupOverlay" class="popup-overlay">
    <div class="popup">
        <span style="font-size:48px;">⚠️</span>
        <div class="popup-message" id="popupMessage">Select event</div>
        <div id="popupSub" style="font-size:14px;color:#64748b;margin-top:6px;"></div>
        <button class="popup-ok-btn" onclick="closeAlertPopup()">OK</button>
    </div>
</div>

<!-- ✅ Logout form at body level - always accessible -->
<form method="post" action="/logout" id="logoutForm" style="display:none;"></form>

<script>
    const eventSelect = document.getElementById("eventSelect");
    const fileInput = document.getElementById("fileInput");
    const folderInput = document.getElementById("folderInput");
    const dropZone = document.getElementById("dropZone");
    const selectedList = document.getElementById("selectedList");
    const selectedCountSpan = document.getElementById("selectedCount");
    const progressArea = document.getElementById("progressArea");
    const uploadListDiv = document.getElementById("uploadList");
    const sidebarCounterSpan = document.getElementById("sidebarCounter");
    const modalCounterSpan = document.getElementById("modalCounter");

    let allFiles = [], uploadedCount = 0, progressReady = false;

    function escapeHtml(str) { return String(str).replace(/[&<>]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;'}[m])); }
    function getRelativePath(f) { return f.webkitRelativePath || f.relativePath || f.name; }
    function buildFileKey(f) { return `${getRelativePath(f)}:${f.size}:${f.lastModified}`; }
    function updateAllCounters() {
        let txt = `${uploadedCount} / ${allFiles.length}`;
        if(sidebarCounterSpan) sidebarCounterSpan.innerText = txt;
        if(modalCounterSpan) modalCounterSpan.innerText = txt;
    }
    function openUploadModal() { document.getElementById("uploadModalOverlay").classList.add("open"); }
    function closeUploadModal() { document.getElementById("uploadModalOverlay").classList.remove("open"); }
    function showToast(msg) { let t=document.createElement("div"); t.className="toast"; t.innerText=msg; document.getElementById("toastWrap").appendChild(t); setTimeout(()=>t.remove(),3200); }
    function showPopup(msg, sub) { document.getElementById("popupMessage").innerText=msg; document.getElementById("popupSub").innerText=sub||""; document.getElementById("popupOverlay").classList.add("show"); }
    function closeAlertPopup() { document.getElementById("popupOverlay").classList.remove("show"); }
    function resetInput(inp) { inp.value=""; }

    async function loadDayEvents() {
        try {
            const res = await fetch('/admin/api/day-events');
            if(!res.ok) throw new Error(`HTTP ${res.status}`);
            const events = await res.json();
            eventSelect.innerHTML = '<option value="" disabled selected>— Select a day —</option>';
            if(!events || events.length === 0) { eventSelect.innerHTML = '<option disabled>No events available</option>'; return; }
            const grouped = new Map();
            events.forEach(ev => {
                if(!ev.event_name || ev.event_name.trim() === "") return;
                const dayKey = ev.day && ev.day.trim() !== "" ? ev.day : "Main Event";
                if(!grouped.has(dayKey)) grouped.set(dayKey, []);
                grouped.get(dayKey).push(ev);
            });
            const sortedDays = Array.from(grouped.keys()).sort((a,b) => {
                let na = parseInt(a.match(/\d+/)?.[0] || "0");
                let nb = parseInt(b.match(/\d+/)?.[0] || "0");
                return na !== nb ? na - nb : a.localeCompare(b);
            });
            for(let day of sortedDays) {
                const og = document.createElement('optgroup');
                og.label = day.toUpperCase();
                grouped.get(day).forEach(ev => {
                    const o = document.createElement('option');
                    o.value = ev.id;
                    o.textContent = `  • ${ev.event_name}`;
                    og.appendChild(o);
                });
                eventSelect.appendChild(og);
            }
        } catch(err) {
            console.error("Failed loading day events:", err);
            eventSelect.innerHTML = '<option disabled>⚠️ Failed to load</option>';
            showToast("Could not load events, please refresh.");
        }
    }

    async function loadEventDetails() {
        try {
            const res = await fetch('/api/event-details');
            const data = await res.json();
            if(data.error) throw new Error(data.error);
            if(data.assets?.logo_image) {
                const sl = document.getElementById("sidebarLogo");
                if(sl) { sl.src = data.assets.logo_image; sl.style.display = "block"; }
                const fb = document.getElementById("sidebarLogoFallback");
                if(fb) fb.style.display = "none";
            }
            if(data.assets?.header_image) {
                const h = document.getElementById("dynamicHeader");
                if(h) { h.src = data.assets.header_image; h.style.display = "block"; }
            }
            if(data.event) {
                document.getElementById("eventTitle").innerText = data.event.event_name || "Event";
                document.getElementById("eventSubtitle").innerText = data.event.event_subtitle || "";
                document.getElementById("eventVenue").innerText = data.event.venue || "TBD";
                document.getElementById("eventDetails").style.display = "block";
                document.title = (data.event.event_name || "IMTMA") + " | Upload";
            }
        } catch(e) { console.warn("Event details failed:", e); }
    }

    function addFiles(filesArray) {
        for(let f of filesArray) {
            if(!f.type || !f.type.startsWith("image/")) continue;
            if(!allFiles.some(ex => buildFileKey(ex) === buildFileKey(f))) allFiles.push(f);
        }
        renderSelected();
        updateAllCounters();
    }

    function renderSelected() {
        selectedCountSpan.innerText = `${allFiles.length} items`;
        if(!allFiles.length) { selectedList.innerHTML = '<div class="empty">📭 No files selected</div>'; return; }
        selectedList.innerHTML = "";
        allFiles.forEach(f => {
            let d = document.createElement("div"); d.className = "item";
            d.innerHTML = `<div class="item-name"><span>🖼️</span> ${escapeHtml(getRelativePath(f))}</div><div class="item-meta"><span>${(f.size/1024).toFixed(1)} KB</span><span>${f.type.split("/")[1]||''}</span></div>`;
            selectedList.appendChild(d);
        });
    }

    function ensureRows(file, idx) {
        if(document.getElementById(`prow-${idx}`)) return;
        if(!progressReady) { progressArea.innerHTML=""; uploadListDiv.innerHTML=""; progressReady=true; }
        let rel = escapeHtml(getRelativePath(file));
        let r1 = document.createElement("div"); r1.className="item"; r1.id=`prow-${idx}`;
        r1.innerHTML = `<div class="item-name"><span id="icon-${idx}">⏳</span> ${rel}</div><div class="item-meta"><span id="stat-${idx}">waiting</span><span id="perc-${idx}">0%</span></div><div class="progress-bar"><div id="bar-${idx}" class="progress-fill"></div></div>`;
        progressArea.appendChild(r1);
        let r2 = document.createElement("div"); r2.className="item"; r2.id=`drow-${idx}`;
        r2.innerHTML = `<div class="item-name"><span id="dicon-${idx}">⏳</span> ${rel}</div><div class="item-meta"><span id="dstat-${idx}">waiting</span><span id="dperc-${idx}">0%</span></div><div class="progress-bar"><div id="dbar-${idx}" class="progress-fill"></div></div>`;
        uploadListDiv.appendChild(r2);
    }

    function setStatus(idx,label,percent) {
        ['stat','dstat'].forEach(p=>{ let e=document.getElementById(`${p}-${idx}`); if(e) e.innerText=label; });
        ['perc','dperc'].forEach(p=>{ let e=document.getElementById(`${p}-${idx}`); if(e) e.innerText=`${percent}%`; });
        ['bar','dbar'].forEach(p=>{ let e=document.getElementById(`${p}-${idx}`); if(e) e.style.width=`${percent}%`; });
    }
    function setIcon(idx,icon) { ['icon','dicon'].forEach(p=>{ let e=document.getElementById(`${p}-${idx}`); if(e) e.innerText=icon; }); }
    function markFinished(idx,msg,pct) { setStatus(idx,msg,pct); setIcon(idx,'✅'); ['bar','dbar'].forEach(p=>{ let e=document.getElementById(`${p}-${idx}`); if(e) e.classList.add("done"); }); uploadedCount++; updateAllCounters(); }
    function markFailed(idx,msg) { setStatus(idx,msg,0); setIcon(idx,'❌'); ['bar','dbar'].forEach(p=>{ let e=document.getElementById(`${p}-${idx}`); if(e) e.classList.add("failed"); }); uploadedCount++; updateAllCounters(); }

    async function checkFileExists(file) {
        try { let r=await fetch(`/api/check-file?name=${encodeURIComponent(file.name)}`); let d=await r.json(); return d.exists; } catch{ return false; }
    }

    function uploadSingle(file, idx) {
        return new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest(), fd = new FormData();
            fd.append("images", file); fd.append("day_event_id", eventSelect.value);
            xhr.open("POST", "/api/upload-event-images");
            xhr.upload.onprogress = e => { if(e.lengthComputable) { let pct=Math.floor((e.loaded/e.total)*100); setIcon(idx,'⏳'); setStatus(idx,`${pct}% uploading`,pct); } };
            xhr.onload = () => { if(xhr.status>=200&&xhr.status<300) resolve({}); else reject(new Error("Upload failed")); };
            xhr.onerror = () => reject(new Error("Network error"));
            xhr.send(fd);
        });
    }

    async function handleFile(file, idx, results) {
        ensureRows(file, idx);
        setIcon(idx,'🔍'); setStatus(idx,"checking...",0);
        try {
            if(await checkFileExists(file)) {
                showToast(`⏩ Skipped: ${file.name}`);
                setIcon(idx,'⏭️'); setStatus(idx,"duplicate",100);
                ['bar','dbar'].forEach(p=>{ let e=document.getElementById(`${p}-${idx}`); if(e){e.style.width="100%";e.classList.add("done");} });
                uploadedCount++; updateAllCounters();
                results.push({file:getRelativePath(file),status:"duplicate"});
                return;
            }
            await uploadSingle(file, idx);
            markFinished(idx,"uploaded ✅",100);
            results.push({file:getRelativePath(file),status:"uploaded"});
        } catch(err) {
            markFailed(idx,"failed ❌");
            results.push({file:getRelativePath(file),status:"failed",error:err.message});
            showToast(`❌ ${file.name}: ${err.message}`);
        }
    }

    function selectFiles() { fileInput.click(); }
    async function selectFolder() {
        if(window.showDirectoryPicker) {
            try { let dir=await window.showDirectoryPicker(); addFiles(await readDirHandle(dir,dir.name)); return; } catch(e){}
        }
        folderInput.click();
    }
    async function readDirHandle(handle, prefix) {
        let files=[];
        for await(let entry of handle.values()) {
            let path = prefix ? `${prefix}/${entry.name}` : entry.name;
            if(entry.kind==="file") { let f=await entry.getFile(); try{Object.defineProperty(f,"relativePath",{value:path});}catch{}; files.push(f); }
            else if(entry.kind==="directory") files.push(...await readDirHandle(entry,path));
        }
        return files;
    }

    fileInput.onchange = e => { addFiles(Array.from(e.target.files)); resetInput(fileInput); };
    folderInput.onchange = e => { addFiles(Array.from(e.target.files)); resetInput(folderInput); };
    dropZone.addEventListener("click",()=>selectFiles());
    dropZone.addEventListener("dragover",e=>{ e.preventDefault(); dropZone.classList.add("dragging"); });
    dropZone.addEventListener("dragleave",()=>dropZone.classList.remove("dragging"));
    dropZone.addEventListener("drop",async e=>{
        e.preventDefault(); dropZone.classList.remove("dragging");
        let files=[];
        if(e.dataTransfer.items?.length) { for(let i=0;i<e.dataTransfer.items.length;i++){ let en=e.dataTransfer.items[i].webkitGetAsEntry(); if(en) files.push(...await getFilesFromEntry(en,"")); } }
        else files=Array.from(e.dataTransfer.files);
        addFiles(files);
    });
    async function getFilesFromEntry(entry,path) {
        let res=[];
        if(entry.isFile) { let f=await new Promise(r=>entry.file(r)); let rp=path?`${path}/${entry.name}`:entry.name; try{Object.defineProperty(f,"relativePath",{value:rp});}catch{}; res.push(f); }
        else if(entry.isDirectory) { let reader=entry.createReader(); let entries=await new Promise(resolve=>{ let all=[]; function batch(){reader.readEntries(c=>{if(!c.length)resolve(all);else{all.push(...c);batch();}});}; batch();}); for(let s of entries) res.push(...await getFilesFromEntry(s,path?`${path}/${entry.name}`:entry.name)); }
        return res;
    }

    document.getElementById("uploadForm").addEventListener("submit", async e => {
        e.preventDefault();
        if(!eventSelect.value) { showPopup("Select a day","Please choose a valid day from dropdown"); eventSelect.style.border="2px solid #dc2626"; setTimeout(()=>eventSelect.style.border="",2000); return; }
        if(!allFiles.length) { showPopup("No files selected","Choose images or folders before uploading"); return; }
        uploadedCount=0; progressReady=false; openUploadModal();
        progressArea.innerHTML='<div class="empty">Preparing...</div>';
        uploadListDiv.innerHTML='<div class="empty">Initializing...</div>';
        updateAllCounters();
        let results=[];
        await Promise.all(allFiles.map((f,i)=>handleFile(f,i,results)));
        let uploaded=results.filter(r=>r.status==="uploaded").length;
        showToast(`✅ Done! ${uploaded}/${allFiles.length} uploaded.`);
    });

    document.getElementById("uploadModalOverlay").addEventListener("click",function(e){if(e.target===this)closeUploadModal();});

    window.addEventListener("DOMContentLoaded",()=>{
        loadDayEvents();
        loadEventDetails();
        renderSelected();
        updateAllCounters();
    });

    function toggleSidebar() { document.getElementById('sidebar').classList.toggle('open'); document.getElementById('sidebarOverlay').classList.toggle('open'); }
    function closeSidebar() { document.getElementById('sidebar').classList.remove('open'); document.getElementById('sidebarOverlay').classList.remove('open'); }
</script>
</body>
</html>