document.addEventListener("DOMContentLoaded", () => {
    // -------------------------------------------------------------
    // 1. Initial configuration & DOM Selectors
    // -------------------------------------------------------------
    const dom = {
        // Clock & Theme
        statusTime: document.getElementById("status-time"),
        themeToggle: document.getElementById("device-theme-toggle"),
        
        // Navigation
        navItems: document.querySelectorAll(".nav-item"),
        sheets: document.querySelectorAll(".app-sheet"),
        
        // Form & Inputs
        orderForm: document.getElementById("order-form"),
        customerName: document.getElementById("customer_name"),
        materialName: document.getElementById("material_name"),
        weight: document.getElementById("weight"),
        count: document.getElementById("count"),
        btnMinus: document.getElementById("btn-count-minus"),
        btnPlus: document.getElementById("btn-count-plus"),
        
        // Validation Errors
        errors: {
            customer: document.getElementById("customer_name_error"),
            material: document.getElementById("material_name_error"),
            weight: document.getElementById("weight_error"),
            count: document.getElementById("count_error")
        },
        
        // Tab 2 (History & Stats)
        statTotalOrders: document.getElementById("stat-total-orders"),
        statTotalWeight: document.getElementById("stat-total-weight"),
        statTotalCount: document.getElementById("stat-total-count"),
        orderSearch: document.getElementById("order-search"),
        ordersList: document.getElementById("orders-list"),
        
        // Tab 3 (Settings)
        btnClearData: document.getElementById("btn-clear-local-data"),
        
        // Success Modal Overlay
        successOverlay: document.getElementById("success-overlay"),
        btnSuccessClose: document.getElementById("btn-success-close"),
        confirmCustomer: document.getElementById("confirm-customer"),
        confirmMaterial: document.getElementById("confirm-material"),
        confirmWeight: document.getElementById("confirm-weight"),
        confirmCount: document.getElementById("confirm-count")
    };

let orders = [];
let lastStates = {};
let materialCardCount = 0;
function checkSystemStateAndRefresh(targetTables, refreshCallback) {
    fetch('api/check_state.php?_t=' + Date.now())
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                let hasChanges = false;
                targetTables.forEach(t => {
                    const newTs = res.states[t] || 0;
                    if (lastStates[t] !== undefined && lastStates[t] !== newTs) {
                        hasChanges = true;
                    }
                    lastStates[t] = newTs;
                });
                if (hasChanges) {
                    refreshCallback();
                }
            }
        })
        .catch(err => console.error("Error checking states:", err));
}

    // Initialize application state
    initClock();
    initTheme();
    loadLocalOrders();
    addMaterialCard(true);
    setupEventListeners();

    // Populate initial states
    fetch('api/check_state.php?_t=' + Date.now())
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                lastStates = res.states;
            }
        }).catch(() => {});

    // Start polling active materials list dynamically in background
    pollActiveMaterials();
    setInterval(() => {
        checkSystemStateAndRefresh(['materials'], pollActiveMaterials);
    }, 3000);

    // ── Auto-refresh history every 45 seconds when the orders tab is active ──
    setInterval(() => {
        const ordersSheet = document.getElementById("sheet-my-orders");
        if (ordersSheet && ordersSheet.classList.contains("active")) {
            const searchVal = document.getElementById("order-search")?.value || "";
            renderOrders(searchVal);
        }
    }, 45000);

// -------------------------------------------------------------
// 2. Simulated Clock Update
// -------------------------------------------------------------
function initClock() {
    const updateTime = () => {
        const now = new Date();
        let hours = now.getHours();
        let minutes = now.getMinutes();
        
        // Format to 2 digits
        hours = hours < 10 ? '0' + hours : hours;
        minutes = minutes < 10 ? '0' + minutes : minutes;
        
        const timeStr = `${hours}:${minutes}`;
        const clockElement = document.getElementById("status-time");
        if (clockElement) {
            clockElement.textContent = timeStr;
        }
    };
    
    updateTime();
    setInterval(updateTime, 60000); // Update every minute
}

// -------------------------------------------------------------
// 3. Theme Toggle Setup (Dark/Light mode inside application)
// -------------------------------------------------------------
function initTheme() {
    const savedTheme = localStorage.getItem("mobile_order_theme");
    const themeBtn = document.getElementById("device-theme-toggle");
    
    if (savedTheme === "dark") {
        document.body.classList.add("dark-theme");
        if (themeBtn) {
            themeBtn.innerHTML = '<i class="fa-solid fa-sun"></i>';
        }
    } else {
        document.body.classList.remove("dark-theme");
        if (themeBtn) {
            themeBtn.innerHTML = '<i class="fa-solid fa-moon"></i>';
        }
    }
}

function toggleTheme() {
    const themeBtn = document.getElementById("device-theme-toggle");
    if (document.body.classList.contains("dark-theme")) {
        document.body.classList.remove("dark-theme");
        localStorage.setItem("mobile_order_theme", "light");
        if (themeBtn) themeBtn.innerHTML = '<i class="fa-solid fa-moon"></i>';
    } else {
        document.body.classList.add("dark-theme");
        localStorage.setItem("mobile_order_theme", "dark");
        if (themeBtn) themeBtn.innerHTML = '<i class="fa-solid fa-sun"></i>';
    }
}

// -------------------------------------------------------------
// 4. Stepper Buttons Operations (+ / -)
// -------------------------------------------------------------
function adjustCount(amount) {
    const countInput = document.getElementById("count");
    if (!countInput) return;
    
    let currentValue = parseInt(countInput.value) || 1;
    let newValue = currentValue + amount;
    
    if (newValue < 1) {
        newValue = 1;
    }
    
    countInput.value = newValue;
    
    // Clear validation error on count if any
    const parentGroup = countInput.closest(".app-input-group");
    if (parentGroup) {
        parentGroup.classList.remove("has-error");
    }
}

// -------------------------------------------------------------
// 5. App Sheet Switching (Tab Navigation)
// -------------------------------------------------------------
function switchSheet(targetSheetId) {
    // Hide all sheets and remove active status from nav items
    const sheets = document.querySelectorAll(".app-sheet");
    const navItems = document.querySelectorAll(".nav-item");
    
    sheets.forEach(sheet => {
        sheet.classList.remove("active");
    });
    
    navItems.forEach(item => {
        item.classList.remove("active");
    });
    
    // Show selected sheet
    const targetSheet = document.getElementById(targetSheetId);
    if (targetSheet) {
        targetSheet.classList.add("active");
    }
    
    // Highlight matching navigation button
    const activeNav = Array.from(navItems).find(item => item.getAttribute("data-target") === targetSheetId);
    if (activeNav) {
        activeNav.classList.add("active");
    }
    
    // Scroll content panel to top upon change
    const contentPanel = document.querySelector(".app-content");
    if (contentPanel) {
        contentPanel.scrollTop = 0;
    }
}

// -------------------------------------------------------------
// 6. Data Management (Local Storage Operations)
// -------------------------------------------------------------

function loadLocalOrders() {
    try {
        const storedOrders = localStorage.getItem("local_mobile_orders");
        if (storedOrders) {
            orders = JSON.parse(storedOrders);
        } else {
            orders = [];
        }
    } catch (e) {
        console.error("Error parsing local orders list:", e);
        orders = [];
    }
    renderOrders();
}

function saveLocalOrders() {
    localStorage.setItem("local_mobile_orders", JSON.stringify(orders));
    renderOrders();
}

function addOrder(orderData) {
    orders.unshift(orderData); // Insert at the beginning of the list
    saveLocalOrders();
}

function deleteOrder(orderId) {
    if (confirm("هل أنت متأكد من رغبتك في حذف هذا الطلب من السجل المحلي؟")) {
        orders = orders.filter(o => o.id !== orderId);
        saveLocalOrders();
    }
}

function clearAllOrders() {
    if (confirm("تحذير: سيتم مسح كافة الاستمارات المسجلة على هذا الجهاز نهائياً. هل تود الاستمرار؟")) {
        orders = [];
        saveLocalOrders();
        switchSheet("sheet-new-order");
    }
}

// -------------------------------------------------------------
// 7. Dynamic List Rendering & Statistics Update
// -------------------------------------------------------------
// Helper to get the work day start hour from settings
function getWorkDayStartHour() {
    const settings = localStorage.getItem("dashboard_settings");
    if (settings) {
        try {
            const parsed = JSON.parse(settings);
            return parsed.workDayStartHour !== undefined ? parseInt(parsed.workDayStartHour) : 5;
        } catch (e) {
            return 5;
        }
    }
    return 5;
}

function getCurrentShiftRange() {
    const now = new Date();
    const start = new Date(now);
    const end = new Date(now);
    
    const currentHour = now.getHours();
    const startHour = getWorkDayStartHour();
    
    if (currentHour >= startHour) {
        // Shift started today at startHour, ends tomorrow at startHour
        start.setHours(startHour, 0, 0, 0);
        end.setDate(end.getDate() + 1);
        end.setHours(startHour, 0, 0, 0);
    } else {
        // Shift started yesterday at startHour, ends today at startHour
        start.setDate(start.getDate() - 1);
        start.setHours(startHour, 0, 0, 0);
        end.setHours(startHour, 0, 0, 0);
    }
    return { start: start.getTime(), end: end.getTime() };
}

function getTimestampFromId(id) {
    if (id && id.startsWith('order_')) {
        const parts = id.split('_');
        if (parts.length > 1) {
            const ts = parseInt(parts[1]);
            if (!isNaN(ts)) return ts;
        }
    }
    return null;
}

function renderOrders(filterQuery = "") {
    const listContainer = document.getElementById("orders-list");
    const statTotalOrders = document.getElementById("stat-total-orders");
    const statTotalWeight = document.getElementById("stat-total-weight");
    const statTotalCount  = document.getElementById("stat-total-count");

    if (!listContainer) return;

    // Show loading state
    listContainer.innerHTML = `
        <div class="empty-list-state">
            <i class="fa-solid fa-spinner fa-spin empty-icon"></i>
            <h3>جاري تحميل سجل الوردية...</h3>
        </div>`;

    fetch('api/forms.php?action=shift_forms&_t=' + Date.now())
        .then(r => r.json())
        .then(res => {
            if (res.status !== 'success') throw new Error('fetch_failed');

            let forms = res.data || [];

            // Apply search filter
            const query = filterQuery.trim().toLowerCase();
            if (query) {
                forms = forms.filter(f =>
                    f.customerName.toLowerCase().includes(query) ||
                    f.items.some(i => i.name.toLowerCase().includes(query))
                );
            }

            // Calculate stats from DB data
            const totalForms   = forms.length;
            const totalWeight  = forms.reduce((sum, f) =>
                sum + f.items.reduce((s, i) => s + (parseFloat(i.weight) || 0), 0), 0);
            const totalCount   = forms.reduce((sum, f) =>
                sum + f.items.reduce((s, i) => s + (parseInt(i.quantity) || 0), 0), 0);

            if (statTotalOrders) statTotalOrders.textContent = totalForms;
            if (statTotalWeight) statTotalWeight.textContent = Number(totalWeight.toFixed(2));
            if (statTotalCount)  statTotalCount.textContent  = totalCount;

            if (forms.length === 0) {
                listContainer.innerHTML = `
                    <div class="empty-list-state">
                        <i class="fa-solid fa-folder-open empty-icon"></i>
                        <h3>${query ? 'لا توجد نتائج مطابقة' : 'لا توجد استمارات في هذه الوردية'}</h3>
                        <p>${query ? 'تأكد من كتابة الاسم أو المادة بشكل صحيح' : 'ابدأ بإضافة طلبك الأول من تبويب "طلب جديد"'}</p>
                    </div>`;
                return;
            }

            listContainer.innerHTML = forms.map((form, idx) => {
                const time = new Date(form.createdAt).toLocaleTimeString('en-US', {
                    timeZone: 'Asia/Baghdad', hour: '2-digit', minute: '2-digit'
                });
                const date = new Date(form.createdAt).toLocaleDateString('en-US', { timeZone: 'Asia/Baghdad' });

                // ── رسوم الاستمارة الثابتة ──
                const FORM_FEE = 1000;

                const itemsHTML = form.items.length === 0
                    ? `<div class="order-info-item" style="color:var(--text-muted);font-size:11px;">لا توجد مواد مسجلة</div>`
                    : form.items.map(item => {
                        const w = item.weight ? `${Number(parseFloat(item.weight).toFixed(2))} كجم` : '—';
                        return `
                            <div class="order-info-item" style="padding:6px 0;border-bottom:1px solid rgba(148,163,184,0.1);display:flex;justify-content:space-between;align-items:center;gap:8px;">
                                <span style="font-weight:700;color:var(--text-primary);font-size:12px;">
                                    <i class="fa-solid fa-circle" style="font-size:6px;color:var(--primary-color);margin-left:5px;"></i>
                                    ${escapeHTML(item.name)}
                                </span>
                                <span style="display:flex;gap:10px;font-size:11px;color:var(--text-secondary);">
                                    <span><i class="fa-solid fa-hashtag" style="font-size:9px;margin-left:3px;"></i>${item.quantity}</span>
                                    <span><i class="fa-solid fa-weight-hanging" style="font-size:9px;margin-left:3px;"></i>${w}</span>
                                </span>
                            </div>`;
                    }).join('');

                // ── سطر رسوم الاستمارة ──
                const feeHTML = `
                    <div class="order-info-item" style="padding:6px 0;display:flex;justify-content:space-between;align-items:center;gap:8px;background:rgba(245,158,11,0.07);border-radius:6px;padding:6px 8px;margin-top:4px;">
                        <span style="font-weight:700;color:#d97706;font-size:12px;">
                            <i class="fa-solid fa-receipt" style="font-size:10px;margin-left:5px;"></i>
                            رسوم الاستمارة
                        </span>
                        <span style="font-weight:800;color:#d97706;font-size:12px;">1,000 د.ع</span>
                    </div>`;

                return `
                    <div class="order-card">
                        <div class="order-card-header">
                            <span class="order-customer">
                                <i class="fa-solid fa-user" style="margin-left:6px;font-size:11px;color:var(--primary-color);"></i>
                                ${escapeHTML(form.customerName)}
                            </span>
                            <span class="order-date">${date} ${time}</span>
                        </div>
                        <div class="order-card-body" style="flex-direction:column;gap:0;">
                            ${itemsHTML}
                            ${feeHTML}
                        </div>
                        <div class="order-card-footer">
                            <span class="order-tag">
                                <i class="fa-solid fa-database"></i>
                                <span>${form.materialsCount} مادة</span>
                            </span>
                            <span class="order-tag" style="background:rgba(16,185,129,0.1);color:#10b981;">
                                <i class="fa-solid fa-circle-check"></i>
                                <span>محفوظ في قاعدة البيانات</span>
                            </span>
                        </div>
                    </div>`;
            }).join('');
        })

        .catch(() => {
            listContainer.innerHTML = `
                <div class="empty-list-state">
                    <i class="fa-solid fa-triangle-exclamation empty-icon" style="color:var(--danger-color);"></i>
                    <h3>تعذّر تحميل السجل</h3>
                    <p>تحقق من الاتصال بالخادم</p>
                </div>`;
        });
}

// Helper to escape HTML characters
function escapeHTML(str) {
    return str.replace(/[&<>'"]/g, 
        tag => ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            "'": '&#39;',
            '"': '&quot;'
        }[tag] || tag)
    );
}

// -------------------------------------------------------------
// 7.5. Dynamic Material Card Management
// -------------------------------------------------------------

function createMaterialCardHTML(index, isFirst = false) {
    const titleText = isFirst ? 'المادة الأولى' : `المادة الإضافية #${index + 1}`;
    const removeBtnHtml = isFirst ? '' : `
        <button type="button" class="btn-remove-material" title="حذف المادة">
            <i class="fa-solid fa-trash-can"></i>
        </button>
    `;

    return `
        <div class="material-item-card" data-index="${index}">
            <div class="material-card-header">
                <span class="material-card-title">
                    <i class="fa-solid fa-box-open"></i>
                    ${titleText}
                </span>
                ${removeBtnHtml}
            </div>
            
            <!-- Material Searchable Combobox -->
            <div class="app-input-group">
                <label>اسم المادة</label>
                <div class="autocomplete-wrapper" style="position:relative;">
                    <div class="input-container">
                        <span class="input-icon"><i class="fa-solid fa-box-open"></i></span>
                        <input type="text" class="material-name-input" placeholder="اكتب أو اختر اسم المادة..." autocomplete="off" required>
                        <i class="fa-solid fa-chevron-down" style="position:absolute; left:12px; font-size:11px; color:var(--text-muted); pointer-events:none;"></i>
                    </div>
                    <!-- Material Filter Dropdown -->
                    <div class="autocomplete-dropdown material-autocomplete-dropdown" style="display:none;"></div>
                </div>
                <span class="validation-msg error-msg">يرجى كتابة أو اختيار اسم المادة.</span>
            </div>
            
            <!-- Weight and Count row -->
            <div class="input-row">
                <!-- Count -->
                <div class="app-input-group">
                    <label>العدد</label>
                    <div class="input-container">
                        <span class="input-icon"><i class="fa-solid fa-hashtag"></i></span>
                        <input type="number" class="material-count-input" min="1" step="1" placeholder="أدخل العدد..." required>
                    </div>
                    <span class="validation-msg error-msg">أدخل عدداً صحيحاً.</span>
                </div>
                <!-- Weight -->
                <div class="app-input-group">
                    <label>الوزن (كجم)</label>
                    <div class="input-container">
                        <span class="input-icon"><i class="fa-solid fa-weight-hanging"></i></span>
                        <input type="number" class="material-weight-input" step="0.1" min="0" placeholder="0.0" required>
                    </div>
                    <span class="validation-msg error-msg">أدخل وزناً صحيحاً (> 0).</span>
                </div>
            </div>
        </div>
    `;
}

function initMaterialCardAutocomplete(cardElement) {
    const input = cardElement.querySelector(".material-name-input");
    const dropdown = cardElement.querySelector(".material-autocomplete-dropdown");
    if (!input || !dropdown) return;

    let highlightedIndex = -1;
    let filteredMaterials = [];

    function highlightMatch(text, query) {
        if (!query) return text;
        const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        return text.replace(new RegExp(`(${escaped})`, 'gi'), '<mark style="background:rgba(99,102,241,0.2); color:var(--primary-color); padding:0 2px; border-radius:3px;">$1</mark>');
    }

    function renderMaterialDropdown(query = "") {
        const q = query.trim().toLowerCase();
        
        let materialsList = [];
        if (typeof AVAILABLE_MATERIALS !== 'undefined' && AVAILABLE_MATERIALS.length > 0) {
            const seen = new Set();
            AVAILABLE_MATERIALS.forEach(m => {
                if (!seen.has(m.name)) {
                    seen.add(m.name);
                    materialsList.push(m);
                }
            });
        }

        if (q === "") {
            filteredMaterials = materialsList;
        } else {
            filteredMaterials = materialsList.filter(m => m.name.toLowerCase().includes(q));
        }

        if (filteredMaterials.length === 0) {
            dropdown.style.display = "block";
            dropdown.innerHTML = `
                <div class="autocomplete-no-result" style="padding:10px 14px; font-size:11px; color:var(--text-secondary); text-align:center;">
                    <i class="fa-solid fa-circle-info" style="margin-left:5px; color:var(--primary-color);"></i>
                    لا توجد مادة مسجلة بهذا الاسم (يمكنك الاستمرار بالإدخال اليدوي)
                </div>`;
            return;
        }

        dropdown.style.display = "block";
        dropdown.innerHTML = filteredMaterials.map((m, i) => {
            const highlighted = q ? highlightMatch(escapeHTML(m.name), q) : escapeHTML(m.name);
            const jallabTag = m.jallab_name ? `<span style="font-size:10px; opacity:0.75; font-weight:normal; margin-right:6px;">(${escapeHTML(m.jallab_name)})</span>` : '';
            const accBadge = m.accounting_type || m.accountingType || '';
            const isSelected = highlightedIndex === i ? 'style="background:rgba(99,102,241,0.1);"' : '';
            return `
                <div class="autocomplete-item ${i === highlightedIndex ? 'highlighted' : ''}" data-index="${i}" ${isSelected} style="padding:10px 14px; font-size:13px; font-weight:700; cursor:pointer; display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid rgba(148,163,184,0.1); transition:background 0.2s;">
                    <div>
                        <i class="fa-solid fa-box-open" style="margin-left:8px; color:var(--primary-color); font-size:12px;"></i>
                        <span>${highlighted}</span> ${jallabTag}
                    </div>
                    ${accBadge ? `<span style="font-size:10px; font-weight:600; padding:2px 8px; border-radius:10px; background:rgba(99,102,241,0.1); color:var(--primary-color);">${accBadge}</span>` : ''}
                </div>`;
        }).join("");

        // Add click events to dropdown items
        const items = dropdown.querySelectorAll(".autocomplete-item");
        items.forEach((itemEl, idx) => {
            itemEl.addEventListener("click", () => {
                selectMaterial(filteredMaterials[idx]);
            });
        });
    }

    function selectMaterial(materialObj) {
        if (!materialObj) return;
        input.value = materialObj.name;
        dropdown.style.display = "none";
        showError(input, false);
        handleMaterialSelectionChange(cardElement, materialObj.name);
    }

    // Input events
    input.addEventListener("focus", () => {
        highlightedIndex = -1;
        renderMaterialDropdown(input.value);
    });

    input.addEventListener("input", () => {
        highlightedIndex = -1;
        showError(input, false);
        renderMaterialDropdown(input.value);
        handleMaterialSelectionChange(cardElement, input.value.trim());
    });

    // Keyboard navigation
    input.addEventListener("keydown", (e) => {
        if (dropdown.style.display === "none") return;
        const items = dropdown.querySelectorAll(".autocomplete-item");

        if (e.key === "ArrowDown") {
            e.preventDefault();
            highlightedIndex = Math.min(highlightedIndex + 1, filteredMaterials.length - 1);
            renderMaterialDropdown(input.value);
        } else if (e.key === "ArrowUp") {
            e.preventDefault();
            highlightedIndex = Math.max(highlightedIndex - 1, 0);
            renderMaterialDropdown(input.value);
        } else if (e.key === "Enter") {
            if (highlightedIndex >= 0 && filteredMaterials[highlightedIndex]) {
                e.preventDefault();
                selectMaterial(filteredMaterials[highlightedIndex]);
            }
        } else if (e.key === "Escape") {
            dropdown.style.display = "none";
        }
    });

    // Close on outside click
    document.addEventListener("click", (e) => {
        if (!cardElement.contains(e.target)) {
            dropdown.style.display = "none";
        }
    });
}

function addMaterialCard(isFirst = false) {
    const container = document.getElementById("materials-container");
    if (!container) return;

    const div = document.createElement("div");
    div.innerHTML = createMaterialCardHTML(materialCardCount, isFirst);
    const cardElement = div.firstElementChild;
    container.appendChild(cardElement);

    // Initialize searchable autocomplete for material input
    initMaterialCardAutocomplete(cardElement);

    // Count input event listener to clear error highlights
    const countInput = cardElement.querySelector(".material-count-input");
    if (countInput) {
        countInput.addEventListener("input", () => showError(countInput, false));
    }

    // Remove action
    const btnRemove = cardElement.querySelector(".btn-remove-material");
    if (btnRemove) {
        btnRemove.addEventListener("click", () => {
            cardElement.remove();
            renumberMaterialCards();
        });
    }

    // Clear error highlights
    const weight = cardElement.querySelector(".material-weight-input");
    if (weight) {
        weight.addEventListener("input", () => showError(weight, false));
    }

    materialCardCount++;
}

// Handle dynamic display of inputs based on material accounting type
function handleMaterialSelectionChange(cardElement, materialNameVal) {
    const materialVal = typeof materialNameVal === 'string' ? materialNameVal : (materialNameVal?.value || "");
    const weightGroup = cardElement.querySelector(".material-weight-input")?.closest(".app-input-group");
    const weightInput = cardElement.querySelector(".material-weight-input");
    const countGroup = cardElement.querySelector(".material-count-input")?.closest(".app-input-group");
    const countInput = cardElement.querySelector(".material-count-input");
    
    if (typeof AVAILABLE_MATERIALS !== 'undefined') {
        const material = AVAILABLE_MATERIALS.find(m => m.name === materialVal);
        if (material) {
            const accType = material.accounting_type || material.accountingType;
            if (accType === "عدد * سعر") {
                // Hide weight field, show count field
                if (weightGroup) weightGroup.style.display = "none";
                if (weightInput) {
                    weightInput.value = "";
                    weightInput.removeAttribute("required");
                }
                if (countGroup) countGroup.style.display = "";
                if (countInput) {
                    countInput.setAttribute("required", "required");
                    if (countInput.value === "1" || countInput.value === "0") {
                        countInput.value = ""; // clear count if it was defaulted/zeroed
                    }
                }
            } else {
                // Show count field, show weight field
                if (countGroup) countGroup.style.display = "";
                if (countInput) {
                    countInput.setAttribute("required", "required");
                    if (countInput.value === "1" || countInput.value === "0") {
                        countInput.value = ""; // clear count if it was defaulted/zeroed
                    }
                }
                if (weightGroup) weightGroup.style.display = "";
                if (weightInput) {
                    weightInput.setAttribute("required", "required");
                }
            }
        } else {
            // Show both fields if no material selected
            if (weightGroup) weightGroup.style.display = "";
            if (weightInput) weightInput.setAttribute("required", "required");
            if (countGroup) countGroup.style.display = "";
            if (countInput) countInput.setAttribute("required", "required");
        }
    }
}

function renumberMaterialCards() {
    const container = document.getElementById("materials-container");
    if (!container) return;
    
    const cards = container.querySelectorAll(".material-item-card");
    cards.forEach((card, index) => {
        card.setAttribute("data-index", index);
        const titleEl = card.querySelector(".material-card-title");
        if (titleEl) {
            if (index === 0) {
                titleEl.innerHTML = `<i class="fa-solid fa-box-open"></i> المادة الأولى`;
                const deleteBtn = card.querySelector(".btn-remove-material");
                if (deleteBtn) deleteBtn.remove();
            } else {
                titleEl.innerHTML = `<i class="fa-solid fa-box-open"></i> المادة الإضافية #${index + 1}`;
            }
        }
    });
}

// -------------------------------------------------------------
// 8. Form Validation & Submissions
// -------------------------------------------------------------
let isSubmitting = false;

function handleFormSubmit(e) {
    e.preventDefault();
    if (isSubmitting) return;
    
    const customerInput = document.getElementById("customer_name");
    let isValid = true;
    
    // Validate Customer Name
    const customerVal = customerInput.value.trim();
    if (!customerVal || customerVal.length < 2) {
        showError(customerInput, true);
        isValid = false;
    } else {
        showError(customerInput, false);
    }
    
    // Validate all material cards
    const materialCards = document.querySelectorAll(".material-item-card");
    const items = [];
    
    if (materialCards.length === 0) {
        alert("يرجى إضافة مادة واحدة على الأقل للطلب.");
        return;
    }
    
    materialCards.forEach((card) => {
        const materialInput = card.querySelector(".material-name-input") || card.querySelector(".material-name-select");
        const weightInput = card.querySelector(".material-weight-input");
        const countInput = card.querySelector(".material-count-input");
        
        let cardValid = true;
        
        // Validate Material Selection - Must match a material in AVAILABLE_MATERIALS
        const materialVal = materialInput ? materialInput.value.trim() : "";
        let selectedMat = null;
        if (typeof AVAILABLE_MATERIALS !== 'undefined' && AVAILABLE_MATERIALS.length > 0) {
            selectedMat = AVAILABLE_MATERIALS.find(m => m.name && m.name.trim().toLowerCase() === materialVal.toLowerCase());
        }

        if (!materialVal || !selectedMat) {
            showError(materialInput, true);
            cardValid = false;
            if (materialVal && !selectedMat) {
                alert(`المادة "${materialVal}" غير مسجلة في الوردية الحالية. يرجى اختيار مادة مسجلة حصراً.`);
            }
        } else {
            showError(materialInput, false);
            if (materialInput && selectedMat.name) {
                materialInput.value = selectedMat.name;
            }
        }
        
        // Validate Weight (only if accounting type is not "عدد * سعر")
        const needsWeight = !selectedMat || selectedMat.accounting_type !== "عدد * سعر";
        
        let weightVal = null;
        if (needsWeight) {
            weightVal = parseFloat(weightInput.value);
            if (isNaN(weightVal) || weightVal <= 0) {
                showError(weightInput, true);
                cardValid = false;
            } else {
                showError(weightInput, false);
            }
        } else {
            showError(weightInput, false);
        }
        
        // Validate Count
        const countVal = parseInt(countInput.value);
        if (isNaN(countVal) || countVal < 1) {
            showError(countInput, true);
            cardValid = false;
        } else {
            showError(countInput, false);
        }
        
        if (!cardValid) {
            isValid = false;
        } else {
            items.push({
                materialName: materialVal,
                weight: needsWeight && weightVal !== null ? Number(weightVal.toFixed(2)) : null,
                count: countVal
            });
        }
    });
    
    if (!isValid) return;
    
    isSubmitting = true;
    const btnSubmit = document.getElementById("btn-submit-order");
    if (btnSubmit) {
        btnSubmit.disabled = true;
        const btnText = btnSubmit.querySelector(".btn-text");
        if (btnText) btnText.textContent = "جاري الإرسال...";
    }
    
    // Get formatted date representation in Arabic
    const formattedDate = formatCurrentArabicDate();
    
    // Create new order entry
    const newOrder = {
        id: 'order_' + Date.now() + '_' + Math.floor(Math.random() * 1000),
        customerName: customerVal,
        items: items,
        date: formattedDate,
        timestamp: Date.now()
    };
    
    // Register order in localStorage DB
    addOrder(newOrder);
    
    // ── Also save to MySQL Database (forms + form_items) ──
    saveOrderToDatabase(newOrder);
    
    // Open the success confirmation screen overlay
    showSuccessOverlay(newOrder);
}

// Send order to MySQL — auto-register customer + reuse shift form if exists
function saveOrderToDatabase(order) {
    // ── Step 1: Ensure customer exists in the customers table ──
    fetch('api/customers.php?action=upsert', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: order.customerName })
    })
    .then(r => r.json())
    .then(cusRes => {
        if (cusRes.status !== 'success') throw new Error('customer_upsert_failed');

        // ── Step 2: Find existing open form in this shift, or create new ──
        return fetch('api/forms.php?action=find_or_create', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ customerName: order.customerName })
        });
    })
    .then(r => r.json())
    .then(formRes => {
        if (formRes.status !== 'success') throw new Error('form_find_or_create_failed');
        const formId = formRes.id;

        // ── Step 3: Add all materials as new form_items ──
        const savePromises = order.items.map(item => {
            return fetch('api/forms.php?action=save_item', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    id: '',
                    form_id: formId,
                    name: item.materialName,
                    quantity: item.count,
                    weight: parseFloat(item.weight) || null,
                    price: 0,
                    worker_share: 0,
                    commission: 0,
                    commission_10: 0,
                    total: 0
                })
            }).then(r => r.json());
        });

        return Promise.all(savePromises);
    })
    .then(itemResults => {
        const allSaved = itemResults.every(res => res && res.status === 'success');
        if (allSaved) {
            renderOrders();
        } else {
            console.warn('بعض المواد لم تُحفظ بنجاح في قاعدة البيانات.');
        }
    })
    .catch(err => {
        console.warn('تعذّر حفظ الطلب في قاعدة البيانات:', err.message);
    });
}

function showError(element, hasError) {
    const parentGroup = element.closest(".app-input-group");
    if (parentGroup) {
        if (hasError) {
            parentGroup.classList.add("has-error");
        } else {
            parentGroup.classList.remove("has-error");
        }
    }
}

function formatCurrentArabicDate() {
    const now = new Date();
    const options = { timeZone: 'Asia/Baghdad', hour: 'numeric', minute: '2-digit', hour12: true };
    const timeStr = now.toLocaleTimeString('en-US', options);
    
    // Return relative dates if today, else formatted date
    return `اليوم، ${timeStr}`;
}

// -------------------------------------------------------------
// 9. Overlay Notification management
// -------------------------------------------------------------
function showSuccessOverlay(order) {
    const overlay = document.getElementById("success-overlay");
    
    document.getElementById("confirm-customer").textContent = order.customerName;
    
    const itemsContainer = document.getElementById("confirm-items-container");
    if (itemsContainer) {
        itemsContainer.innerHTML = order.items.map(item => {
            const wText = item.weight ? ` (${item.weight} كجم)` : '';
            return `
                <div class="detail-row" style="border-bottom: 1px solid rgba(255,255,255,0.08); padding-bottom: 6px; margin-bottom: 4px; display:flex; justify-content:space-between; width:100%;">
                    <span class="detail-label" style="font-weight: 700;">${escapeHTML(item.materialName)}:</span>
                    <span class="detail-value" style="font-size: 12px; opacity: 0.9;">
                        ${item.count} قطع${wText}
                    </span>
                </div>
            `;
        }).join("");
    }
    
    if (overlay) {
        overlay.classList.add("active");
    }
}

function closeSuccessOverlay() {
    const overlay = document.getElementById("success-overlay");
    if (overlay) {
        overlay.classList.remove("active");
    }
    
    // Reset Form Input fields
    const form = document.getElementById("order-form");
    if (form) {
        form.reset();
    }

    const container = document.getElementById("materials-container");
    if (container) {
        container.innerHTML = "";
    }
    materialCardCount = 0;
    addMaterialCard(true);
    
    isSubmitting = false;
    const btnSubmit = document.getElementById("btn-submit-order");
    if (btnSubmit) {
        btnSubmit.disabled = false;
        const btnText = btnSubmit.querySelector(".btn-text");
        if (btnText) btnText.textContent = "إرسال الطلب الآن";
    }
}

// Expose delete function globally so that HTML template onClick binds successfully
window.deleteOrder = deleteOrder;

// -------------------------------------------------------------
// 10. Event Listeners Wiring
// -------------------------------------------------------------
function setupEventListeners() {
    // Header theme switch
    const themeBtn = document.getElementById("device-theme-toggle");
    if (themeBtn) {
        themeBtn.addEventListener("click", toggleTheme);
    }
    
    // Navigation items
    const navItems = document.querySelectorAll(".nav-item");
    navItems.forEach(item => {
        item.addEventListener("click", () => {
            const targetSheetId = item.getAttribute("data-target");
            switchSheet(targetSheetId);
            // Refresh history from DB whenever the orders tab is opened
            if (targetSheetId === "sheet-my-orders") {
                const searchVal = document.getElementById("order-search")?.value || "";
                renderOrders(searchVal);
            }
        });
    });
    
    // زر إضافة مادة أخرى
    const btnAddMaterial = document.getElementById("btn-add-material");
    if (btnAddMaterial) {
        btnAddMaterial.addEventListener("click", () => {
            addMaterialCard(false);
        });
    }
    
    // Form submitting
    const form = document.getElementById("order-form");
    if (form) {
        form.addEventListener("submit", handleFormSubmit);
    }
    
    // Close success overlay modal
    const btnCloseSuccess = document.getElementById("btn-success-close");
    if (btnCloseSuccess) {
        btnCloseSuccess.addEventListener("click", closeSuccessOverlay);
    }
    
    // Resetting DB
    const btnClear = document.getElementById("btn-clear-local-data");
    if (btnClear) {
        btnClear.addEventListener("click", clearAllOrders);
    }
    
    // History search input filter
    const searchInput = document.getElementById("order-search");
    if (searchInput) {
        searchInput.addEventListener("input", (e) => {
            renderOrders(e.target.value);
        });
    }
    
    // Clear validation error highlights for customer name
    const customerInput = document.getElementById("customer_name");
    if (customerInput) {
        customerInput.addEventListener("input", () => {
            showError(customerInput, false);
        });
    }

    // Init customer autocomplete
    initCustomerAutocomplete();
}

// -------------------------------------------------------------
// 11. Customer Name Autocomplete
// -------------------------------------------------------------
function initCustomerAutocomplete() {
    const input = document.getElementById("customer_name");
    const dropdown = document.getElementById("customer-autocomplete");
    if (!input || !dropdown) return;

    let debounceTimer = null;
    let highlightedIndex = -1;
    let currentResults = [];

    // Debounced fetch from server
    input.addEventListener("input", () => {
        const query = input.value.trim();
        clearTimeout(debounceTimer);
        highlightedIndex = -1;

        if (query.length < 1) {
            closeDropdown();
            return;
        }

        // Show loading indicator
        dropdown.style.display = "block";
        dropdown.innerHTML = `
            <div class="autocomplete-loading">
                <div class="autocomplete-spinner"></div>
                <span>جاري البحث...</span>
            </div>`;

        debounceTimer = setTimeout(() => {
            fetchCustomers(query);
        }, 280);
    });

    // Keyboard navigation
    input.addEventListener("keydown", (e) => {
        if (dropdown.style.display === "none") return;

        const items = dropdown.querySelectorAll(".autocomplete-item");
        if (e.key === "ArrowDown") {
            e.preventDefault();
            highlightedIndex = Math.min(highlightedIndex + 1, items.length - 1);
            updateHighlight(items);
        } else if (e.key === "ArrowUp") {
            e.preventDefault();
            highlightedIndex = Math.max(highlightedIndex - 1, 0);
            updateHighlight(items);
        } else if (e.key === "Enter") {
            if (highlightedIndex >= 0 && items[highlightedIndex]) {
                e.preventDefault();
                selectCustomer(currentResults[highlightedIndex]);
            }
        } else if (e.key === "Escape") {
            closeDropdown();
        }
    });

    // Close on outside click
    document.addEventListener("click", (e) => {
        if (!input.contains(e.target) && !dropdown.contains(e.target)) {
            closeDropdown();
        }
    });

    function fetchCustomers(query) {
        fetch(`api/customers_search.php?q=${encodeURIComponent(query)}`)
            .then(r => r.json())
            .then(res => {
                if (res.status === "success") {
                    currentResults = res.data;
                    renderDropdown(res.data, query);
                } else {
                    closeDropdown();
                }
            })
            .catch(() => closeDropdown());
    }

    function renderDropdown(customers, query) {
        if (customers.length === 0) {
            dropdown.style.display = "block";
            dropdown.innerHTML = `<div class="autocomplete-no-result"><i class="fa-solid fa-user-slash" style="margin-left:6px;"></i>لا يوجد زبون بهذا الاسم</div>`;
            return;
        }

        dropdown.style.display = "block";
        dropdown.innerHTML = customers.map((c, i) => {
            const highlightedName = highlightMatch(escapeHTML(c.name), query);
            const phoneDisplay = c.phone ? c.phone : '<span style="color:var(--text-muted)">لا يوجد رقم</span>';
            return `
                <div class="autocomplete-item" data-index="${i}">
                    <div class="autocomplete-item-icon">
                        <i class="fa-solid fa-user"></i>
                    </div>
                    <div class="autocomplete-item-info">
                        <span class="autocomplete-item-name">${highlightedName}</span>
                        <span class="autocomplete-item-phone">${phoneDisplay}</span>
                    </div>
                </div>`;
        }).join("");

        // Bind click events on items
        dropdown.querySelectorAll(".autocomplete-item").forEach((el, i) => {
            el.addEventListener("mousedown", (e) => {
                e.preventDefault(); // prevent input blur before click
                selectCustomer(customers[i]);
            });
            el.addEventListener("mouseover", () => {
                highlightedIndex = i;
                updateHighlight(dropdown.querySelectorAll(".autocomplete-item"));
            });
        });
    }

    function selectCustomer(customer) {
        input.value = customer.name;
        showError(input, false);
        closeDropdown();
        // Move focus to next field (first select option of materials)
        const nextField = document.querySelector(".material-name-select");
        if (nextField) nextField.focus();
    }

    function closeDropdown() {
        dropdown.style.display = "none";
        dropdown.innerHTML = "";
        highlightedIndex = -1;
        currentResults = [];
    }

    function updateHighlight(items) {
        items.forEach((item, i) => {
            item.classList.toggle("highlighted", i === highlightedIndex);
            if (i === highlightedIndex) {
                item.scrollIntoView({ block: "nearest" });
            }
        });
    }

    // Highlight matched text portion
    function highlightMatch(text, query) {
        if (!query) return text;
        const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        return text.replace(new RegExp(`(${escaped})`, 'gi'), '<mark>$1</mark>');
    }
}

// ── Auto-refresh active materials from server without blinking ──
let lastMaterialsJson = "";
function pollActiveMaterials() {
    fetch('api/active_materials.php')
        .then(response => response.json())
        .then(data => {
            if (data && data.status === 'success' && Array.isArray(data.materials)) {
                const newJson = JSON.stringify(data.materials);
                if (newJson !== lastMaterialsJson) {
                    lastMaterialsJson = newJson;
                    AVAILABLE_MATERIALS = data.materials;
                    updateAllMaterialSelects();
                }
            }
        })
        .catch(err => console.error('Error fetching active materials:', err));
}

function updateAllMaterialSelects() {
    const cards = document.querySelectorAll(".material-item-card");
    cards.forEach(cardElement => {
        const input = cardElement.querySelector(".material-name-input") || cardElement.querySelector(".material-name-select");
        if (input && input.value.trim()) {
            handleMaterialSelectionChange(cardElement, input.value.trim());
        }
    });
}
});
