const { useState, useEffect, useRef, useMemo } = React;

// ==========================================
// PURE SVG OUTLINE ICON COMPONENT (100% SVG OUTLINE - ZERO DEPENDENCY)
// ==========================================
function Icon({ name, size = 18, className = "" }) {
    const p = {
        width: size,
        height: size,
        viewBox: "0 0 24 24",
        fill: "none",
        stroke: "currentColor",
        strokeWidth: "2",
        strokeLinecap: "round",
        strokeLinejoin: "round",
        className: `inline-block align-middle shrink-0 ${className}`
    };

    switch (name) {
        case 'package-check':
            return <svg {...p}><path d="m16 16 2 2 4-4"/><path d="M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>;
        case 'package':
        case 'box':
            return <svg {...p}><path d="m7.5 4.27 9 5.15"/><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>;
        case 'package-open':
            return <svg {...p}><path d="M12 2v10"/><path d="M12 12l4-2.5"/><path d="M12 12l-4-2.5"/><path d="m21.12 6.4-6.05-3.52a2 2 0 0 0-2.14 0L6.88 6.4a2 2 0 0 0-1 1.73v7.74a2 2 0 0 0 1 1.73l6.05 3.52a2 2 0 0 0 2.14 0l6.05-3.52a2 2 0 0 0 1-1.73V8.13a2 2 0 0 0-1-1.73Z"/></svg>;
        case 'boxes':
            return <svg {...p}><path d="M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z"/><path d="m7 16.5-4.74-2.85"/><path d="m7 16.5 5-3"/><path d="M7 16.5v5.17"/><path d="M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z"/><path d="m17 16.5-5-3"/><path d="m17 16.5 4.74-2.85"/><path d="M17 16.5v5.17"/><path d="M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z"/><path d="M12 8 7.26 5.15"/><path d="m12 8 4.74-2.85"/><path d="M12 13.5V8"/></svg>;
        case 'arrow-up-right':
            return <svg {...p}><path d="M7 7h10v10"/><path d="M7 17 17 7"/></svg>;
        case 'arrow-down-left':
            return <svg {...p}><path d="M17 17H7V7"/><path d="M17 7 7 17"/></svg>;
        case 'arrow-down':
            return <svg {...p}><path d="M12 5v14"/><path d="m19 12-7 7-7-7"/></svg>;
        case 'qr-code':
            return <svg {...p}><rect width="5" height="5" x="3" y="3" rx="1"/><rect width="5" height="5" x="16" y="3" rx="1"/><rect width="5" height="5" x="3" y="16" rx="1"/><path d="M21 16h-3a2 2 0 0 0-2 2v3"/><path d="M21 21v.01"/><path d="M12 7v3a2 2 0 0 1-2 2H7"/><path d="M3 12h.01"/><path d="M12 3h.01"/><path d="M12 16v.01"/><path d="M16 12h1"/><path d="M21 12v.01"/><path d="M12 21v-1"/></svg>;
        case 'scan':
            return <svg {...p}><path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/></svg>;
        case 'camera':
            return <svg {...p}><path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/></svg>;
        case 'clipboard-check':
            return <svg {...p}><rect width="8" height="4" x="8" y="2" rx="1" ry="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><path d="m9 14 2 2 4-4"/></svg>;
        case 'volume-2':
            return <svg {...p}><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>;
        case 'bar-chart-3':
            return <svg {...p}><path d="M3 3v18h18"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/></svg>;
        case 'pie-chart':
            return <svg {...p}><path d="M21.21 15.89A10 10 0 1 1 8 2.83"/><path d="M22 12A10 10 0 0 0 12 2v10z"/></svg>;
        case 'trending-up':
            return <svg {...p}><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>;
        case 'trending-down':
            return <svg {...p}><polyline points="22 17 13.5 8.5 8.5 13.5 2 7"/><polyline points="16 17 22 17 22 11"/></svg>;
        case 'history':
            return <svg {...p}><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/></svg>;
        case 'file-spreadsheet':
            return <svg {...p}><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M8 13h2"/><path d="M14 13h2"/><path d="M8 17h2"/><path d="M14 17h2"/></svg>;
        case 'send':
            return <svg {...p}><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>;
        case 'rotate-ccw':
            return <svg {...p}><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>;
        case 'log-out':
            return <svg {...p}><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" x2="9" y1="12" y2="12"/></svg>;
        case 'plus':
            return <svg {...p}><path d="M5 12h14"/><path d="M12 5v14"/></svg>;
        case 'search':
            return <svg {...p}><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>;
        case 'x':
            return <svg {...p}><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>;
        case 'check':
            return <svg {...p}><path d="M20 6 9 17l-5-5"/></svg>;
        case 'check-circle':
            return <svg {...p}><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><path d="m9 11 3 3L22 4"/></svg>;
        case 'alert-circle':
            return <svg {...p}><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>;
        case 'alert-triangle':
            return <svg {...p}><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" x2="12" y1="9" y2="13"/><line x1="12" x2="12.01" y1="17" y2="17"/></svg>;
        case 'alert-octagon':
            return <svg {...p}><polygon points="7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>;
        case 'user':
            return <svg {...p}><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>;
        case 'lock':
            return <svg {...p}><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>;
        case 'eye':
            return <svg {...p}><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>;
        case 'eye-off':
            return <svg {...p}><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" x2="22" y1="2" y2="22"/></svg>;
        case 'pencil':
            return <svg {...p}><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>;
        case 'trash':
            return <svg {...p}><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>;
        case 'printer':
            return <svg {...p}><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect width="12" height="8" x="6" y="14"/></svg>;
        case 'refresh-cw':
            return <svg {...p}><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>;
        case 'filter':
            return <svg {...p}><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>;
        case 'download':
            return <svg {...p}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>;
        case 'menu':
            return <svg {...p}><line x1="4" x2="20" y1="12" y2="12"/><line x1="4" x2="20" y1="6" y2="6"/><line x1="4" x2="20" y1="18" y2="18"/></svg>;
        case 'chevron-right':
            return <svg {...p}><path d="m9 18 6-6-6-6"/></svg>;
        case 'chevron-left':
            return <svg {...p}><path d="m15 18-6-6 6-6"/></svg>;
        case 'loader-2':
            return <svg {...p}><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>;
        case 'sparkles':
            return <svg {...p}><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg>;
        case 'shield-check':
            return <svg {...p}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10"/><path d="m9 12 2 2 4-4"/></svg>;
        case 'shield-alert':
            return <svg {...p}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>;
        case 'shield':
            return <svg {...p}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10"/></svg>;
        case 'file-text':
            return <svg {...p}><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/></svg>;
        case 'clipboard-list':
            return <svg {...p}><rect width="8" height="4" x="8" y="2" rx="1" ry="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><path d="M12 11h4"/><path d="M12 16h4"/><circle cx="9" cy="11" r="1"/><circle cx="9" cy="16" r="1"/></svg>;
        case 'clock':
            return <svg {...p}><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>;
        case 'x-circle':
            return <svg {...p}><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>;
        case 'chevron-down':
            return <svg {...p}><path d="m6 9 6 6 6-6"/></svg>;
        case 'arrow-left':
            return <svg {...p}><path d="m12 19-7-7 7-7"/><path d="M19 12H5"/></svg>;
        case 'arrow-right':
            return <svg {...p}><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>;
        case 'map-pin':
            return <svg {...p}><path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"/><circle cx="12" cy="10" r="3"/></svg>;
        case 'shopping-cart':
            return <svg {...p}><circle cx="8" cy="21" r="1"/><circle cx="19" cy="21" r="1"/><path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"/></svg>;
        case 'shopping-bag':
            return <svg {...p}><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z"/><path d="M3 6h18"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>;
        default:
            return null;
    }
}

// In-App Toast Notification
function Toast({ message, type = "success", onClose }) {
    if (!message) return null;
    const bg = type === "error" ? "bg-red-500" : type === "warning" ? "bg-amber-500" : "bg-emerald-600";
    return (
        <div className={`fixed top-4 left-1/2 -translate-x-1/2 sm:top-auto sm:bottom-6 sm:right-6 sm:left-auto sm:translate-x-0 z-50 flex items-center gap-3 px-4 py-3 rounded-2xl text-white shadow-xl ${bg} transition-all duration-300 max-w-[90vw] animate-in`}>
            <Icon name={type === "error" ? "alert-circle" : type === "warning" ? "alert-triangle" : "check-circle"} size={18} />
            <span className="text-xs sm:text-sm font-semibold truncate">{message}</span>
            <button onClick={onClose} className="p-1 hover:opacity-80 shrink-0"><Icon name="x" size={14} /></button>
        </div>
    );
}

// In-App Confirmation Modal (แทน window.confirm ของเบราว์เซอร์)
function InAppConfirmModal({ dialog, onClose }) {
    if (!dialog) return null;
    return (
        <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto animate-fade-in">
            <div className="bg-white rounded-3xl p-6 max-w-sm w-full shadow-2xl text-center space-y-4 my-auto modal-responsive-card border border-slate-100">
                <div className={`w-14 h-14 rounded-2xl flex items-center justify-center mx-auto ${dialog.isDanger ? 'bg-red-50 text-red-600' : 'bg-emerald-50 text-emerald-600'}`}>
                    <Icon name={dialog.isDanger ? 'alert-triangle' : 'check-circle'} size={28} />
                </div>
                <div>
                    <h3 className="font-bold text-base text-slate-900">{dialog.title}</h3>
                    <p className="text-xs text-slate-500 mt-1">{dialog.message}</p>
                </div>
                <div className="flex gap-2 pt-2">
                    <button
                        onClick={onClose}
                        className="flex-1 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl font-bold text-xs transition tap-bounce">
                        {dialog.cancelText || 'ยกเลิก'}
                    </button>
                    <button
                        onClick={() => {
                            onClose();
                            if (dialog.onConfirm) dialog.onConfirm();
                        }}
                        className={`flex-1 py-2.5 text-white rounded-xl font-bold text-xs shadow-md transition tap-bounce ${dialog.isDanger ? 'bg-red-600 hover:bg-red-700 shadow-red-600/20' : 'bg-emerald-600 hover:bg-emerald-700 shadow-emerald-600/20'}`}>
                        {dialog.confirmText || 'ยืนยัน'}
                    </button>
                </div>
            </div>
        </div>
    );
}

// ==========================================
// Barcode / QR Code Scan Feedback (เสียงติ๊ด + ระบบสั่นเมื่อสแกน)
// ==========================================
let _scanAudioCtx = null;
function getScanAudioContext() {
    try {
        const AudioCtx = window.AudioContext || window.webkitAudioContext;
        if (!AudioCtx) return null;
        if (!_scanAudioCtx || _scanAudioCtx.state === 'closed') {
            _scanAudioCtx = new AudioCtx();
        }
        if (_scanAudioCtx.state === 'suspended') {
            _scanAudioCtx.resume();
        }
        return _scanAudioCtx;
    } catch (e) {
        return null;
    }
}

function playScanFeedback(success = true) {
    try {
        // Haptic feedback (Vibrate on mobile devices)
        if (typeof navigator !== 'undefined' && navigator.vibrate) {
            navigator.vibrate(success ? [60] : [40, 50, 40]);
        }

        const ctx = getScanAudioContext();
        if (!ctx) return;

        if (ctx.state === 'suspended') {
            ctx.resume();
        }

        const osc = ctx.createOscillator();
        const gain = ctx.createGain();

        osc.connect(gain);
        gain.connect(ctx.destination);

        const now = ctx.currentTime;
        if (success) {
            // เสียง "ติ๊ด" คมชัดแบบเครื่องยิงบาร์โค้ด (ความถี่ 1850Hz, 85ms)
            osc.type = 'sine';
            osc.frequency.setValueAtTime(1850, now);
            gain.gain.setValueAtTime(0.28, now);
            gain.gain.exponentialRampToValueAtTime(0.001, now + 0.085);
            osc.start(now);
            osc.stop(now + 0.085);
        } else {
            // เสียงเตือนเมื่อไม่พบบาร์โค้ดในระบบ (ความถี่ 320Hz, 150ms)
            osc.type = 'triangle';
            osc.frequency.setValueAtTime(320, now);
            gain.gain.setValueAtTime(0.22, now);
            gain.gain.exponentialRampToValueAtTime(0.001, now + 0.15);
            osc.start(now);
            osc.stop(now + 0.15);
        }
    } catch (e) {
        // Ignore audio playback errors if restricted by browser
    }
}

// Modern Saving & Loading Screen (หน้าจอ "กำลังบันทึก..." รูปแบบสวยงามทันสมัย - แสดงเฉพาะข้อมูลหลัก)
function ModernLoadingModal({ show, title = "กำลังบันทึก..." }) {
    if (!show) return null;
    return (
        <div className="fixed inset-0 z-[120] bg-slate-900/60 backdrop-blur-md flex items-center justify-center p-4 animate-fade-in overflow-y-auto">
            <div className="bg-white rounded-3xl p-6 sm:p-8 max-w-xs w-full shadow-2xl flex flex-col items-center text-center space-y-4 border border-slate-100 my-auto">
                {/* Modern Glowing Ring Spinner */}
                <div className="relative w-20 h-20 flex items-center justify-center">
                    <div className="absolute inset-0 rounded-full border-4 border-emerald-100"></div>
                    <div className="absolute inset-0 rounded-full border-4 border-emerald-600 border-t-transparent animate-spin"></div>
                    <div className="w-12 h-12 rounded-2xl bg-emerald-50 text-emerald-600 flex items-center justify-center shadow-xs">
                        <Icon name="package-check" size={26} className="animate-pulse" />
                    </div>
                </div>

                <div>
                    <h4 className="font-bold text-base sm:text-lg text-slate-900 tracking-tight">
                        {title}
                    </h4>
                </div>

                {/* Shimmer gradient line */}
                <div className="w-full bg-slate-100 rounded-full h-1.5 overflow-hidden">
                    <div className="bg-gradient-to-r from-emerald-500 via-teal-400 to-emerald-600 h-full w-full animate-pulse rounded-full"></div>
                </div>
            </div>
        </div>
    );
}

// App Sidebar Navigation Component (สไลด์บาร์สำหรับเดสก์ท็อปและมือถือ)
function AppSidebar({
    tab,
    setTab,
    stats,
    userRole,
    currentUser,
    pendingCounts,
    requisitions = [],
    cartCount = 0,
    handleLogout,
    handleExportPdfReport,
    handleExportExcel,
    handleSendTelegramSummary,
    handleResetSeedData,
    onOpenCategorySafety,
    submitting,
    isMobile = false,
    onCloseMobile = () => {}
}) {
    const myPendingCount = useMemo(() => {
        if (!currentUser) return 0;
        const name = (currentUser.name || '').toLowerCase();
        const user = (currentUser.username || '').toLowerCase();
        return (requisitions || []).filter(r => {
            if (r.status !== 'pending') return false;
            const tech = (r.technician || r.technician_name || '').toLowerCase();
            const usr = (r.created_by || r.technician_username || '').toLowerCase();
            return (name && tech === name) || (user && usr === user);
        }).length;
    }, [requisitions, currentUser]);

    const navItems = useMemo(() => {
        const list = [
            { id: 'inventory', label: 'คลังสต็อก', icon: 'boxes' },
            { 
                id: 'checkout', 
                label: userRole.mustRequestApproval ? 'ขอเบิกของ' : 'เบิกของ', 
                icon: 'arrow-up-right',
                badge: cartCount > 0 ? cartCount : undefined
            },
        ];

        if (userRole.isAdmin) {
            list.push({ 
                id: 'approvals', 
                label: 'อนุมัติ', 
                icon: 'shield-check', 
                badge: pendingCounts?.totalPending || 0 
            });
        } else if (userRole.isAds) {
            list.push({ 
                id: 'approvals', 
                label: 'รายการขอเบิก', 
                icon: 'file-text', 
                badge: pendingCounts?.totalPending || 0 
            });
        } else if (userRole.isTech) {
            list.push({ 
                id: 'my-requests', 
                label: 'คำขอเบิกของฉัน', 
                icon: 'clipboard-list', 
                badge: myPendingCount || 0 
            });
        }

        list.push({ id: 'scan', label: 'สแกน', icon: 'qr-code' });

        if (userRole.canManageStock) {
            list.push({ id: 'audit', label: 'ตรวจนับ', icon: 'clipboard-check' });
        }

        list.push(
            { id: 'dashboard', label: 'ภาพรวม', icon: 'bar-chart-3' },
            { id: 'history', label: 'ประวัติ', icon: 'history' }
        );

        return list;
    }, [userRole, pendingCounts, myPendingCount]);

    return (
        <div className="flex flex-col h-full bg-white select-none">
            {/* Header Brand */}
            <div className="p-4 sm:p-5 border-b border-slate-100 flex items-center justify-between">
                <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-2xl bg-emerald-600 flex items-center justify-center text-white shadow-md shadow-emerald-600/20 shrink-0">
                        <Icon name="package-check" size={22} />
                    </div>
                    <div>
                        <div className="flex items-center gap-1.5">
                            <span className="font-bold text-base text-slate-900 tracking-tight leading-none">Stock-Service</span>
                        </div>
                        <span className="text-[10px] text-slate-400 font-medium tracking-wide">PAVARA Application</span>
                    </div>
                </div>
                {isMobile ? (
                    <button 
                        onClick={onCloseMobile}
                        className="w-8 h-8 rounded-full bg-slate-100 text-slate-500 hover:bg-slate-200 flex items-center justify-center transition"
                    >
                        <Icon name="x" size={16} />
                    </button>
                ) : (
                    <span className="text-[10px] bg-emerald-50 text-emerald-700 px-2 py-0.5 rounded-full font-bold border border-emerald-200/60">
                        v{window.APP_VERSION || '1.0.24'}
                    </span>
                )}
            </div>

            {/* Navigation Links */}
            <div className="flex-1 overflow-y-auto p-3 sm:p-4 space-y-1.5 no-scrollbar">
                <div className="text-[11px] font-bold text-slate-400 uppercase tracking-wider px-3 mb-2">
                    เมนูระบบ
                </div>

                {navItems.map(item => {
                    const active = tab === item.id;
                    return (
                        <button
                            key={item.id}
                            onClick={() => {
                                setTab(item.id);
                                if (isMobile) onCloseMobile();
                            }}
                            className={`w-full flex items-center justify-between px-3.5 py-2.5 rounded-2xl font-bold text-xs sm:text-sm transition-all duration-150 group ${
                                active
                                    ? 'bg-emerald-600 text-white shadow-md shadow-emerald-600/20 translate-x-0.5'
                                    : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
                            }`}
                        >
                            <div className="flex items-center gap-3">
                                <div className={`w-8 h-8 rounded-xl flex items-center justify-center transition-colors ${
                                    active ? 'bg-white/20 text-white' : 'bg-slate-100 text-slate-600 group-hover:bg-slate-200'
                                }`}>
                                    <Icon name={item.icon} size={17} />
                                </div>
                                <span>{item.label}</span>
                            </div>
                            
                            <div className="flex items-center gap-1.5">
                                {item.badge !== undefined && item.badge > 0 && (
                                    <span className={`px-2 py-0.5 text-[10px] rounded-full font-bold shadow-xs ${
                                        active ? 'bg-amber-300 text-slate-900' : 'bg-amber-500 text-white animate-pulse'
                                    }`}>
                                        {item.badge}
                                    </span>
                                )}
                                {item.id === 'inventory' && stats.outOfStock > 0 && (
                                    <span className={`px-2 py-0.5 text-[10px] rounded-full font-bold ${
                                        active ? 'bg-red-500 text-white' : 'bg-red-100 text-red-600'
                                    }`}>
                                        {stats.outOfStock}
                                    </span>
                                )}
                                {isMobile && (
                                    <Icon name="chevron-right" size={16} className={active ? 'text-white/80' : 'text-slate-300'} />
                                )}
                            </div>
                        </button>
                    );
                })}

                {/* Admin Management Tools */}
                {userRole.isAdmin && (
                    <div className="pt-4 mt-4 border-t border-slate-100 space-y-1.5">
                        <div className="text-[11px] font-bold text-slate-400 uppercase tracking-wider px-3 mb-2">
                            เครื่องมือจัดการ
                        </div>
                        <button
                            onClick={() => {
                                const exportFn = handleExportPdfReport || handleExportExcel;
                                if (exportFn) {
                                    try { exportFn(); } catch(e) { console.error(e); }
                                }
                                if (isMobile) {
                                    setTimeout(() => onCloseMobile(), 150);
                                }
                            }}
                            className="w-full flex items-center gap-3 px-3.5 py-2 rounded-xl text-xs font-semibold text-slate-600 hover:bg-slate-100 transition"
                        >
                            <div className="w-7 h-7 rounded-lg bg-red-50 text-red-600 flex items-center justify-center">
                                <Icon name="file-text" size={15} />
                            </div>
                            <span>ส่งออกรายงาน PDF</span>
                        </button>

                                <button
                                    onClick={() => {
                                        handleSendTelegramSummary();
                                        if (isMobile) onCloseMobile();
                                    }}
                                    disabled={submitting}
                                    className="w-full flex items-center gap-3 px-3.5 py-2 rounded-xl text-xs font-semibold text-slate-600 hover:bg-sky-50 hover:text-sky-700 transition"
                                >
                                    <div className="w-7 h-7 rounded-lg bg-sky-50 text-sky-600 flex items-center justify-center">
                                        <Icon name="send" size={15} />
                                    </div>
                                    <span>เตือนสต็อก Telegram</span>
                                </button>
                            </div>
                        )}
                    </div>

            {/* Footer Profile & Logout */}
            <div className="p-3.5 sm:p-4 border-t border-slate-100 bg-slate-50/70">
                <div className="flex items-center justify-between gap-2">
                    <div className="flex items-center gap-2.5 min-w-0">
                        {currentUser.photo_url ? (
                            <img 
                                src={window.getDriveThumbnail ? window.getDriveThumbnail(currentUser.photo_url) : currentUser.photo_url} 
                                alt={currentUser.name} 
                                className="w-9 h-9 rounded-full object-cover shrink-0 border border-emerald-300 shadow-xs"
                                onError={(e) => { 
                                    e.target.style.display = 'none'; 
                                    const fallback = e.target.nextElementSibling;
                                    if (fallback) fallback.style.display = 'flex';
                                }}
                            />
                        ) : null}
                        <div 
                            style={{ display: currentUser.photo_url ? 'none' : 'flex' }}
                            className="w-9 h-9 rounded-full bg-emerald-600/10 text-emerald-700 items-center justify-center font-bold text-xs uppercase shrink-0 border border-emerald-200/50 shadow-xs"
                        >
                            {currentUser.name ? currentUser.name.charAt(0) : 'U'}
                        </div>
                        <div className="min-w-0">
                            <div className="text-xs font-bold text-slate-800 truncate">{currentUser.name}</div>
                            <span className={`inline-block text-[10px] font-bold px-1.5 py-0.2 rounded-full ${
                                userRole.isAdmin ? 'bg-amber-100 text-amber-800' : userRole.isAds ? 'bg-blue-100 text-blue-800' : 'bg-emerald-100 text-emerald-800'
                            }`}>
                                {userRole.label}
                            </span>
                        </div>
                    </div>
                    <button
                        onClick={handleLogout}
                        title="ออกจากระบบ"
                        className="p-2 rounded-xl text-red-500 hover:bg-red-50 hover:text-red-700 transition shrink-0 tap-bounce"
                    >
                        <Icon name="log-out" size={16} />
                    </button>
                </div>
            </div>
        </div>
    );
}

// Skeleton Card
function SkeletonCard() {
    return (
        <div className="bg-white p-4 rounded-3xl shadow-xs border border-slate-100 flex flex-col gap-3">
            <div className="skeleton h-32 w-full rounded-2xl"></div>
            <div className="skeleton h-5 w-3/4"></div>
            <div className="skeleton h-4 w-1/2"></div>
            <div className="flex justify-between items-center pt-2">
                <div className="skeleton h-7 w-20"></div>
                <div className="skeleton h-9 w-24 rounded-xl"></div>
            </div>
        </div>
    );
}

// ==========================================
// 0. LOGIN VIEW (หน้าลงชื่อเข้าใช้งาน)
// ==========================================
function LoginView({ onLoginSuccess }) {
    const [username, setUsername] = useState(() => {
        try {
            const saved = JSON.parse(localStorage.getItem('pavara_stock_saved_auth') || '{}');
            return saved.username || '';
        } catch (e) { return ''; }
    });
    const [password, setPassword] = useState(() => {
        try {
            const saved = JSON.parse(localStorage.getItem('pavara_stock_saved_auth') || '{}');
            return saved.password || '';
        } catch (e) { return ''; }
    });
    const [rememberMe, setRememberMe] = useState(true);
    const [showPassword, setShowPassword] = useState(false);
    const [loading, setLoading] = useState(false);
    const [errorMsg, setErrorMsg] = useState('');

    // จดจำการเข้าสู่ระบบอัตโนมัติเมื่อเคยเข้าใช้งานแล้ว
    useEffect(() => {
        try {
            const manualLogout = sessionStorage.getItem('pavara_manual_logout');
            const saved = JSON.parse(localStorage.getItem('pavara_stock_saved_auth') || '{}');
            if (!manualLogout && saved.username && saved.password && (saved.remember !== false)) {
                setLoading(true);
                StockApi.login(saved.username, saved.password)
                    .then(res => {
                        if (res && res.success && res.user) {
                            if (onLoginSuccess) onLoginSuccess(res.user);
                        } else {
                            setLoading(false);
                        }
                    })
                    .catch(() => setLoading(false));
            }
        } catch (e) {
            setLoading(false);
        }
    }, []);

    const handleSubmit = async (e) => {
        if (e && e.preventDefault) e.preventDefault();
        const cleanUser = username.trim();
        const cleanPass = password.trim();

        if (!cleanUser || !cleanPass) {
            setErrorMsg('กรุณากรอกชื่อผู้ใช้งานและรหัสผ่าน');
            return;
        }

        setLoading(true);
        setErrorMsg('');
        try {
            const res = await StockApi.login(cleanUser, cleanPass);
            if (res && res.success && res.user) {
                if (rememberMe) {
                    localStorage.setItem('pavara_stock_saved_auth', JSON.stringify({
                        username: cleanUser,
                        password: cleanPass,
                        remember: true
                    }));
                } else {
                    localStorage.removeItem('pavara_stock_saved_auth');
                }
                sessionStorage.removeItem('pavara_manual_logout');
                onLoginSuccess(res.user);
            } else {
                setErrorMsg((res && res.error) || 'ชื่อผู้ใช้งานหรือรหัสผ่านไม่ถูกต้อง');
            }
        } catch (err) {
            setErrorMsg(toFriendlyError(err));
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen bg-gradient-to-br from-emerald-800 via-teal-900 to-slate-900 flex items-center justify-center p-4 sm:p-6">
            <div className="bg-white rounded-3xl p-6 sm:p-8 w-full max-w-sm shadow-2xl space-y-6">
                {/* Logo & Header */}
                <div className="text-center">
                    <div className="w-20 h-20 rounded-3xl bg-emerald-50 text-emerald-600 flex items-center justify-center mx-auto mb-3 shadow-inner border border-emerald-100">
                        <Icon name="package-check" size={38} />
                    </div>
                    <h1 className="text-xl font-bold text-slate-900 tracking-tight">Stock-Service</h1>
                    <p className="text-xs text-slate-500 mt-1">ระบบสต็อกอุปกรณ์ในเครือ PAVARA</p>
                </div>

                {/* Form */}
                <form onSubmit={handleSubmit} className="space-y-4">
                    {errorMsg && (
                        <div className="p-3 bg-red-50 border border-red-200 rounded-2xl flex items-center gap-2 text-red-700 text-xs">
                            <Icon name="alert-circle" size={16} className="shrink-0" />
                            <span>{errorMsg}</span>
                        </div>
                    )}

                    {/* Username */}
                    <div>
                        <label className="block text-xs font-bold text-slate-700 mb-1.5">ชื่อผู้ใช้งาน</label>
                        <div className="relative">
                            <Icon name="user" size={18} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400" />
                            <input
                                type="text"
                                placeholder="ชื่อผู้ใช้งาน"
                                value={username}
                                onChange={(e) => setUsername(e.target.value)}
                                className="w-full bg-slate-50 border border-slate-200 rounded-2xl pl-10 pr-4 py-3 text-sm focus:outline-hidden focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500"
                                required
                            />
                        </div>
                    </div>

                    {/* Password */}
                    <div>
                        <label className="block text-xs font-bold text-slate-700 mb-1.5">รหัสผ่าน</label>
                        <div className="relative">
                            <Icon name="lock" size={18} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400" />
                            <input
                                type={showPassword ? "text" : "password"}
                                placeholder="รหัสผ่าน"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                className="w-full bg-slate-50 border border-slate-200 rounded-2xl pl-10 pr-11 py-3 text-sm focus:outline-hidden focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500"
                                required
                            />
                            <button
                                type="button"
                                onClick={() => setShowPassword(!showPassword)}
                                className="absolute right-3.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-1">
                                <Icon name={showPassword ? "eye-off" : "eye"} size={18} />
                            </button>
                        </div>
                    </div>

                    {/* Remember Password Checkbox */}
                    <div className="flex items-center justify-between text-xs px-1">
                        <label className="flex items-center gap-2 text-slate-600 cursor-pointer select-none font-medium">
                            <input
                                type="checkbox"
                                checked={rememberMe}
                                onChange={(e) => setRememberMe(e.target.checked)}
                                className="w-4 h-4 text-emerald-600 focus:ring-emerald-500 border-slate-300 rounded cursor-pointer accent-emerald-600"
                            />
                            <span>จดจำรหัสผ่านและเข้าสู่ระบบอัตโนมัติ</span>
                        </label>
                    </div>

                    {/* Submit Button (ตัดไอคอนประตูออกตามคำขอ) */}
                    <button
                        type="submit"
                        disabled={loading}
                        className="w-full py-3.5 bg-emerald-600 hover:bg-emerald-700 active:scale-[0.98] text-white rounded-2xl font-bold text-sm shadow-lg shadow-emerald-600/20 transition flex items-center justify-center gap-2">
                        {loading ? (
                            <>
                                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                                <span>กำลังเข้าสู่ระบบ...</span>
                            </>
                        ) : (
                            <span>เข้าสู่ระบบ</span>
                        )}
                    </button>
                </form>
            </div>
        </div>
    );
}

// คำนวณรหัสอุปกรณ์ถัดไปโดยอิงจากเลขสูงสุดที่มีอยู่ในระบบ (ไม่ซ้ำเดิม)
function getNextItemCode(items = []) {
    let maxNum = 0;
    (items || []).forEach(it => {
        if (it && it.code) {
            const match = it.code.match(/STK-(\d+)/i);
            if (match) {
                const num = parseInt(match[1], 10);
                if (num > maxNum) maxNum = num;
            }
        }
    });
    return 'STK-' + (maxNum + 1).toString().padStart(3, '0');
}

// ==========================================
// MAIN APP COMPONENT
// ==========================================
function App() {
    const [currentUser, setCurrentUser] = useState(StockApi.getCurrentUser());
    const [tab, setTab] = useState('inventory'); // 'inventory', 'checkout', 'scan', 'audit', 'dashboard', 'history'
    const [items, setItems] = useState([]);
    const [projects, setProjects] = useState([]);
    const [transactions, setTransactions] = useState([]);
    const [loading, setLoading] = useState(true);
    const [submitting, setSubmitting] = useState(false);
    const [toast, setToast] = useState(null);
    const [confirmDialog, setConfirmDialog] = useState(null);
    const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

    // Filter & Search
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedCategory, setSelectedCategory] = useState('ทั้งหมด');
    const [stockFilter, setStockFilter] = useState('all'); // 'all', 'out', 'low'

    // Modals
    const [editingItem, setEditingItem] = useState(null);
    const [checkoutTarget, setCheckoutTarget] = useState(null);
    const [convertTarget, setConvertTarget] = useState(null);
    const [labelPrintItem, setLabelPrintItem] = useState(null);
    const [showCategorySafetyModal, setShowCategorySafetyModal] = useState(false);
    const [categorySafetyStocks, setCategorySafetyStocks] = useState(() => StockApi.getCategorySafetyStocks());

    // Requisitions & Approvals State (ระบบขอเบิกและอนุมัติ)
    const [requisitions, setRequisitions] = useState([]);
    const [pendingCounts, setPendingCounts] = useState({ totalPending: 0, byItem: {}, byVariant: {}, pendingReqs: [] });

    // ตะกร้าเบิกอุปกรณ์หลายรายการ (Multi-item Picking Cart)
    const [checkoutCart, setCheckoutCart] = useState(() => {
        try {
            const saved = localStorage.getItem('pavara_stock_checkout_cart_v1');
            return saved ? JSON.parse(saved) : [];
        } catch (e) {
            return [];
        }
    });

    useEffect(() => {
        try {
            localStorage.setItem('pavara_stock_checkout_cart_v1', JSON.stringify(checkoutCart));
        } catch (e) {}
    }, [checkoutCart]);

    const addToCheckoutCart = (item, variant, qty = 1) => {
        if (!item) return false;
        const numQty = Number(qty) || 1;
        const targetVariant = variant || (item.variants && item.variants.length > 0 ? item.variants[0] : null);
        const variantId = targetVariant ? targetVariant.id : null;
        const variantName = targetVariant ? targetVariant.name : 'ปกติ';
        const unit = targetVariant ? targetVariant.unit : item.unit;
        const maxQty = targetVariant ? (Number(targetVariant.qty) || 0) : (Number(item.total_qty) || 0);

        if (maxQty <= 0) {
            showToast(`อุปกรณ์ "${item.name}" สินค้าหมด`, "warning");
            return false;
        }

        let isAdded = true;
        setCheckoutCart(prev => {
            const idx = prev.findIndex(c => c.itemId === item.id && (c.variantId || null) === variantId);
            if (idx >= 0) {
                const next = [...prev];
                const newQty = Math.min(maxQty, next[idx].qty + numQty);
                next[idx] = {
                    ...next[idx],
                    qty: newQty,
                    maxQty: maxQty
                };
                return next;
            } else {
                return [...prev, {
                    cartId: `${item.id}-${variantId || 'base'}-${Date.now()}`,
                    itemId: item.id,
                    itemCode: item.code,
                    itemName: item.name,
                    itemImage: item.image_url || '',
                    variantId: variantId,
                    variantName: variantName,
                    qty: Math.min(maxQty, numQty),
                    unit: unit,
                    maxQty: maxQty
                }];
            }
        });
        showToast(`เพิ่ม "${item.name}" ลงรายการแล้ว`);
        return isAdded;
    };

    const updateCartItemQty = (cartId, newQty) => {
        setCheckoutCart(prev => prev.map(c => {
            if (c.cartId === cartId) {
                const clamped = Math.max(1, Math.min(c.maxQty, Number(newQty) || 1));
                return { ...c, qty: clamped };
            }
            return c;
        }));
    };

    const removeCartItem = (cartId) => {
        setCheckoutCart(prev => prev.filter(c => c.cartId !== cartId));
    };

    const clearCheckoutCart = () => {
        setCheckoutCart([]);
    };

    // แยกสิทธิ์ผู้ใช้งานตามมาตรฐาน PAVARA Central Roles
    const userRole = useMemo(() => {
        if (!currentUser) return { type: 'guest', label: 'ผู้เยี่ยมชม', isAdmin: false, isAds: false, isTech: false, canManageStock: false, canApprove: false, canDirectCheckout: false, mustRequestApproval: false };
        const r = (currentUser.role || '').toLowerCase().trim();
        const isAdmin = r === 'admin' || currentUser.username === 'admin';
        const isAds = r === 'user ads' || r.includes('ads');
        const isTech = r === 'user tc' || r === 'user tcs' || r.includes('tc') || (!isAdmin && !isAds);

        return {
            type: isAdmin ? 'admin' : (isAds ? 'ads' : (isTech ? 'technician' : 'viewer')),
            label: isAdmin ? 'ADMIN' : (isAds ? 'USER ADS' : (r === 'user tcs' ? 'USER TCS' : 'USER TC')),
            isAdmin,             // role "admin"
            isAds,               // role "user ads"
            isTech,              // role "user tc", "user tcs"
            canApprove: isAdmin, // role "admin" อนุมัติการเบิกได้คนเดียว
            canManageStock: isAdmin || isAds, // เพิ่ม, แก้ไข, ลบ, ตรวจนับ
            canDirectCheckout: isAdmin || isAds, // เบิกตัดสต็อกได้ทันที
            mustRequestApproval: isTech && !isAdmin && !isAds // ต้องรอ Admin อนุมัติ
        };
    }, [currentUser]);

    const showToast = (message, type = "success") => {
        setToast({ message, type });
        setTimeout(() => setToast(null), 3500);
    };

    const openConfirm = (opts) => {
        setConfirmDialog(opts);
    };

    // โหลดข้อมูลทั้งหมด
    const loadAllData = async () => {
        setLoading(true);
        try {
            const [fetchedItems, fetchedProjects, fetchedTx, fetchedReqs, pCounts] = await Promise.all([
                StockApi.getItems(),
                StockApi.getProjects(),
                StockApi.getTransactions(),
                StockApi.getRequisitions(),
                StockApi.getPendingCounts()
            ]);
            setItems(fetchedItems || []);
            setProjects(fetchedProjects || []);
            setTransactions(fetchedTx || []);
            setRequisitions(fetchedReqs || []);
            setPendingCounts(pCounts || { totalPending: 0, byItem: {}, byVariant: {} });
            setCategorySafetyStocks(StockApi.getCategorySafetyStocks());
        } catch (err) {
            showToast(toFriendlyError(err), "error");
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (currentUser) {
            loadAllData();

            // ดึงรูปโปรไฟล์ล่าสุดจาก central_users อัตโนมัติ
            StockApi.refreshUserProfile().then(updated => {
                if (updated && updated.photo_url && updated.photo_url !== currentUser.photo_url) {
                    setCurrentUser(prev => ({ ...prev, photo_url: updated.photo_url }));
                }
            }).catch(() => {});

            // เชื่อมต่อ Supabase Realtime เมื่อมีการเปลี่ยนแปลงตาราง
            const unsubscribe = StockApi.subscribeRealtime(() => {
                StockApi.getItems().then(fetched => setItems(fetched || [])).catch(() => {});
                StockApi.getTransactions().then(fetchedTx => setTransactions(fetchedTx || [])).catch(() => {});
                StockApi.getRequisitions().then(fetchedReqs => setRequisitions(fetchedReqs || [])).catch(() => {});
                StockApi.getPendingCounts().then(pc => setPendingCounts(pc || { totalPending: 0, byItem: {}, byVariant: {} })).catch(() => {});
            });

            return () => {
                if (unsubscribe) unsubscribe();
            };
        }
    }, [currentUser?.username || currentUser?.id]);

    // การคำนวณสถิติ
    const stats = useMemo(() => {
        let totalItems = items.length;
        let outOfStock = 0;
        let lowStock = 0;
        let totalValue = 0;

        items.forEach(item => {
            const qty = Number(item.total_qty) || 0;
            const catThreshold = categorySafetyStocks[item.category];
            const reorder = (catThreshold !== undefined) ? Number(catThreshold) : (Number(item.reorder_point) || 5);
            const price = Number(item.cost_price) || 0;
            totalValue += qty * price;

            if (qty <= 0) outOfStock++;
            else if (qty <= reorder) lowStock++;
        });

        return { totalItems, outOfStock, lowStock, totalValue };
    }, [items, categorySafetyStocks]);

    // รายการที่ผ่านการค้นหาและกรอง
    const filteredItems = useMemo(() => {
        return items.filter(item => {
            const matchesSearch = !searchQuery || 
                item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                item.code.toLowerCase().includes(searchQuery.toLowerCase()) ||
                (item.category && item.category.toLowerCase().includes(searchQuery.toLowerCase()));

            const matchesCategory = selectedCategory === 'ทั้งหมด' || item.category === selectedCategory;

            const qty = Number(item.total_qty) || 0;
            const catThreshold = categorySafetyStocks[item.category];
            const reorder = (catThreshold !== undefined) ? Number(catThreshold) : (Number(item.reorder_point) || 5);
            let matchesStock = true;
            if (stockFilter === 'out') matchesStock = (qty <= 0);
            if (stockFilter === 'low') matchesStock = (qty > 0 && qty <= reorder);

            return matchesSearch && matchesCategory && matchesStock;
        });
    }, [items, searchQuery, selectedCategory, stockFilter, categorySafetyStocks]);

    // รายการเมนูด้านล่างบนมือถือ แยกตามสิทธิ์
    const mobileNavTabs = useMemo(() => {
        const myPending = (requisitions || []).filter(r => {
            if (r.status !== 'pending') return false;
            const tech = (r.technician || r.technician_name || '').toLowerCase();
            const usr = (r.created_by || r.technician_username || '').toLowerCase();
            const name = (currentUser?.name || '').toLowerCase();
            const user = (currentUser?.username || '').toLowerCase();
            return (name && tech === name) || (user && usr === user);
        }).length;

        if (userRole.isAdmin) {
            return [
                { id: 'inventory', label: 'สต็อก', icon: 'boxes' },
                { id: 'approvals', label: 'อนุมัติ', icon: 'shield-check', badge: pendingCounts?.totalPending },
                { id: 'scan', label: 'สแกน', icon: 'qr-code', isCenter: true },
                { id: 'checkout', label: 'เบิกของ', icon: 'arrow-up-right', badge: checkoutCart.length > 0 ? checkoutCart.length : undefined },
                { id: 'dashboard', label: 'สรุป', icon: 'bar-chart-3' },
            ];
        } else if (userRole.isAds) {
            return [
                { id: 'inventory', label: 'สต็อก', icon: 'boxes' },
                { id: 'approvals', label: 'ขอเบิก', icon: 'file-text', badge: pendingCounts?.totalPending },
                { id: 'scan', label: 'สแกน', icon: 'qr-code', isCenter: true },
                { id: 'checkout', label: 'เบิกของ', icon: 'arrow-up-right', badge: checkoutCart.length > 0 ? checkoutCart.length : undefined },
                { id: 'audit', label: 'ตรวจนับ', icon: 'clipboard-check' },
            ];
        } else {
            return [
                { id: 'inventory', label: 'สต็อก', icon: 'boxes' },
                { id: 'checkout', label: 'ขอเบิก', icon: 'arrow-up-right', badge: checkoutCart.length > 0 ? checkoutCart.length : undefined },
                { id: 'scan', label: 'สแกน', icon: 'qr-code', isCenter: true },
                { id: 'my-requests', label: 'คำขอฉัน', icon: 'clipboard-list', badge: myPending },
                { id: 'dashboard', label: 'สรุป', icon: 'bar-chart-3' },
            ];
        }
    }, [userRole, pendingCounts, requisitions, currentUser, checkoutCart.length]);

    // ออกจากระบบ (ใช้ In-App Confirm Modal)
    const handleLogout = () => {
        openConfirm({
            title: 'ออกจากระบบ',
            message: 'คุณต้องการออกจากระบบ Stock-Service ใช่หรือไม่?',
            confirmText: 'ออกจากระบบ',
            isDanger: true,
            onConfirm: () => {
                try { sessionStorage.setItem('pavara_manual_logout', 'true'); } catch(e) {}
                StockApi.logout();
                setCurrentUser(null);
                showToast("ออกจากระบบแล้ว");
            }
        });
    };

    // ลบสินค้า (Admin & User ADS Only, In-App Confirm)
    const handleDeleteItem = (itemId) => {
        if (!userRole.canManageStock) return showToast("เฉพาะผู้ดูแลระบบ (Admin) หรือ User ADS เท่านั้นที่ลบได้", "error");
        openConfirm({
            title: 'ลบอุปกรณ์',
            message: 'ยืนยันต้องการลบอุปกรณ์นี้ออกจากสต็อก?',
            confirmText: 'ลบรายการ',
            isDanger: true,
            onConfirm: async () => {
                setSubmitting(true);
                try {
                    await StockApi.deleteItem(itemId);
                    setItems(prev => prev.filter(i => i.id !== itemId));
                    showToast("ลบรายการแล้ว");
                } catch (err) {
                    showToast(toFriendlyError(err), "error");
                } finally {
                    setSubmitting(false);
                }
            }
        });
    };

    // ส่งออกรายงานสต็อกเป็นรูปแบบ PDF ขนาด A4 จัดกลุ่มตามหมวดหมู่ พร้อมไฮไลต์สีจุดสั่งซื้อ/หมดสต็อก
    const handleExportPdfReport = () => {
        try {
            if (!items || items.length === 0) {
                showToast("ไม่มีข้อมูลสินค้าในสต็อกสำหรับออกรายงาน", "warning");
                return;
            }

            const now = new Date();
            const pad = (n) => String(n).padStart(2, '0');
            const todayStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
            const reportFileName = `PAVARA_Stock_Report_${todayStr}`;

            // จัดกลุ่มอุปกรณ์ตามหมวดหมู่
            const groups = {};
            items.forEach(it => {
                const cat = it.category?.trim() || 'ทั่วไป';
                if (!groups[cat]) groups[cat] = [];
                groups[cat].push(it);
            });

            const htmlContent = `<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>${reportFileName}</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Thai:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        @page {
            size: A4 portrait;
            margin: 10mm 10mm 12mm 10mm;
        }
        * {
            box-sizing: border-box;
            font-family: 'Noto Sans Thai', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        body {
            margin: 0;
            padding: 0;
            color: #0f172a;
            font-size: 11px;
            line-height: 1.35;
            background: #fff;
        }
        .header {
            border-bottom: 2px solid #00A651;
            padding-bottom: 8px;
            margin-bottom: 12px;
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
        }
        .brand {
            font-size: 17px;
            font-weight: bold;
            color: #0f172a;
            letter-spacing: -0.3px;
        }
        .brand span {
            color: #00A651;
        }
        .doc-title {
            font-size: 13px;
            font-weight: 600;
            color: #334155;
            margin-top: 2px;
        }
        .meta {
            text-align: right;
            font-size: 10px;
            color: #64748b;
        }
        .summary-bar {
            display: flex;
            gap: 12px;
            margin-bottom: 12px;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            padding: 8px 12px;
            border-radius: 8px;
            font-size: 11px;
        }
        .summary-item strong {
            color: #0f172a;
        }
        .cat-title {
            font-size: 12px;
            font-weight: bold;
            color: #0f172a;
            background: #f1f5f9;
            padding: 5px 10px;
            border-left: 4px solid #00A651;
            margin-top: 12px;
            margin-bottom: 6px;
            page-break-after: avoid;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 8px;
            font-size: 10px;
        }
        tr {
            page-break-inside: avoid;
        }
        th {
            background: #f8fafc;
            color: #475569;
            font-weight: bold;
            border: 1px solid #cbd5e1;
            padding: 5px 6px;
            text-align: left;
            font-size: 9.5px;
        }
        td {
            border: 1px solid #e2e8f0;
            padding: 4.5px 6px;
            vertical-align: middle;
        }
        .text-center { text-align: center; }
        .text-right { text-align: right; }
        .font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; }
        .status-badge {
            display: inline-block;
            padding: 1.5px 5px;
            border-radius: 4px;
            font-size: 9px;
            font-weight: bold;
        }
        .row-out {
            background-color: #fee2e2 !important;
            color: #991b1b;
        }
        .row-out .status-badge {
            background: #fca5a5;
            color: #7f1d1d;
        }
        .row-low {
            background-color: #fef3c7 !important;
            color: #92400e;
        }
        .row-low .status-badge {
            background: #fde68a;
            color: #78350f;
        }
        .status-normal {
            background: #dcfce7;
            color: #166534;
        }
        .footer {
            margin-top: 16px;
            padding-top: 8px;
            border-top: 1px solid #cbd5e1;
            font-size: 9px;
            color: #94a3b8;
            display: flex;
            justify-content: space-between;
        }
        @media print {
            body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .no-print { display: none !important; }
        }
    </style>
</head>
<body>
    <div class="no-print" style="background:#0f172a; color:#fff; padding:10px 16px; display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; border-radius:8px;">
        <span>📄 รายงานสต็อกอุปกรณ์ PAVARA (ขนาด A4) พร้อมสั่งพิมพ์หรือบันทึกเป็น PDF</span>
        <button onclick="window.print()" style="background:#00A651; color:#fff; border:none; padding:6px 16px; border-radius:6px; font-weight:bold; cursor:pointer;">พิมพ์ / บันทึก PDF</button>
    </div>

    <div class="header">
        <div>
            <div class="brand">PAVARA <span>STOCK-SERVICE</span></div>
            <div class="doc-title">รายงานสถานะสต็อกอุปกรณ์และยอดคงเหลือ</div>
        </div>
        <div class="meta">
            <div>วันที่ออกเอกสาร: <b>${new Date().toLocaleDateString('th-TH', { year: 'numeric', month: 'long', day: 'numeric' })}</b></div>
            <div>เวลา: ${new Date().toLocaleTimeString('th-TH', { hour: '2-digit', minute: '2-digit' })} น.</div>
        </div>
    </div>

    <div class="summary-bar">
        <div>อุปกรณ์ทั้งหมด: <strong>${items.length} รายการ</strong></div>
        <div style="color:#b91c1c;">• หมดสต็อก: <strong>${stats.outOfStock} รายการ</strong></div>
        <div style="color:#b45309;">• ใกล้หมด: <strong>${stats.lowStock} รายการ</strong></div>
        <div style="color:#15803d;">• พร้อมใช้: <strong>${Math.max(0, items.length - stats.outOfStock - stats.lowStock)} รายการ</strong></div>
    </div>

    ${Object.entries(groups).map(([catName, catItems]) => `
        <div class="cat-title">หมวดหมู่: ${catName} (${catItems.length} รายการ)</div>
        <table>
            <thead>
                <tr>
                    <th style="width:30px;" class="text-center">ลำดับ</th>
                    <th style="width:75px;">รหัส</th>
                    <th>ชื่ออุปกรณ์</th>
                    <th style="width:65px;" class="text-center">จุดสั่งซื้อ</th>
                    <th style="width:65px;" class="text-right">คงเหลือ</th>
                    <th style="width:45px;" class="text-center">หน่วย</th>
                    <th style="width:70px;" class="text-center">สถานะ</th>
                    <th>สถานะย่อย</th>
                </tr>
            </thead>
            <tbody>
                ${catItems.map((item, idx) => {
                    const qty = Number(item.total_qty) || 0;
                    const catThreshold = categorySafetyStocks[item.category];
                    const reorder = (catThreshold !== undefined) ? Number(catThreshold) : (Number(item.reorder_point) || 5);
                    const isOut = qty <= 0;
                    const isLow = qty > 0 && qty <= reorder;
                    const rowClass = isOut ? 'row-out' : (isLow ? 'row-low' : '');
                    const statusText = isOut ? 'หมดสต็อก' : (isLow ? 'ใกล้หมด' : 'พร้อมใช้');
                    const badgeClass = isOut ? '' : (isLow ? '' : 'status-normal');
                    const variantsStr = (item.variants || []).map(v => `${v.name}: ${v.qty}`).join(', ') || '-';

                    return `
                        <tr class="${rowClass}">
                            <td class="text-center">${idx + 1}</td>
                            <td class="font-mono font-bold">${item.code || '-'}</td>
                            <td><b>${item.name}</b></td>
                            <td class="text-center font-mono">${reorder}</td>
                            <td class="text-right font-mono font-bold">${qty}</td>
                            <td class="text-center">${item.unit}</td>
                            <td class="text-center"><span class="status-badge ${badgeClass}">${statusText}</span></td>
                            <td style="color:#64748b; font-size:9px;">${variantsStr}</td>
                        </tr>
                    `;
                }).join('')}
            </tbody>
        </table>
    `).join('')}

    <div class="footer">
        <div>PAVARA Application - ระบบบริหารจัดการสต็อกอุปกรณ์</div>
        <div>หน้าเอกสารรายงานสรุป A4 (ไฟล์: ${reportFileName}.pdf)</div>
    </div>

    <script>
        function triggerPrint() {
            try {
                window.focus();
                window.print();
            } catch(e) {
                console.error('Trigger print error:', e);
            }
        }
        if (document.readyState === 'complete') {
            setTimeout(triggerPrint, 500);
        } else {
            window.addEventListener('load', function() {
                setTimeout(triggerPrint, 500);
            });
            setTimeout(triggerPrint, 1000);
        }
    </script>
</body>
</html>`;

            // สร้าง Blob URL เพื่อความเสถียรและป้องกันการบล็อกของเบราว์เซอร์
            const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' });
            const blobUrl = URL.createObjectURL(blob);

            let opened = false;
            let printWindow = null;

            try {
                printWindow = window.open(blobUrl, '_blank');
                if (printWindow && !printWindow.closed && typeof printWindow.closed !== 'undefined') {
                    opened = true;
                    try { printWindow.focus(); } catch (e) {}
                    showToast("เปิดหน้าพิมพ์รายงาน PDF สำเร็จ! (เลือก 'บันทึกเป็น PDF')");
                }
            } catch (e) {
                opened = false;
            }

            // หากเบราว์เซอร์บล็อกป็อปอัป (Popup Blocker) ให้ใช้ hidden iframe สั่งพิมพ์โดยตรงอัตโนมัติ 100%
            if (!opened) {
                let iframe = document.getElementById('pdf-report-print-frame');
                if (iframe && document.body.contains(iframe)) {
                    document.body.removeChild(iframe);
                }
                iframe = document.createElement('iframe');
                iframe.id = 'pdf-report-print-frame';
                iframe.style.position = 'fixed';
                iframe.style.right = '0';
                iframe.style.bottom = '0';
                iframe.style.width = '0';
                iframe.style.height = '0';
                iframe.style.border = '0';
                iframe.style.opacity = '0';
                iframe.style.pointerEvents = 'none';
                iframe.src = blobUrl;
                document.body.appendChild(iframe);

                iframe.onload = () => {
                    setTimeout(() => {
                        try {
                            iframe.contentWindow.focus();
                            iframe.contentWindow.print();
                            showToast("กำลังเปิดหน้าต่างพิมพ์รายงาน PDF (เลือก 'บันทึกเป็น PDF')...");
                        } catch (err) {
                            console.warn("Iframe print error:", err);
                            const link = document.createElement('a');
                            link.href = blobUrl;
                            link.target = '_blank';
                            link.click();
                        }
                    }, 400);
                };

                setTimeout(() => {
                    const f = document.getElementById('pdf-report-print-frame');
                    if (f && document.body.contains(f)) {
                        document.body.removeChild(f);
                    }
                    URL.revokeObjectURL(blobUrl);
                }, 120000);
            } else {
                setTimeout(() => {
                    URL.revokeObjectURL(blobUrl);
                }, 120000);
            }
        } catch (err) {
            console.error("PDF Export error:", err);
            showToast("ไม่สามารถสร้างรายงาน PDF ได้: " + err.message, "error");
        }
    };
    const handleExportExcel = handleExportPdfReport;

    // รีเซ็ตข้อมูล 67 รายการเริ่มต้น (Admin Only, In-App Confirm)
    const handleResetSeedData = () => {
        if (!userRole.isAdmin) return showToast("เฉพาะผู้ดูแลระบบ (Admin) เท่านั้นที่ทำได้", "error");
        openConfirm({
            title: 'รีเซ็ตข้อมูลสต็อก',
            message: 'ต้องการรีเซ็ตข้อมูลกลับเป็น 67 รายการเริ่มต้นจากระบบ PAVARA?',
            confirmText: 'ยืนยันรีเซ็ต',
            isDanger: true,
            onConfirm: async () => {
                setSubmitting(true);
                try {
                    const data = await StockApi.resetSeedData();
                    setItems(data);
                    showToast("รีเซ็ตสต็อก 67 รายการสำเร็จ!");
                } catch (err) {
                    showToast(toFriendlyError(err), "error");
                } finally {
                    setSubmitting(false);
                }
            }
        });
    };

    // ส่งแจ้งเตือน Telegram สรุปสต็อกวิกฤต (Admin Only)
    const handleSendTelegramSummary = async () => {
        if (!userRole.isAdmin) return showToast("เฉพาะผู้ดูแลระบบ (Admin) เท่านั้นที่ทำได้", "error");
        setSubmitting(true);
        try {
            await StockApi.sendLowStockTelegramAlert();
            showToast("ส่งรายงานเข้า Telegram แล้ว!");
        } catch (err) {
            showToast(toFriendlyError(err), "error");
        } finally {
            setSubmitting(false);
        }
    };

    // ถ้ายังไม่ได้เข้าสู่ระบบ แสดงหน้าจอ Login View
    if (!currentUser) {
        return (
            <>
                <LoginView 
                    onLoginSuccess={(user) => {
                        StockApi.setCurrentUser(user);
                        try { sessionStorage.removeItem('pavara_manual_logout'); } catch(e) {}
                        setCurrentUser(user);
                        showToast(`ยินดีต้อนรับคุณ ${user.name}`);
                    }} 
                />
                <Toast message={toast?.message} type={toast?.type} onClose={() => setToast(null)} />
            </>
        );
    }

    return (
        <div className="min-h-screen flex bg-slate-50 font-sans">
            {/* Modern Saving & Loading Screen */}
            <ModernLoadingModal 
                show={submitting} 
                title="กำลังบันทึก..." 
            />

            {/* 1. Desktop Permanent Left Sidebar (md:flex) */}
            <aside className="hidden md:flex flex-col w-64 lg:w-72 bg-white border-r border-slate-200/80 sticky top-0 h-screen shrink-0 z-30 shadow-xs">
                <AppSidebar 
                    tab={tab}
                    setTab={setTab}
                    stats={stats}
                    userRole={userRole}
                    currentUser={currentUser}
                    pendingCounts={pendingCounts}
                    requisitions={requisitions}
                    cartCount={checkoutCart.length}
                    handleLogout={handleLogout}
                    handleExportPdfReport={handleExportPdfReport}
                    handleExportExcel={handleExportExcel}
                    handleSendTelegramSummary={handleSendTelegramSummary}
                    handleResetSeedData={handleResetSeedData}
                    onOpenCategorySafety={() => setShowCategorySafetyModal(true)}
                    submitting={submitting}
                />
            </aside>

            {/* 2. Mobile Slide-out Drawer Sidebar (สไลด์บาร์) */}
            {isMobileMenuOpen && (
                <div className="fixed inset-0 z-50 md:hidden flex pointer-events-auto">
                    <div 
                        className="fixed inset-0 bg-slate-900/60 backdrop-blur-xs animate-fade-in"
                        onClick={() => setIsMobileMenuOpen(false)}
                    />
                    <aside className="relative w-72 max-w-[85vw] bg-white h-full shadow-2xl flex flex-col z-10 animate-slide-right">
                        <AppSidebar 
                            tab={tab}
                            setTab={setTab}
                            stats={stats}
                            userRole={userRole}
                            currentUser={currentUser}
                            pendingCounts={pendingCounts}
                            requisitions={requisitions}
                            cartCount={checkoutCart.length}
                            handleLogout={handleLogout}
                            handleExportPdfReport={handleExportPdfReport}
                            handleExportExcel={handleExportExcel}
                            handleSendTelegramSummary={handleSendTelegramSummary}
                            handleResetSeedData={handleResetSeedData}
                            onOpenCategorySafety={() => setShowCategorySafetyModal(true)}
                            submitting={submitting}
                            isMobile={true}
                            onCloseMobile={() => setIsMobileMenuOpen(false)}
                        />
                    </aside>
                </div>
            )}

            {/* 3. Main Content Wrapper */}
            <div className="flex-1 flex flex-col min-w-0 pb-24 md:pb-8">
                {/* Modern Header Bar */}
                <header className="sticky top-0 z-20 bg-white/95 backdrop-blur-md border-b border-slate-200/80 px-4 sm:px-6 py-2.5 sm:py-3.5 flex items-center justify-between shadow-xs">
                    {/* Left: Mobile Menu Hamburger Button + Page Title */}
                    <div className="flex items-center gap-2.5 sm:gap-3">
                        <button
                            onClick={() => setIsMobileMenuOpen(true)}
                            className="md:hidden p-2 -ml-1 text-slate-700 hover:bg-slate-100 rounded-xl transition tap-bounce"
                            title="เปิดเมนูสไลด์บาร์"
                        >
                            <Icon name="menu" size={22} />
                        </button>
                        <div>
                            <h2 className="font-bold text-base sm:text-lg text-slate-900 tracking-tight leading-none">
                                {
                                    tab === 'inventory' ? 'รายการ' :
                                    tab === 'checkout' ? (userRole.mustRequestApproval ? 'ขอเบิกอุปกรณ์' : 'เบิกอุปกรณ์') :
                                    tab === 'approvals' ? (userRole.isAdmin ? 'อนุมัติ' : 'อุปกรณ์ที่เบิก') :
                                    tab === 'my-requests' ? 'คำขอเบิกอุปกรณ์ของฉัน' :
                                    tab === 'scan' ? 'สแกน' :
                                    tab === 'audit' ? 'ตรวจนับสต็อกประจำงวด' :
                                    tab === 'dashboard' ? 'ภาพรวมสต็อกและแจ้งเตือน' :
                                    tab === 'history' ? 'ประวัติ' : 'รายการ'
                                }
                            </h2>
                        </div>
                    </div>
                </header>

            {/* Main Content Area */}
            <main className="flex-1 max-w-7xl w-full mx-auto px-3.5 sm:px-6 py-3.5 sm:py-5">
                {/* 1. INVENTORY CATALOG VIEW */}
                {tab === 'inventory' && (
                    <InventoryView 
                        items={filteredItems}
                        allItems={items}
                        loading={loading}
                        stats={stats}
                        canManageStock={userRole.canManageStock}
                        pendingCounts={pendingCounts}
                        categorySafetyStocks={categorySafetyStocks}
                        searchQuery={searchQuery}
                        setSearchQuery={setSearchQuery}
                        selectedCategory={selectedCategory}
                        setSelectedCategory={setSelectedCategory}
                        stockFilter={stockFilter}
                        setStockFilter={setStockFilter}
                        onAddItem={() => {
                            const defCat = 'อุปกรณ์หัวจ่าย';
                            const defReorder = (categorySafetyStocks && categorySafetyStocks[defCat] !== undefined)
                                ? categorySafetyStocks[defCat]
                                : 5;
                            setEditingItem({ 
                                code: getNextItemCode(items), 
                                name: '',
                                category: defCat,
                                unit: 'ชิ้น', 
                                reorder_point: defReorder, 
                                cost_price: 0, 
                                notes: '',
                                variants: [
                                    { id: 'var-' + Date.now(), condition_type: 'new', name: 'ของใหม่', qty: 0, unit: 'ชิ้น' }
                                ] 
                            });
                        }}
                        onEditItem={(item) => setEditingItem(item)}
                        onDeleteItem={handleDeleteItem}
                        onQuickCheckout={(item) => setCheckoutTarget(item)}
                        onConvertVariant={(item) => setConvertTarget(item)}
                        onPrintLabel={(item) => setLabelPrintItem(item)}
                        onOpenCategorySafety={() => setShowCategorySafetyModal(true)}
                    />
                )}

                {/* 2. CHECKOUT VIEW */}
                {tab === 'checkout' && (
                    <CheckoutView 
                        items={items}
                        projects={projects}
                        currentUser={currentUser}
                        userRole={userRole}
                        pendingCounts={pendingCounts}
                        requisitions={requisitions}
                        transactions={transactions}
                        cart={checkoutCart}
                        onAddToCart={addToCheckoutCart}
                        onUpdateCartQty={updateCartItemQty}
                        onRemoveCartItem={removeCartItem}
                        onClearCart={clearCheckoutCart}
                        onNavigateToScan={() => setTab('scan')}
                        onNavigateToMyRequests={() => setTab('my-requests')}
                        onNavigateToHistory={() => setTab('history')}
                        onSuccess={(targetTab) => {
                            loadAllData();
                            if (targetTab) {
                                setTab(targetTab);
                            } else if (userRole?.mustRequestApproval) {
                                setTab('my-requests');
                            } else {
                                setTab('history');
                            }
                        }}
                        showToast={showToast}
                    />
                )}

                {/* 2.5 APPROVALS & REQUISITIONS VIEW */}
                {(tab === 'approvals' || tab === 'my-requests') && (
                    <ApprovalManagementView 
                        requisitions={requisitions}
                        items={items}
                        currentUser={currentUser}
                        userRole={userRole}
                        onSuccess={loadAllData}
                        showToast={showToast}
                        openConfirm={openConfirm}
                    />
                )}

                {/* 3. SCANNER VIEW */}
                {tab === 'scan' && (
                    <ScannerView 
                        items={items}
                        projects={projects}
                        currentUser={currentUser}
                        userRole={userRole}
                        cart={checkoutCart}
                        onAddToCart={addToCheckoutCart}
                        onUpdateCartQty={updateCartItemQty}
                        onRemoveCartItem={removeCartItem}
                        onNavigateToCheckout={() => setTab('checkout')}
                        onSuccess={() => { loadAllData(); showToast("ทำรายการสำเร็จ!"); }}
                        showToast={showToast}
                    />
                )}

                {/* 4. AUDIT MODE VIEW (Admin and ADS only) */}
                {tab === 'audit' && (
                    userRole.canManageStock ? (
                        <AuditModeView 
                            items={items}
                            currentUser={currentUser}
                            isAdmin={userRole.isAdmin}
                            openConfirm={openConfirm}
                            onSuccess={() => { loadAllData(); showToast("ปรับยอดตรวจนับสำเร็จ!"); }}
                            showToast={showToast}
                        />
                    ) : (
                        <div className="text-center py-16 bg-white rounded-3xl border border-slate-200">
                            <Icon name="alert-triangle" size={36} className="text-amber-500 mx-auto mb-2" />
                            <h3 className="font-bold text-slate-800">ไม่มีสิทธิ์เข้าถึงเมนูตรวจนับสต็อก</h3>
                            <p className="text-xs text-slate-400 mt-1">เฉพาะ Admin และ User ADS เท่านั้นที่สามารถตรวจนับสต็อกได้</p>
                        </div>
                    )
                )}

                {/* 5. DASHBOARD VIEW */}
                {tab === 'dashboard' && (
                    <DashboardView 
                        stats={stats} 
                        items={items} 
                        transactions={transactions}
                        isAdmin={userRole.isAdmin}
                        categorySafetyStocks={categorySafetyStocks}
                        onSelectFilter={(f) => { setStockFilter(f); setTab('inventory'); }}
                        onOpenScan={() => setTab('scan')}
                        onOpenCheckout={() => setTab('checkout')}
                        onOpenAudit={() => setTab('audit')}
                        onOpenCategorySafety={() => setShowCategorySafetyModal(true)}
                        onExportExcel={handleExportExcel}
                    />
                )}

                {/* 6. HISTORY VIEW */}
                {tab === 'history' && (
                    <HistoryView 
                        transactions={transactions}
                        items={items}
                        loading={loading}
                        onRefresh={loadAllData}
                        onExportExcel={handleExportExcel}
                    />
                )}
            </main>
        </div>

            {/* MOBILE FIXED BOTTOM NAVIGATION BAR */}
            <nav className="fixed bottom-0 inset-x-0 z-40 bg-white/95 backdrop-blur-md border-t border-slate-200/90 shadow-lg safe-area-bottom md:hidden">
                <div className="grid grid-cols-5 items-center justify-around py-1.5 px-2">
                    {mobileNavTabs.map(t => {
                        const active = tab === t.id;
                        if (t.isCenter) {
                            return (
                                <button
                                    key={t.id}
                                    onClick={() => setTab(t.id)}
                                    className="flex flex-col items-center justify-center -mt-5 tap-bounce focus:outline-hidden"
                                >
                                    <div className="w-12 h-12 rounded-full bg-emerald-600 text-white shadow-lg shadow-emerald-600/30 flex items-center justify-center border-4 border-white">
                                        <Icon name={t.icon} size={22} />
                                    </div>
                                    <span className="text-[10px] font-bold text-emerald-700 mt-0.5">{t.label}</span>
                                </button>
                            );
                        }

                        return (
                            <button
                                key={t.id}
                                onClick={() => setTab(t.id)}
                                className={`flex flex-col items-center justify-center py-1 tap-bounce focus:outline-hidden transition relative ${
                                    active ? 'text-emerald-600 font-bold' : 'text-slate-400 hover:text-slate-600'
                                }`}
                            >
                                <div className="relative">
                                    <Icon name={t.icon} size={19} />
                                    {t.badge !== undefined && t.badge > 0 && (
                                        <span className="absolute -top-1 -right-2 bg-amber-500 text-white text-[9px] font-bold px-1 min-w-[14px] h-[14px] rounded-full flex items-center justify-center shadow-xs">
                                            {t.badge}
                                        </span>
                                    )}
                                </div>
                                <span className="text-[10px] mt-0.5">{t.label}</span>
                            </button>
                        );
                    })}
                </div>
            </nav>

            {/* MODALS */}
            {showCategorySafetyModal && (
                <CategorySafetyModal 
                    categorySafetyStocks={categorySafetyStocks}
                    items={items}
                    onClose={() => setShowCategorySafetyModal(false)}
                    onSave={async (newMap, applyToExisting) => {
                        setSubmitting(true);
                        try {
                            const res = await StockApi.saveCategorySafetyStocks(newMap, applyToExisting);
                            setCategorySafetyStocks(newMap);
                            if (applyToExisting && res && res.items) {
                                setItems(res.items);
                            }
                            await loadAllData();
                            setShowCategorySafetyModal(false);
                            showToast("บันทึกสต็อกขั้นต่ำเรียบร้อย");
                        } catch (err) {
                            showToast(toFriendlyError(err), "error");
                        } finally {
                            setSubmitting(false);
                        }
                    }}
                    submitting={submitting}
                />
            )}

            {editingItem && (
                <ItemEditModal 
                    item={editingItem} 
                    existingItems={items}
                    categorySafetyStocks={categorySafetyStocks}
                    isAdmin={userRole.isAdmin}
                    onClose={() => setEditingItem(null)} 
                    onSave={async (savedData) => {
                        setSubmitting(true);
                        try {
                            await StockApi.saveItem(savedData);
                            await loadAllData();
                            setEditingItem(null);
                            showToast("บันทึกเรียบร้อย");
                        } catch (err) {
                            showToast(toFriendlyError(err), "error");
                        } finally {
                            setSubmitting(false);
                        }
                    }}
                    submitting={submitting}
                />
            )}

            {checkoutTarget && (
                <QuickCheckoutModal 
                    item={checkoutTarget} 
                    projects={projects}
                    currentUser={currentUser}
                    onAddToCart={addToCheckoutCart}
                    onClose={() => setCheckoutTarget(null)}
                    onSuccess={() => {
                        setCheckoutTarget(null);
                        loadAllData();
                        showToast("เบิกของเรียบร้อย!");
                    }}
                    showToast={showToast}
                />
            )}

            {convertTarget && (
                <ConvertVariantModal 
                    item={convertTarget}
                    currentUser={currentUser}
                    onClose={() => setConvertTarget(null)}
                    onSuccess={() => {
                        setConvertTarget(null);
                        loadAllData();
                        showToast("แปรรูปสินค้าสำเร็จ!");
                    }}
                    showToast={showToast}
                />
            )}

            {labelPrintItem && (
                <LabelPrintModal 
                    item={labelPrintItem} 
                    onClose={() => setLabelPrintItem(null)} 
                />
            )}

            <InAppConfirmModal dialog={confirmDialog} onClose={() => setConfirmDialog(null)} />
            <Toast message={toast?.message} type={toast?.type} onClose={() => setToast(null)} />
        </div>
    );
}

// ==========================================
// 1. INVENTORY CATALOG VIEW
// ==========================================
function InventoryView({
    items, allItems, loading, stats, canManageStock, pendingCounts,
    categorySafetyStocks = {},
    searchQuery, setSearchQuery,
    selectedCategory, setSelectedCategory,
    stockFilter, setStockFilter,
    onAddItem, onEditItem, onDeleteItem,
    onQuickCheckout, onConvertVariant, onPrintLabel,
    onOpenCategorySafety
}) {
    const categories = window.SEED_CATEGORIES || ['ทั้งหมด'];

    return (
        <div className="space-y-3.5">
            {/* Top Bar: Search Input & Add Button */}
            <div className="flex gap-2 items-center">
                <div className="relative flex-1">
                    <Icon name="search" size={17} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400" />
                    <input
                        type="text"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        placeholder="ค้นหา...."
                        className="w-full pl-9 sm:pl-10 pr-8 py-2.5 bg-white border border-slate-200/90 rounded-2xl text-xs sm:text-sm focus:outline-hidden focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 shadow-xs"
                    />
                    {searchQuery && (
                        <button onClick={() => setSearchQuery('')} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                            <Icon name="x" size={15} />
                        </button>
                    )}
                </div>

                {canManageStock && (
                    <button
                        type="button"
                        onClick={onAddItem}
                        className="flex items-center justify-center gap-1.5 px-3.5 sm:px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 active:scale-[0.98] text-white rounded-2xl font-bold text-xs sm:text-sm shadow-md shadow-emerald-600/20 transition shrink-0 whitespace-nowrap tap-bounce">
                        <Icon name="plus" size={17} />
                        <span className="hidden sm:inline">เพิ่มอุปกรณ์</span>
                    </button>
                )}
            </div>

            {/* Quick Filter Pill Carousel */}
            <div className="flex items-center gap-2 overflow-x-auto no-scrollbar py-1">
                <button
                    onClick={() => setStockFilter('all')}
                    className={`shrink-0 whitespace-nowrap px-3.5 py-1.5 rounded-xl text-xs font-semibold transition ${
                        stockFilter === 'all' 
                            ? 'bg-slate-800 text-white shadow-xs' 
                            : 'bg-white text-slate-600 hover:bg-slate-100 border border-slate-200'
                    }`}>
                    ทั้งหมด ({allItems.length})
                </button>
                <button
                    onClick={() => setStockFilter('out')}
                    className={`shrink-0 whitespace-nowrap flex items-center gap-1 px-3.5 py-1.5 rounded-xl text-xs font-semibold transition ${
                        stockFilter === 'out' 
                            ? 'bg-red-600 text-white shadow-xs' 
                            : 'bg-red-50 text-red-700 hover:bg-red-100 border border-red-200'
                    }`}>
                    <span>หมดสต็อก ({stats.outOfStock})</span>
                </button>
                <button
                    onClick={() => setStockFilter('low')}
                    className={`shrink-0 whitespace-nowrap flex items-center gap-1 px-3.5 py-1.5 rounded-xl text-xs font-semibold transition ${
                        stockFilter === 'low' 
                            ? 'bg-amber-600 text-white shadow-xs' 
                            : 'bg-amber-50 text-amber-800 hover:bg-amber-100 border border-amber-200'
                    }`}>
                    <span>ใกล้หมด ({stats.lowStock})</span>
                </button>

                <select
                    value={selectedCategory}
                    onChange={(e) => setSelectedCategory(e.target.value)}
                    className="shrink-0 whitespace-nowrap text-xs bg-white border border-slate-200 rounded-xl px-3 py-1.5 font-medium text-slate-700 focus:outline-hidden">
                    {categories.map(c => <option key={c} value={c}>{c === 'ทั้งหมด' ? 'ทุกหมวดหมู่' : c}</option>)}
                </select>
            </div>

            {/* Items Grid */}
            {loading ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3.5">
                    {[1, 2, 3, 4, 5, 6].map(n => <SkeletonCard key={n} />)}
                </div>
            ) : items.length === 0 ? (
                <div className="text-center py-16 bg-white rounded-3xl border border-slate-200 shadow-xs">
                    <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center text-slate-400 mx-auto mb-3">
                        <Icon name="package-open" size={30} />
                    </div>
                    <p className="font-bold text-slate-700 text-sm">ไม่พบรายการอุปกรณ์</p>
                    <p className="text-xs text-slate-400 mt-1">ลองเปลี่ยนคำค้นหา หรือเปลี่ยนตัวกรอง</p>
                </div>
            ) : (
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4">
                    {items.map(item => (
                        <ItemCard 
                            key={item.id} 
                            item={item} 
                            canManageStock={canManageStock}
                            categorySafetyStocks={categorySafetyStocks}
                            pendingCount={(pendingCounts?.byItem && pendingCounts.byItem[item.id]) || 0}
                            onEdit={() => onEditItem(item)}
                            onDelete={() => onDeleteItem(item.id)}
                            onConvert={() => onConvertVariant(item)}
                            onPrint={() => onPrintLabel(item)}
                        />
                    ))}
                </div>
            )}
        </div>
    );
}

// Single Item Card
function ItemCard({ item, canManageStock, categorySafetyStocks = {}, pendingCount = 0, onEdit, onDelete, onConvert, onPrint }) {
    const qty = Number(item.total_qty) || 0;
    const catThreshold = categorySafetyStocks && categorySafetyStocks[item.category];
    const reorder = (catThreshold !== undefined) ? Number(catThreshold) : (Number(item.reorder_point) || 5);
    const availableQty = Math.max(0, qty - pendingCount);
    const isOut = qty <= 0;
    const isLow = qty > 0 && qty <= reorder;

    const hasConvertible = item.variants && item.variants.some(v => v.condition_type === 'raw_box');

    return (
        <div className={`bg-white rounded-2xl sm:rounded-3xl p-3 sm:p-4 border transition-all duration-200 hover:shadow-md hover:border-slate-300 flex flex-col justify-between ${
            isOut ? 'border-red-200/90 bg-red-50/10' : isLow ? 'border-amber-200/90 bg-amber-50/10' : 'border-slate-200/80 shadow-xs'
        }`}>
            <div>
                {/* On Mobile (<sm): Compact horizontal card layout */}
                <div className="flex sm:hidden gap-3 items-start">
                    {/* Left Thumbnail (w-20 h-20) */}
                    <div className="w-20 h-20 rounded-2xl bg-slate-100 overflow-hidden relative shrink-0 flex items-center justify-center border border-slate-200/70 shadow-2xs">
                        {item.image_url ? (
                            <img src={item.image_url} alt={item.name} className="w-full h-full object-cover" />
                        ) : (
                            <div className="text-slate-300 flex flex-col items-center">
                                <Icon name="package" size={24} />
                            </div>
                        )}
                        <span className="absolute bottom-1 left-1 bg-slate-900/80 text-white text-[9px] px-1.5 py-0.2 rounded backdrop-blur-xs font-medium truncate max-w-[70px]">
                            {item.category}
                        </span>
                    </div>

                    {/* Right Info */}
                    <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between gap-1 mb-1">
                            <span className="font-mono text-[11px] font-bold text-slate-500 tracking-wider truncate">{item.code}</span>
                            <div className="flex items-center gap-1 shrink-0">
                                {isOut && <span className="bg-red-100 text-red-700 text-[9px] font-bold px-1.5 py-0.2 rounded-full">หมดสต็อก</span>}
                                {isLow && <span className="bg-amber-100 text-amber-800 text-[9px] font-bold px-1.5 py-0.2 rounded-full">ใกล้หมด</span>}
                                {!isOut && !isLow && <span className="bg-emerald-100 text-emerald-800 text-[9px] font-bold px-1.5 py-0.2 rounded-full">พร้อมใช้</span>}
                            </div>
                        </div>

                        <h3 className="font-bold text-xs text-slate-900 line-clamp-2 leading-snug" title={item.name}>
                            {item.name}
                        </h3>
                        {item.notes && (
                            <p className="text-[10px] text-slate-400 mt-0.5 line-clamp-1 flex items-center gap-1">
                                <Icon name="message-square" size={10} className="shrink-0 text-slate-300" />
                                <span>{item.notes}</span>
                            </p>
                        )}
                    </div>
                </div>

                {/* On Tablet/Desktop (>=sm): Beautiful Image Showcase Card */}
                <div className="hidden sm:block">
                    {/* Image Area with Clean Overlay Badges */}
                    <div className="w-full h-44 rounded-2xl bg-slate-100 overflow-hidden relative mb-3 flex items-center justify-center border border-slate-200/60 group">
                        {item.image_url ? (
                            <img src={item.image_url} alt={item.name} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" />
                        ) : (
                            <div className="text-slate-300 flex flex-col items-center">
                                <Icon name="package" size={36} />
                                <span className="text-[10px] mt-1 text-slate-400 font-medium">{item.category}</span>
                            </div>
                        )}
                        {/* Top-Left: Code Badge */}
                        <span className="absolute top-2.5 left-2.5 font-mono text-xs font-bold bg-slate-900/75 text-white backdrop-blur-xs px-2 py-0.5 rounded-lg shadow-2xs">
                            {item.code}
                        </span>

                        {/* Top-Right: Status & Pending Badges */}
                        <div className="absolute top-2.5 right-2.5 flex items-center gap-1.5 flex-wrap justify-end">
                            {isOut && <span className="bg-red-500/90 text-white text-[10px] font-bold px-2 py-0.5 rounded-lg backdrop-blur-xs shadow-2xs">หมดสต็อก</span>}
                            {isLow && <span className="bg-amber-500/90 text-white text-[10px] font-bold px-2 py-0.5 rounded-lg backdrop-blur-xs shadow-2xs">ใกล้หมด</span>}
                            {!isOut && !isLow && <span className="bg-emerald-600/90 text-white text-[10px] font-bold px-2 py-0.5 rounded-lg backdrop-blur-xs shadow-2xs">พร้อมใช้</span>}
                            {pendingCount > 0 && (
                                <span className="bg-amber-600 text-white text-[10px] font-bold px-2 py-0.5 rounded-lg flex items-center gap-1 shadow-2xs backdrop-blur-xs">
                                    <Icon name="clock" size={10} />
                                    รอ {pendingCount}
                                </span>
                            )}
                        </div>

                        {/* Bottom-Left: Category Pill */}
                        <span className="absolute bottom-2.5 left-2.5 bg-white/95 text-slate-700 font-medium text-[11px] px-2.5 py-0.5 rounded-lg shadow-2xs border border-white/60 backdrop-blur-xs">
                            {item.category}
                        </span>
                    </div>

                    {/* Title */}
                    <h3 className="font-bold text-sm text-slate-900 line-clamp-2 leading-snug" title={item.name}>
                        {item.name}
                    </h3>
                    {item.notes && (
                        <p className="text-[11px] text-slate-400 mt-1 line-clamp-1 flex items-center gap-1">
                            <Icon name="message-square" size={11} className="shrink-0 text-slate-300" />
                            <span>{item.notes}</span>
                        </p>
                    )}
                </div>

                {/* Variants Breakdown */}
                {item.variants && item.variants.length > 0 && (
                    <div className="mt-2.5 pt-2 border-t border-slate-100 space-y-1">
                        <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">สถานะย่อย</span>
                        <div className="grid grid-cols-2 gap-1 text-[11px]">
                            {item.variants.map((v, idx) => (
                                <div key={idx} className="bg-slate-50 px-2 py-1 rounded-lg flex items-center justify-between border border-slate-100">
                                    <span className="text-slate-600 truncate">{v.name}</span>
                                    <span className="font-bold text-slate-900 ml-1 font-mono">{v.qty} <span className="text-[9px] text-slate-400 font-sans">{v.unit}</span></span>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </div>

            {/* Footer */}
            <div className="mt-3 pt-3 border-t border-slate-100 flex items-center justify-between gap-2">
                <div>
                    <span className="text-[10px] text-slate-400 font-semibold block leading-none">
                        คงเหลือ
                    </span>
                    <div className="flex items-baseline gap-1 mt-1 flex-wrap">
                        <span className={`text-xl sm:text-2xl font-black font-mono leading-none ${isOut ? 'text-red-600' : isLow ? 'text-amber-600' : 'text-slate-900'}`}>
                            {qty}
                        </span>
                        <span className="text-xs text-slate-500 font-semibold">{item.unit}</span>
                        {pendingCount > 0 && (
                            <span className="text-[10px] font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-lg border border-emerald-200/60 ml-1 shadow-2xs">
                                พร้อมเบิก {availableQty}
                            </span>
                        )}
                    </div>
                </div>

                {/* Action Buttons: พิมพ์ -> แปรรูป -> แก้ไข -> ลบ (ตัดปุ่มเบิกออกแล้ว) */}
                <div className="flex items-center gap-1.5 ml-auto">
                    {/* 1. ปุ่มพิมพ์ (Print) */}
                    <button 
                        onClick={onPrint}
                        title="พิมพ์ป้ายสติกเกอร์" 
                        className="w-8 h-8 rounded-xl bg-slate-100 text-slate-600 hover:bg-slate-200 flex items-center justify-center transition tap-bounce">
                        <Icon name="printer" size={14} />
                    </button>

                    {/* แปรรูป/แปลงสภาพ (ถ้ามี) - เฉพาะ Admin & User ADS */}
                    {hasConvertible && canManageStock && (
                        <button 
                            onClick={onConvert}
                            title="แปรรูป/แปลงสภาพ" 
                            className="w-8 h-8 rounded-xl bg-blue-50 text-blue-600 hover:bg-blue-100 flex items-center justify-center transition tap-bounce">
                            <Icon name="refresh-cw" size={14} />
                        </button>
                    )}

                    {/* 3. ปุ่มแก้ไข & 4. ปุ่มลบ (สำหรับ Admin และ User ADS) */}
                    {canManageStock && (
                        <>
                            <button 
                                onClick={onEdit}
                                title="แก้ไขข้อมูล" 
                                className="w-8 h-8 rounded-xl bg-slate-100 text-slate-600 hover:bg-slate-200 flex items-center justify-center transition tap-bounce">
                                <Icon name="pencil" size={14} />
                            </button>
                            <button 
                                onClick={onDelete}
                                title="ลบรายการ" 
                                className="w-8 h-8 rounded-xl bg-red-50 text-red-600 hover:bg-red-100 flex items-center justify-center transition tap-bounce">
                                <Icon name="trash" size={14} />
                            </button>
                        </>
                    )}
                </div>
            </div>
        </div>
    );
}

// ==========================================
// 2. CHECKOUT COMPONENTS & VIEW
// ==========================================

// Searchable Equipment Selector with Thumbnail Images for Checkout View
function CheckoutItemSelector({ items = [], selectedItemId, onSelectItem }) {
    const [open, setOpen] = useState(false);
    const [search, setSearch] = useState('');
    const containerRef = useRef(null);

    const selectedItem = items.find(i => i.id === selectedItemId);

    useEffect(() => {
        const handleClickOutside = (e) => {
            if (containerRef.current && !containerRef.current.contains(e.target)) {
                setOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const filteredItems = useMemo(() => {
        if (!search.trim()) return items;
        const q = search.toLowerCase().trim();
        return items.filter(it => 
            (it.name && it.name.toLowerCase().includes(q)) ||
            (it.code && it.code.toLowerCase().includes(q)) ||
            (it.category && it.category.toLowerCase().includes(q))
        );
    }, [items, search]);

    return (
        <div ref={containerRef} className="relative">
            <label className="block text-xs font-bold text-slate-700 mb-1.5">
                เลือกอุปกรณ์ <span className="text-red-500">*</span>
            </label>

            {/* If Item is selected and dropdown is closed: show sleek Selected Item Card */}
            {selectedItem && !open ? (
                <div 
                    onClick={() => {
                        setOpen(true);
                        setSearch('');
                    }}
                    className="p-3 sm:p-3.5 bg-white border-2 border-emerald-500/40 hover:border-emerald-500 rounded-2xl flex items-center justify-between gap-3 cursor-pointer transition shadow-xs group"
                >
                    <div className="flex items-center gap-3 min-w-0">
                        <div className="w-12 h-12 sm:w-14 sm:h-14 rounded-2xl overflow-hidden bg-slate-100 border border-slate-200 shrink-0 flex items-center justify-center">
                            {selectedItem.image_url ? (
                                <img src={selectedItem.image_url} alt={selectedItem.name} className="w-full h-full object-cover" />
                            ) : (
                                <Icon name="package" size={24} className="text-slate-300" />
                            )}
                        </div>
                        <div className="min-w-0">
                            <div className="flex items-center gap-1.5 flex-wrap">
                                <span className="font-mono text-xs font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-lg border border-emerald-200/50">
                                    {selectedItem.code}
                                </span>
                                <span className="text-[10px] text-slate-500 bg-slate-100 px-2 py-0.5 rounded-lg font-medium">
                                    {selectedItem.category}
                                </span>
                            </div>
                            <div className="font-bold text-slate-900 text-xs sm:text-sm truncate mt-1" title={selectedItem.name}>
                                {selectedItem.name}
                            </div>
                            <div className="text-xs mt-0.5 flex items-center gap-1">
                                <span className="text-slate-400">คงเหลือ:</span>
                                <span className={`font-mono font-bold ${selectedItem.total_qty > 0 ? "text-emerald-600" : "text-red-500"}`}>
                                    {selectedItem.total_qty} {selectedItem.unit}
                                </span>
                            </div>
                        </div>
                    </div>

                    <button
                        type="button"
                        onClick={(e) => {
                            e.stopPropagation();
                            setOpen(true);
                            setSearch('');
                        }}
                        className="px-3 py-1.5 rounded-xl bg-slate-100 group-hover:bg-emerald-50 text-slate-600 group-hover:text-emerald-700 font-semibold text-xs border border-slate-200/80 group-hover:border-emerald-300 transition flex items-center gap-1.5 shrink-0 tap-bounce shadow-2xs"
                    >
                        <Icon name="repeat" size={13} />
                        <span>เปลี่ยน</span>
                    </button>
                </div>
            ) : (
                /* Search Input Bar (Shown when no item selected or when changing) */
                <div className="relative">
                    <div className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none">
                        <Icon name="search" size={15} />
                    </div>
                    <input
                        type="text"
                        autoFocus={open && !!selectedItem}
                        value={search}
                        onChange={(e) => {
                            setSearch(e.target.value);
                            setOpen(true);
                        }}
                        onFocus={() => setOpen(true)}
                        onKeyDown={(e) => {
                            if (e.key === 'Enter' && search.trim()) {
                                const trimmed = search.trim().toLowerCase();
                                const exact = items.find(it => (it.code && it.code.toLowerCase() === trimmed) || (it.name && it.name.toLowerCase() === trimmed));
                                if (exact) {
                                    playScanFeedback(true);
                                    onSelectItem(exact.id);
                                    setOpen(false);
                                    setSearch('');
                                } else if (filteredItems.length === 1) {
                                    playScanFeedback(true);
                                    onSelectItem(filteredItems[0].id);
                                    setOpen(false);
                                    setSearch('');
                                }
                            }
                        }}
                        placeholder="ค้นหาชื่ออุปกรณ์, รหัสสินค้า, หรือหมวดหมู่..."
                        className="w-full bg-slate-50 border border-slate-200 rounded-2xl pl-9 pr-16 py-2.5 text-xs sm:text-sm font-medium focus:bg-white focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/20 focus:outline-hidden transition shadow-xs"
                    />
                    {search ? (
                        <button
                            type="button"
                            onClick={() => setSearch('')}
                            className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-0.5"
                        >
                            <Icon name="x" size={14} />
                        </button>
                    ) : selectedItem ? (
                        <button
                            type="button"
                            onClick={() => setOpen(false)}
                            className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-700 text-xs font-semibold px-2 py-1 rounded-lg bg-slate-100 hover:bg-slate-200 transition"
                        >
                            ยกเลิก
                        </button>
                    ) : null}
                </div>
            )}

            {/* Dropdown Menu with Image, Code, Name & Stock */}
            {open && (
                <div className="absolute left-0 right-0 top-full mt-1 bg-white border border-slate-200 rounded-2xl shadow-xl z-50 max-h-72 overflow-y-auto divide-y divide-slate-100 animate-fade-in">
                    <div className="px-3.5 py-2 text-[10px] font-bold text-slate-400 uppercase tracking-wider bg-slate-50/90 flex items-center justify-between sticky top-0 backdrop-blur-xs z-10">
                        <span>รายการอุปกรณ์ ({filteredItems.length})</span>
                        <span>แตะเพื่อเลือก</span>
                    </div>

                    {filteredItems.length === 0 ? (
                        <div className="p-4 text-center text-xs text-slate-400 font-medium">
                            ไม่พบอุปกรณ์ที่ตรงกับการค้นหา
                        </div>
                    ) : (
                        filteredItems.map(item => {
                            const isOutOfStock = item.total_qty <= 0;
                            const isSelected = item.id === selectedItemId;

                            return (
                                <button
                                    key={item.id}
                                    type="button"
                                    disabled={isOutOfStock}
                                    onMouseDown={(e) => {
                                        e.preventDefault();
                                        onSelectItem(item.id);
                                        setOpen(false);
                                        setSearch('');
                                    }}
                                    className={`w-full p-2.5 sm:p-3 text-left flex items-center justify-between gap-3 transition ${
                                        isSelected 
                                            ? 'bg-emerald-50/80 text-emerald-950 font-bold' 
                                            : isOutOfStock 
                                                ? 'opacity-40 bg-slate-50/50 cursor-not-allowed' 
                                                : 'hover:bg-slate-50'
                                    }`}
                                >
                                    <div className="flex items-center gap-3 min-w-0">
                                        <div className="w-10 h-10 rounded-xl overflow-hidden bg-slate-100 border border-slate-200 shrink-0 flex items-center justify-center">
                                            {item.image_url ? (
                                                <img src={item.image_url} alt={item.name} className="w-full h-full object-cover" />
                                            ) : (
                                                <Icon name="package" size={18} className="text-slate-300" />
                                            )}
                                        </div>
                                        <div className="min-w-0">
                                            <div className="flex items-center gap-1.5">
                                                <span className="font-mono text-[10px] font-bold text-emerald-700 bg-emerald-50 px-1 rounded border border-emerald-200/50">
                                                    {item.code}
                                                </span>
                                                <span className="text-[10px] text-slate-400">{item.category}</span>
                                            </div>
                                            <div className="text-xs sm:text-sm font-semibold text-slate-800 truncate">
                                                {item.name}
                                            </div>
                                        </div>
                                    </div>

                                    <div className="text-right shrink-0">
                                        <div className={`text-xs font-bold ${item.total_qty > 0 ? 'text-emerald-600' : 'text-red-500'}`}>
                                            {item.total_qty > 0 ? `${item.total_qty} ${item.unit}` : 'หมด'}
                                        </div>
                                        {isSelected && (
                                            <span className="text-[10px] text-emerald-600 font-bold flex items-center gap-0.5 justify-end mt-0.5">
                                                <Icon name="check" size={11} /> เลือกอยู่
                                            </span>
                                        )}
                                    </div>
                                </button>
                            );
                        })
                    )}
                </div>
            )}
        </div>
    );
}

// Searchable Job Site / Project Combobox
function JobSiteSelector({ projects = [], value, onChange }) {
    const [open, setOpen] = useState(false);
    const containerRef = useRef(null);

    useEffect(() => {
        const handleClickOutside = (e) => {
            if (containerRef.current && !containerRef.current.contains(e.target)) {
                setOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const projectList = useMemo(() => {
        return (projects || []).map(p => ({
            id: p.id,
            name: p.name,
            sub: p.province ? `จังหวัด ${p.province}` : ''
        }));
    }, [projects]);

    const filtered = useMemo(() => {
        if (!value) return projectList;
        const q = value.toLowerCase().trim();
        return projectList.filter(p => 
            p.name.toLowerCase().includes(q) || (p.sub && p.sub.toLowerCase().includes(q))
        );
    }, [projectList, value]);

    return (
        <div ref={containerRef} className="relative">
            <label className="block text-xs font-bold text-slate-700 mb-1.5">
                โครงการ / หน้างาน <span className="text-red-500">*</span>
            </label>

            <div className="relative">
                <input
                    type="text"
                    required
                    value={value}
                    onChange={(e) => {
                        onChange(e.target.value);
                        setOpen(true);
                    }}
                    onFocus={() => setOpen(true)}
                    placeholder="พิมพ์ค้นหาโครงการ หรือระบุชื่อหน้างาน..."
                    className="w-full bg-slate-50 border border-slate-200 rounded-2xl px-3.5 pr-8 py-2.5 text-xs sm:text-sm font-medium focus:bg-white focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/20 focus:outline-hidden transition"
                />
                {value && (
                    <button
                        type="button"
                        onClick={() => { onChange(''); setOpen(true); }}
                        className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-0.5"
                    >
                        <Icon name="x" size={14} />
                    </button>
                )}
            </div>

            {/* Suggestions Dropdown */}
            {open && filtered.length > 0 && (
                <div className="absolute left-0 right-0 top-full mt-1 bg-white border border-slate-200 rounded-2xl shadow-xl z-50 max-h-56 overflow-y-auto divide-y divide-slate-100 animate-fade-in py-1">
                    <div className="px-3.5 py-1.5 text-[10px] font-bold text-slate-400 uppercase tracking-wider bg-slate-50/90 flex items-center justify-between">
                        <span>โครงการในระบบ ({filtered.length})</span>
                        <span>แตะเพื่อเลือก</span>
                    </div>
                    {filtered.map((p, idx) => (
                        <button
                            key={p.id || idx}
                            type="button"
                            onMouseDown={(e) => {
                                e.preventDefault();
                                onChange(p.name);
                                setOpen(false);
                            }}
                            className="w-full text-left px-3.5 py-2.5 text-xs font-semibold text-slate-700 hover:bg-emerald-50 hover:text-emerald-800 flex items-center justify-between transition group"
                        >
                            <span className="truncate">{p.name}</span>
                            {p.sub && <span className="text-[10px] text-slate-400 group-hover:text-emerald-600 shrink-0">{p.sub}</span>}
                        </button>
                    ))}
                </div>
            )}
        </div>
    );
}

function CheckoutView({ 
    items, 
    projects, 
    currentUser, 
    userRole, 
    pendingCounts, 
    requisitions = [],
    transactions = [],
    cart = [],
    onAddToCart,
    onUpdateCartQty,
    onRemoveCartItem,
    onClearCart,
    onNavigateToScan,
    onNavigateToMyRequests,
    onNavigateToHistory,
    onSuccess, 
    showToast 
}) {
    const [selectedItemId, setSelectedItemId] = useState(items[0]?.id || '');
    const [variantId, setVariantId] = useState('');
    const [pickerQty, setPickerQty] = useState(1);
    const [jobSite, setJobSite] = useState(projects[0]?.name || 'โครงการพราว น้ำพอง');
    const [reason, setReason] = useState('ติดตั้งใหม่');
    const [customReason, setCustomReason] = useState('');
    const [note, setNote] = useState('');
    const [consentAgreed, setConsentAgreed] = useState(false);
    const [isReviewing, setIsReviewing] = useState(false);
    const [submitting, setSubmitting] = useState(false);

    const mustRequestApproval = userRole?.mustRequestApproval;
    const selectedItem = items.find(i => i.id === selectedItemId);
    const selectedVariant = selectedItem?.variants?.find(v => v.id === variantId) || selectedItem?.variants?.[0];
    const techName = currentUser?.name || 'ช่างเทคนิค';

    const currentVariantQty = selectedVariant ? Number(selectedVariant.qty) || 0 : Number(selectedItem?.total_qty) || 0;

    useEffect(() => {
        if (selectedItem && selectedItem.variants && selectedItem.variants.length > 0) {
            setVariantId(selectedItem.variants[0].id);
        } else {
            setVariantId('');
        }
        setPickerQty(1);
    }, [selectedItemId]);

    // รายการอุปกรณ์ที่จะทำการเบิก (ถ้ามีในตะกร้าใช้ในตะกร้า หากไม่มีแต่เลือกอุปกรณ์ค้างไว้ในฟอร์ม ใช้รายการที่เลือก)
    const effectiveItemsToCheckout = useMemo(() => {
        if (cart && cart.length > 0) return cart;
        if (selectedItem && Number(pickerQty) > 0 && currentVariantQty >= Number(pickerQty)) {
            const v = selectedVariant || selectedItem.variants?.[0];
            return [{
                cartId: `temp-${selectedItem.id}-${Date.now()}`,
                itemId: selectedItem.id,
                itemCode: selectedItem.code || '',
                itemName: selectedItem.name,
                itemCategory: selectedItem.category,
                itemImage: selectedItem.image_url || selectedItem.image || null,
                variantId: v?.id || '',
                variantName: v?.name || 'ปกติ',
                qty: Number(pickerQty),
                unit: v?.unit || selectedItem.unit || 'ชิ้น',
                maxQty: currentVariantQty
            }];
        }
        return [];
    }, [cart, selectedItem, selectedVariant, pickerQty, currentVariantQty]);

    // ประวัติการเบิกล่าสุด หรือ คำขอเบิกล่าสุดของผู้ใช้
    const recentList = useMemo(() => {
        if (mustRequestApproval) {
            const myName = (currentUser?.name || '').toLowerCase().trim();
            const myUser = (currentUser?.username || '').toLowerCase().trim();
            return (requisitions || []).filter(r => {
                const tName = (r.technician || r.technician_name || '').toLowerCase().trim();
                const tUser = (r.created_by || r.technician_username || '').toLowerCase().trim();
                if (!myName && !myUser) return true;
                return (myName && (tName === myName || tName.includes(myName) || myName.includes(tName))) ||
                       (myUser && (tUser === myUser || tUser.includes(myUser) || myUser.includes(tUser)));
            }).slice(0, 5);
        } else {
            return (transactions || []).filter(t => t.type === 'checkout').slice(0, 5);
        }
    }, [mustRequestApproval, requisitions, transactions, currentUser]);

    // เพิ่มอุปกรณ์ที่กำลังเลือกเข้าตะกร้า
    const handleAddCurrentToCart = (e) => {
        if (e) e.preventDefault();
        if (!selectedItem) return showToast("กรุณาเลือกอุปกรณ์", "error");
        const numQty = Number(pickerQty);
        if (numQty <= 0) return showToast("จำนวนต้องมากกว่า 0", "error");
        if (currentVariantQty <= 0) return showToast(`อุปกรณ์ "${selectedItem.name}" สินค้าหมด`, "warning");
        if (numQty > currentVariantQty) {
            return showToast(`ยอดคงเหลือไม่พอ (มีเพียง ${currentVariantQty} ${selectedVariant?.unit || selectedItem?.unit})`, "warning");
        }

        const ok = onAddToCart ? onAddToCart(selectedItem, selectedVariant, numQty) : false;
        if (ok) {
            setPickerQty(1);
        }
        return ok;
    };

    // ขั้นตอนตรวจสอบข้อมูลก่อนบันทึก
    const handleStartCheckout = (e) => {
        e.preventDefault();

        if (effectiveItemsToCheckout.length === 0) {
            return showToast("กรุณาเลือกอุปกรณ์และระบุจำนวนที่ต้องการเบิก", "warning");
        }

        if (!jobSite || !jobSite.trim()) return showToast("กรุณาระบุโครงการ / หน้างาน", "error");

        const finalReason = reason === 'อื่นๆ' ? (customReason.trim() || 'อื่นๆ') : reason;
        if (reason === 'อื่นๆ' && !customReason.trim()) {
            return showToast("กรุณาระบุเหตุผลการเบิกเพิ่มเติม", "error");
        }

        if (mustRequestApproval && !consentAgreed) {
            return showToast("กรุณาทำเครื่องหมายยินยอมรับผิดชอบทุกกรณีหากนำสิ่งของออกก่อนการอนุมัติ", "warning");
        }

        setIsReviewing(true);
    };

    // ยืนยันบันทึกการเบิก หรือ ส่งคำขอเบิกทั้งหมด
    const handleConfirmCheckout = async () => {
        const itemsToSubmit = effectiveItemsToCheckout;
        if (!itemsToSubmit || itemsToSubmit.length === 0) return showToast("ไม่มีรายการอุปกรณ์ในตะกร้า", "error");
        const finalReason = reason === 'อื่นๆ' ? (customReason.trim() || 'อื่นๆ') : reason;

        setSubmitting(true);
        try {
            if (mustRequestApproval) {
                // Technician: ส่งคำขอเบิกเป็นชุดให้ Admin อนุมัติ
                const res = await StockApi.createRequisitionBatch({
                    items: itemsToSubmit,
                    jobSite: jobSite.trim(),
                    reason: finalReason,
                    technician: techName,
                    technicianUsername: currentUser?.username || '',
                    note: note.trim(),
                    acknowledgedRisk: true
                });
                setIsReviewing(false);
                if (onClearCart) onClearCart();
                setNote('');
                setConsentAgreed(false);
                if (reason === 'อื่นๆ') setCustomReason('');
                showToast(`ส่งคำขอเบิก ${res.count} รายการ สำเร็จ! รหัส ${res.batchCode} (รอผู้อนุมัติ)`);
                if (onSuccess) onSuccess('my-requests');
            } else {
                // Admin / ADS: ตัดสต็อกเป็นชุดได้ทันที
                const res = await StockApi.checkoutBatch({
                    items: itemsToSubmit,
                    jobSite: jobSite.trim(),
                    reason: finalReason,
                    technician: techName,
                    note: note.trim()
                });
                setIsReviewing(false);
                if (onClearCart) onClearCart();
                setNote('');
                if (reason === 'อื่นๆ') setCustomReason('');
                showToast(`บันทึกการเบิกและตัดสต็อก ${res.count} รายการสำเร็จ!`);
                if (onSuccess) onSuccess('history');
            }
        } catch (err) {
            showToast(toFriendlyError(err), "error");
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <div className="max-w-3xl mx-auto space-y-5">
            {/* Modern Saving & Loading Modal */}
            <ModernLoadingModal show={submitting} title={mustRequestApproval ? "กำลังส่งคำขอเบิก..." : "กำลังบันทึกการเบิก..."} />

            {/* Modal ตรวจสอบข้อมูลก่อนบันทึกการเบิก */}
            {isReviewing && (
                <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto animate-fade-in">
                    <div className="bg-white rounded-3xl max-w-lg w-full shadow-2xl border border-slate-100 my-auto flex flex-col max-h-[calc(100dvh-2rem)] sm:max-h-[92vh] overflow-hidden modal-responsive-card">
                        {/* Header */}
                        <div className="px-5 py-3.5 sm:py-4 border-b border-slate-100 flex items-center justify-between shrink-0 bg-white">
                            <div className="flex items-center gap-2.5">
                                <div className={`w-9 h-9 rounded-2xl flex items-center justify-center shrink-0 ${mustRequestApproval ? 'bg-amber-50 text-amber-600' : 'bg-emerald-50 text-emerald-600'}`}>
                                    <Icon name={mustRequestApproval ? "clipboard-list" : "clipboard-check"} size={20} />
                                </div>
                                <div>
                                    <h3 className="font-bold text-slate-900 text-sm sm:text-base">
                                        {mustRequestApproval ? `ตรวจสอบคำขอเบิก (${effectiveItemsToCheckout.length})` : `ตรวจสอบการเบิก (${effectiveItemsToCheckout.length})`}
                                    </h3>
                                    <p className="text-[11px] text-slate-400">
                                        {mustRequestApproval ? 'ตรวจสอบข้อมูลก่อนส่งคำขอไปยังผู้อนุมัติ' : 'ตรวจสอบความถูกต้องก่อนตัดสต็อก'}
                                    </p>
                                </div>
                            </div>
                            <button
                                type="button"
                                onClick={() => setIsReviewing(false)}
                                disabled={submitting}
                                className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition"
                            >
                                <Icon name="x" size={18} />
                            </button>
                        </div>

                        {/* Body */}
                        <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-3.5 text-xs">
                            {/* Items List in Review */}
                            <div>
                                <label className="block text-[11px] font-bold text-slate-500 mb-1.5 uppercase tracking-wider">
                                    รายการอุปกรณ์ที่เบิก ({effectiveItemsToCheckout.length})
                                </label>
                                <div className="divide-y divide-slate-100 bg-slate-50/80 rounded-2xl border border-slate-200/80 overflow-hidden max-h-56 overflow-y-auto">
                                    {effectiveItemsToCheckout.map((c, idx) => (
                                        <div key={c.cartId || idx} className="p-2.5 flex items-center justify-between gap-2.5">
                                            <div className="flex items-center gap-2.5 min-w-0">
                                                <div className="w-9 h-9 rounded-lg bg-white border border-slate-200 overflow-hidden shrink-0 flex items-center justify-center">
                                                    {c.itemImage ? (
                                                        <img src={c.itemImage} alt={c.itemName} className="w-full h-full object-cover" />
                                                    ) : (
                                                        <Icon name="package" size={16} className="text-slate-300" />
                                                    )}
                                                </div>
                                                <div className="min-w-0">
                                                    <div className="font-bold text-slate-900 text-xs truncate" title={c.itemName}>
                                                        {idx + 1}. {c.itemName}
                                                    </div>
                                                    <div className="text-[10px] text-slate-500 flex items-center gap-1.5 mt-0.5">
                                                        <span className="font-mono text-emerald-700 font-bold">{c.itemCode}</span>
                                                        <span>• สภาพ: {c.variantName}</span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div className="text-right shrink-0">
                                                <span className="font-bold text-emerald-600 text-sm">
                                                    {c.qty}
                                                </span>
                                                <span className="text-slate-500 text-[11px] ml-1">{c.unit}</span>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {/* Summary Details */}
                            <div className="bg-slate-50/70 p-3.5 rounded-2xl border border-slate-200/70 space-y-2">
                                <div className="flex justify-between items-center py-1 border-b border-slate-200/50">
                                    <span className="text-slate-500">โครงการ / หน้างาน:</span>
                                    <span className="font-bold text-slate-800 text-right max-w-[220px] truncate flex items-center gap-1.5 justify-end">
                                        <Icon name="map-pin" size={13} className="text-slate-400 shrink-0" />
                                        <span>{jobSite}</span>
                                    </span>
                                </div>
                                <div className="flex justify-between items-center py-1 border-b border-slate-200/50">
                                    <span className="text-slate-500">เหตุผล:</span>
                                    <span className="font-semibold text-slate-800 text-right max-w-[220px] truncate flex items-center gap-1.5 justify-end">
                                        <Icon name="file-text" size={13} className="text-slate-400 shrink-0" />
                                        <span>{reason === 'อื่นๆ' ? customReason : reason}</span>
                                    </span>
                                </div>
                                <div className="flex justify-between items-center py-1 border-b border-slate-200/50">
                                    <span className="text-slate-500">ผู้ทำรายการ:</span>
                                    <span className="font-bold text-slate-800 flex items-center gap-1.5 justify-end">
                                        <Icon name="user" size={13} className="text-slate-400 shrink-0" />
                                        <span>{techName}</span>
                                    </span>
                                </div>
                                {note && (
                                    <div className="flex justify-between items-start py-1">
                                        <span className="text-slate-500">หมายเหตุ:</span>
                                        <span className="text-slate-700 text-right max-w-[220px] flex items-center gap-1.5 justify-end">
                                            <Icon name="message-square" size={13} className="text-slate-400 shrink-0" />
                                            <span>{note}</span>
                                        </span>
                                    </div>
                                )}
                            </div>

                            {mustRequestApproval ? (
                                <p className="text-[11px] text-amber-800 bg-amber-50 p-2.5 rounded-xl border border-amber-200 flex items-start gap-1.5 leading-relaxed">
                                    <Icon name="alert-triangle" size={14} className="shrink-0 text-amber-600 mt-0.5" />
                                    <span>คำขอจะถูกส่งเป็นชุดไปยัง <b>ผู้อนุมัติ</b> ก่อนนำของออกจากคลัง</span>
                                </p>
                            ) : (
                                <p className="text-[11px] text-amber-700 bg-amber-50 p-2.5 rounded-xl border border-amber-200/60 flex items-center gap-1.5">
                                    <Icon name="alert-circle" size={14} className="shrink-0 text-amber-600" />
                                    <span>ระบบจะตัดสต็อกและส่งแจ้งเตือน Telegram รวม 1 ข้อความไปยังกลุ่มงานทันที</span>
                                </p>
                            )}
                        </div>

                        {/* Footer Buttons */}
                        <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2.5 shrink-0">
                            <button
                                type="button"
                                onClick={() => setIsReviewing(false)}
                                disabled={submitting}
                                className="flex-1 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl font-bold transition flex items-center justify-center gap-1.5 text-xs sm:text-sm tap-bounce"
                            >
                                <span>แก้ไข</span>
                            </button>
                            <button
                                type="button"
                                onClick={handleConfirmCheckout}
                                disabled={submitting}
                                className={`flex-1 py-2.5 text-white rounded-xl font-bold shadow-md transition flex items-center justify-center text-xs sm:text-sm tap-bounce ${
                                    mustRequestApproval 
                                        ? 'bg-amber-600 hover:bg-amber-700 shadow-amber-600/20' 
                                        : 'bg-emerald-600 hover:bg-emerald-700 shadow-emerald-600/20'
                                }`}
                            >
                                <span>
                                    {submitting 
                                        ? (mustRequestApproval ? 'กำลังส่งคำขอ...' : 'กำลังบันทึก...') 
                                        : (mustRequestApproval ? `ส่งคำขอ (${effectiveItemsToCheckout.length})` : `เบิกของ (${effectiveItemsToCheckout.length})`)}
                                </span>
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Main Checkout View Card */}
            <div className="bg-white rounded-3xl p-5 sm:p-7 border border-slate-200/80 shadow-xs space-y-6">
                {/* Header Banner */}
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-4 border-b border-slate-100">
                    <div className="flex items-center gap-3">
                        <div className={`w-11 h-11 rounded-2xl flex items-center justify-center shrink-0 ${
                            mustRequestApproval ? 'bg-amber-500/10 text-amber-600' : 'bg-emerald-500/10 text-emerald-600'
                        }`}>
                            <Icon name={mustRequestApproval ? "clipboard-list" : "arrow-up-right"} size={22} />
                        </div>
                        <div>
                            <div className="flex items-center gap-2">
                                <h2 className="text-base sm:text-lg font-bold text-slate-900">
                                    {mustRequestApproval ? 'ส่งคำขอเบิก' : 'เบิกอุปกรณ์'}
                                </h2>
                                {cart.length > 0 && (
                                    <span className="px-2.5 py-0.5 rounded-full bg-emerald-100 text-emerald-800 text-xs font-bold">
                                        {cart.length} รายการ
                                    </span>
                                )}
                            </div>
                        </div>
                    </div>

                    {/* Quick Button: สแกนด้วยกล้อง */}
                    {onNavigateToScan && (
                        <button
                            type="button"
                            onClick={onNavigateToScan}
                            className="flex items-center gap-1.5 px-3.5 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-2xl text-xs font-bold transition w-fit tap-bounce shrink-0"
                        >
                            <Icon name="camera" size={15} className="text-emerald-600" />
                            <span>สแกน</span>
                        </button>
                    )}
                </div>

                {/* Section 1: เลือกอุปกรณ์ + เพิ่มรายการ */}
                <div className="p-4 sm:p-5 bg-slate-50/70 border border-slate-200/80 rounded-2xl space-y-4">
                    <div className="flex items-center justify-between">
                        <h3 className="text-xs sm:text-sm font-bold text-slate-800">
                            รายการ
                        </h3>
                    </div>

                    {/* Equipment Selector */}
                    <CheckoutItemSelector
                        items={items}
                        selectedItemId={selectedItemId}
                        onSelectItem={(id) => setSelectedItemId(id)}
                    />

                    {/* Condition / Variant Selector */}
                    {selectedItem && selectedItem.variants && selectedItem.variants.length > 0 && (
                        <div>
                            <label className="block text-xs font-bold text-slate-700 mb-1.5">สภาพสินค้า *</label>
                            <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                                {selectedItem.variants.map(v => (
                                    <button
                                        type="button"
                                        key={v.id}
                                        onClick={() => setVariantId(v.id)}
                                        className={`p-2.5 rounded-xl border text-left text-xs transition ${
                                            variantId === v.id 
                                                ? 'border-emerald-600 bg-emerald-50 text-emerald-900 font-bold ring-2 ring-emerald-500/20' 
                                                : 'border-slate-200 bg-white hover:bg-slate-100 text-slate-600'
                                        }`}>
                                        <div className="font-semibold truncate">{v.name}</div>
                                        <div className="text-[11px] text-slate-500 mt-0.5">เหลือ: {v.qty} {v.unit}</div>
                                    </button>
                                ))}
                            </div>
                        </div>
                    )}

                    {/* Quantity Picker + Add to Cart Button */}
                    <div className="flex flex-col sm:flex-row items-stretch sm:items-end gap-3 pt-1">
                        <div className="sm:w-48">
                            <label className="block text-xs font-bold text-slate-700 mb-1.5">
                                จำนวน *
                            </label>
                            <div className="flex items-center gap-2">
                                <button
                                    type="button"
                                    onClick={() => setPickerQty(Math.max(1, Number(pickerQty) - 1))}
                                    className="w-10 h-10 rounded-xl bg-white hover:bg-slate-100 border border-slate-200 text-slate-700 font-bold flex items-center justify-center text-base transition">
                                    -
                                </button>
                                <input
                                    type="number"
                                    min="1"
                                    max={currentVariantQty > 0 ? currentVariantQty : 1}
                                    value={pickerQty}
                                    onChange={(e) => setPickerQty(e.target.value)}
                                    className="flex-1 bg-white border border-slate-200 rounded-xl py-2 text-center text-sm font-bold focus:outline-hidden focus:border-emerald-500"
                                />
                                <button
                                    type="button"
                                    onClick={() => setPickerQty(Number(pickerQty) + 1)}
                                    className="w-10 h-10 rounded-xl bg-white hover:bg-slate-100 border border-slate-200 text-slate-700 font-bold flex items-center justify-center text-base transition">
                                    +
                                </button>
                                <span className="text-xs font-semibold text-slate-500 w-10 text-center shrink-0">
                                    {selectedVariant?.unit || selectedItem?.unit || 'ชิ้น'}
                                </span>
                            </div>
                        </div>

                        {/* Button: เพิ่มรายการ */}
                        <button
                            type="button"
                            onClick={handleAddCurrentToCart}
                            className="flex-1 py-2.5 sm:py-2.5 px-4 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold text-xs sm:text-sm shadow-md shadow-emerald-600/20 flex items-center justify-center transition tap-bounce active:scale-[0.98]">
                            <span>+ เพิ่มรายการ</span>
                        </button>
                    </div>
                </div>

                {/* Cart Items List or Active Item Indicator */}
                {cart.length > 0 ? (
                    <div className="space-y-3 pt-1">
                        <div className="flex items-center justify-between pb-1">
                            <h3 className="text-xs sm:text-sm font-bold text-slate-800 flex items-center gap-2">
                                <span className="w-5 h-5 rounded-full bg-emerald-600 text-white text-[10px] font-bold flex items-center justify-center">
                                    {cart.length}
                                </span>
                                <span>รายการ ({cart.length})</span>
                            </h3>
                            <button
                                type="button"
                                onClick={onClearCart}
                                className="text-xs text-red-500 hover:text-red-700 font-semibold transition hover:underline">
                                <span>ล้างตะกร้า</span>
                            </button>
                        </div>

                        <div className="space-y-2.5">
                            {cart.map((c, idx) => (
                                <div 
                                    key={c.cartId || idx}
                                    className="p-3 bg-white border border-slate-200/90 hover:border-slate-300 rounded-2xl flex flex-col sm:flex-row sm:items-center justify-between gap-3 shadow-2xs transition"
                                >
                                    <div className="flex items-center gap-3 min-w-0 flex-1">
                                        <div className="w-11 h-11 rounded-xl overflow-hidden bg-slate-100 border border-slate-200 shrink-0 flex items-center justify-center">
                                            {c.itemImage ? (
                                                <img src={c.itemImage} alt={c.itemName} className="w-full h-full object-cover" />
                                            ) : (
                                                <Icon name="package" size={20} className="text-slate-300" />
                                            )}
                                        </div>
                                        <div className="min-w-0 flex-1">
                                            <div className="flex items-center gap-1.5 flex-wrap">
                                                <span className="font-mono text-[10px] font-bold text-emerald-700 bg-emerald-50 px-1 rounded border border-emerald-200/50">
                                                    {c.itemCode}
                                                </span>
                                                <span className="text-[10px] text-slate-600 bg-slate-100 px-1.5 py-0.5 rounded font-medium">
                                                    สภาพ: {c.variantName}
                                                </span>
                                            </div>
                                            <div className="font-bold text-slate-900 text-xs sm:text-sm truncate mt-0.5" title={c.itemName}>
                                                {c.itemName}
                                            </div>
                                            <div className="text-[10px] text-slate-400 mt-0.5">
                                                คงเหลือ: {c.maxQty} {c.unit}
                                            </div>
                                        </div>
                                    </div>

                                    {/* Inline Quantity Modifier & Trash Button */}
                                    <div className="flex items-center justify-between sm:justify-end gap-3 shrink-0 pt-2 sm:pt-0 border-t sm:border-t-0 border-slate-100">
                                        <div className="flex items-center gap-1.5 bg-slate-50 border border-slate-200 rounded-xl p-1">
                                            <button
                                                type="button"
                                                onClick={() => onUpdateCartQty && onUpdateCartQty(c.cartId, c.qty - 1)}
                                                className="w-7 h-7 rounded-lg bg-white hover:bg-slate-200 text-slate-700 font-bold flex items-center justify-center text-sm transition">
                                                -
                                            </button>
                                            <input
                                                type="number"
                                                min="1"
                                                max={c.maxQty}
                                                value={c.qty}
                                                onChange={(e) => onUpdateCartQty && onUpdateCartQty(c.cartId, e.target.value)}
                                                className="w-12 text-center text-xs sm:text-sm font-bold bg-transparent focus:outline-hidden"
                                            />
                                            <button
                                                type="button"
                                                onClick={() => onUpdateCartQty && onUpdateCartQty(c.cartId, c.qty + 1)}
                                                className="w-7 h-7 rounded-lg bg-white hover:bg-slate-200 text-slate-700 font-bold flex items-center justify-center text-sm transition">
                                                +
                                            </button>
                                            <span className="text-xs text-slate-500 font-semibold px-1">{c.unit}</span>
                                        </div>

                                        <button
                                            type="button"
                                            onClick={() => onRemoveCartItem && onRemoveCartItem(c.cartId)}
                                            title="ลบรายการนี้"
                                            className="w-8 h-8 rounded-xl bg-red-50 hover:bg-red-100 text-red-600 flex items-center justify-center transition tap-bounce">
                                            <Icon name="trash" size={14} />
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                ) : selectedItem ? (
                    <div className="p-3 bg-emerald-50/70 border border-emerald-200/70 rounded-2xl flex items-center gap-2.5 text-xs text-emerald-900 animate-fade-in shadow-2xs">
                        <Icon name="check-circle" size={16} className="text-emerald-600 shrink-0" />
                        <span>พร้อมเบิก <b>{selectedItem.name}</b> จำนวน <b>{pickerQty} {selectedVariant?.unit || selectedItem.unit}</b> ทันทีเมื่อกดยืนยัน (หรือกด &quot;+ เพิ่มรายการ&quot; หากต้องการเบิกหลายอย่างพร้อมกัน)</span>
                    </div>
                ) : (
                    <div className="p-3 bg-slate-50 border border-slate-200/70 rounded-2xl flex items-center gap-2 text-xs text-slate-500">
                        <Icon name="info" size={15} className="text-slate-400 shrink-0" />
                        <span>เลือกอุปกรณ์และระบุจำนวนด้านบน จากนั้นกรอกข้อมูลการเบิกด้านล่าง</span>
                    </div>
                )}

                {/* Section 3: ข้อมูลการเบิก */}
                <form onSubmit={handleStartCheckout} className="space-y-4 pt-2">
                    <h3 className="text-xs sm:text-sm font-bold text-slate-800">
                        ข้อมูลการเบิก
                    </h3>

                    {/* Security Warning Box for Technicians (user tc / user tcs) */}
                    {mustRequestApproval && (
                        <div className="p-3.5 bg-amber-50/90 border border-amber-300 rounded-2xl space-y-2.5 animate-fade-in shadow-2xs">
                            <div className="text-xs text-amber-900 leading-relaxed">
                                <strong className="block text-amber-900 font-bold mb-1 text-xs sm:text-[13px]">
                                    ข้อกำหนดความปลอดภัยในการเบิกอุปกรณ์ (สำคัญมาก)
                                </strong>
                                ขอเบิกต้องรออนุมัติจากผู้อนุมัติ ถึงจะนำของออกจากระบบได้ ถ้านำของออกก่อน ผู้ที่เบิกต้องรับผิดชอบการกระทำของตัวเอง เมื่อมีปัญหาตามมา
                            </div>
                            <label className="flex items-start gap-2 pt-2 border-t border-amber-200/90 cursor-pointer select-none text-xs text-amber-950 font-bold hover:text-amber-900 transition">
                                <input
                                    type="checkbox"
                                    checked={consentAgreed}
                                    onChange={(e) => setConsentAgreed(e.target.checked)}
                                    className="w-4 h-4 rounded text-amber-600 focus:ring-amber-500 border-amber-300 cursor-pointer mt-0.5 shrink-0"
                                />
                                <span className="leading-tight">
                                    ข้าพเจ้ารับทราบและยินยอมรับผิดชอบทุกกรณีหากนำสิ่งของออกก่อนการอนุมัติ <span className="text-red-500">*</span>
                                </span>
                            </label>
                        </div>
                    )}

                    {/* โครงการ / หน้างาน */}
                    <JobSiteSelector
                        projects={projects}
                        value={jobSite}
                        onChange={(val) => setJobSite(val)}
                    />

                    {/* เหตุผล และ ผู้ทำรายการ */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs sm:text-sm">
                        <div>
                            <label className="block text-xs font-bold text-slate-700 mb-1.5">
                                เหตุผล <span className="text-red-500">*</span>
                            </label>
                            <select
                                value={reason}
                                onChange={(e) => {
                                    setReason(e.target.value);
                                    if (e.target.value !== 'อื่นๆ') setCustomReason('');
                                }}
                                className="w-full bg-slate-50 border border-slate-200 rounded-2xl px-3.5 py-2.5 text-xs sm:text-sm font-medium focus:bg-white focus:border-emerald-500 focus:outline-hidden transition">
                                <option value="ติดตั้งใหม่">ติดตั้งใหม่</option>
                                <option value="ซ่อมแซม/เปลี่ยนอะไหล่">ซ่อมแซม / เปลี่ยนอะไหล่</option>
                                <option value="สำรองติดรถช่าง">สำรองติดรถช่าง</option>
                                <option value="ส่งมอบงานทดสอบ">ส่งมอบงานทดสอบ</option>
                                <option value="อื่นๆ">อื่นๆ</option>
                            </select>
                            {reason === 'อื่นๆ' && (
                                <div className="mt-2 animate-fade-in">
                                    <input
                                        type="text"
                                        required
                                        value={customReason}
                                        onChange={(e) => setCustomReason(e.target.value)}
                                        placeholder="พิมพ์ระบุเหตุผลเพิ่มเติม..."
                                        className="w-full bg-white border border-slate-200 rounded-2xl px-3.5 py-2.5 text-xs sm:text-sm font-medium focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/20 focus:outline-hidden transition"
                                    />
                                </div>
                            )}
                        </div>

                        {/* ผู้ทำรายการ */}
                        <div>
                            <label className="block text-xs font-bold text-slate-700 mb-1.5">
                                <span>ผู้ทำรายการ</span>
                            </label>
                            <div>
                                <input
                                    type="text"
                                    readOnly
                                    disabled
                                    value={techName}
                                    className="w-full bg-slate-100 border border-slate-200 text-slate-700 rounded-2xl px-3.5 py-2.5 text-xs sm:text-sm font-bold cursor-not-allowed select-none"
                                />
                            </div>
                        </div>
                    </div>

                    {/* หมายเหตุ */}
                    <div>
                        <label className="block text-xs font-bold text-slate-700 mb-1.5">หมายเหตุ</label>
                        <input
                            type="text"
                            value={note}
                            onChange={(e) => setNote(e.target.value)}
                            placeholder="ระบุหมายเหตุถ้ามี เช่น เบิกด่วนนอกเวลา..."
                            className="w-full bg-slate-50 border border-slate-200 rounded-2xl px-3.5 py-2.5 text-xs sm:text-sm font-medium focus:bg-white focus:border-emerald-500 focus:outline-hidden transition"
                        />
                    </div>

                    {/* Submit Button */}
                    <button
                        type="submit"
                        disabled={submitting || effectiveItemsToCheckout.length === 0 || (mustRequestApproval && !consentAgreed)}
                        className={`w-full py-3.5 text-white rounded-2xl font-bold text-sm shadow-md transition flex items-center justify-center gap-2 mt-3 tap-bounce ${
                            (mustRequestApproval && !consentAgreed) || effectiveItemsToCheckout.length === 0
                                ? 'bg-slate-300 text-slate-500 cursor-not-allowed shadow-none'
                                : mustRequestApproval
                                ? 'bg-amber-600 hover:bg-amber-700 shadow-amber-600/20 active:scale-[0.98]'
                                : 'bg-emerald-600 hover:bg-emerald-700 shadow-emerald-600/20 active:scale-[0.98]'
                        }`}>
                        <span>
                            {mustRequestApproval 
                                ? `ส่งคำขอ (${effectiveItemsToCheckout.length})` 
                                : `เบิกของ (${effectiveItemsToCheckout.length})`}
                        </span>
                    </button>
                </form>
            </div>

            {/* รายการคำขอเบิกล่าสุด หรือ ประวัติการเบิกล่าสุด (เพื่อให้เห็นรายการทันทีหลังจากเบิก) */}
            <div className="bg-white rounded-3xl p-5 sm:p-6 border border-slate-200/80 shadow-xs space-y-3.5">
                <div className="flex items-center justify-between pb-3 border-b border-slate-100">
                    <div className="flex items-center gap-2.5">
                        <div className={`w-8 h-8 rounded-xl flex items-center justify-center shrink-0 ${
                            mustRequestApproval ? 'bg-amber-50 text-amber-600' : 'bg-emerald-50 text-emerald-600'
                        }`}>
                            <Icon name={mustRequestApproval ? "clipboard-list" : "history"} size={17} />
                        </div>
                        <div>
                            <h3 className="font-bold text-slate-900 text-sm sm:text-base">
                                ประวัติล่าสุด
                            </h3>
                        </div>
                    </div>
                    {(mustRequestApproval ? onNavigateToMyRequests : onNavigateToHistory) && (
                        <button
                            type="button"
                            onClick={mustRequestApproval ? onNavigateToMyRequests : onNavigateToHistory}
                            className="text-xs font-bold text-emerald-600 hover:text-emerald-700 flex items-center gap-1 hover:underline transition tap-bounce"
                        >
                            <span>ดูทั้งหมด</span>
                            <Icon name="chevron-right" size={14} />
                        </button>
                    )}
                </div>

                {recentList.length === 0 ? (
                    <div className="py-8 text-center text-slate-400 text-xs">
                        {mustRequestApproval ? 'ยังไม่มีประวัติคำขอเบิกอุปกรณ์' : 'ยังไม่มีประวัติการเบิกตัดสต็อก'}
                    </div>
                ) : (
                    <div className="space-y-2.5">
                        {recentList.map((item, idx) => {
                            if (mustRequestApproval) {
                                const isPending = item.status === 'pending';
                                const isApproved = item.status === 'approved';
                                return (
                                    <div key={item.id || idx} className="p-3 sm:p-3.5 bg-slate-50/70 hover:bg-slate-50 border border-slate-200/80 rounded-2xl flex items-center justify-between gap-3 transition shadow-2xs">
                                        <div className="flex items-center gap-3 min-w-0">
                                            {/* Status Icon */}
                                            <div className={`w-9 h-9 sm:w-10 sm:h-10 rounded-xl flex items-center justify-center shrink-0 border ${
                                                isPending ? 'bg-amber-50 text-amber-600 border-amber-200/70' :
                                                isApproved ? 'bg-emerald-50 text-emerald-600 border-emerald-200/70' :
                                                'bg-red-50 text-red-600 border-red-200/70'
                                            }`}>
                                                <Icon name={isPending ? "clock" : isApproved ? "check-circle" : "x-circle"} size={17} />
                                            </div>

                                            <div className="min-w-0">
                                                <div className="flex items-center gap-2 flex-wrap">
                                                    <span className="font-bold text-slate-900 text-xs sm:text-sm truncate max-w-[200px]" title={item.item_name}>
                                                        {item.item_name}
                                                    </span>
                                                    <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full flex items-center gap-1 border ${
                                                        isPending ? 'bg-amber-100 text-amber-800 border-amber-200' :
                                                        isApproved ? 'bg-emerald-100 text-emerald-800 border-emerald-200' :
                                                        'bg-red-100 text-red-800 border-red-200'
                                                    }`}>
                                                        <span>{isPending ? 'รออนุมัติ' : isApproved ? 'อนุมัติ' : 'ไม่อนุมัติ'}</span>
                                                    </span>
                                                </div>
                                                <div className="text-[11px] text-slate-500 flex items-center gap-2 mt-1 flex-wrap">
                                                    <span className="font-mono text-emerald-700 font-bold bg-white px-1.5 py-0.2 rounded border border-slate-200/80 text-[10px]">{item.code || item.req_code}</span>
                                                    <span className="inline-flex items-center gap-1">
                                                        <Icon name="map-pin" size={11} className="text-slate-400 shrink-0" />
                                                        <span>{item.job_site}</span>
                                                    </span>
                                                    <span className="inline-flex items-center gap-1 text-slate-400">
                                                        <Icon name="clock" size={11} className="text-slate-400 shrink-0" />
                                                        <span>{new Date(item.created_at).toLocaleString('th-TH', { dateStyle: 'short', timeStyle: 'short' })}</span>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>

                                        <div className="text-right shrink-0">
                                            <span className="font-mono font-bold text-slate-900 text-xs sm:text-sm bg-white border border-slate-200 px-2.5 py-1 rounded-xl shadow-2xs">
                                                {item.qty} {item.unit}
                                            </span>
                                        </div>
                                    </div>
                                );
                            } else {
                                return (
                                    <div key={item.id || idx} className="p-3 sm:p-3.5 bg-slate-50/70 hover:bg-slate-50 border border-slate-200/80 rounded-2xl flex items-center justify-between gap-3 transition shadow-2xs">
                                        <div className="flex items-center gap-3 min-w-0">
                                            {/* Checkout Activity Icon */}
                                            <div className="w-9 h-9 sm:w-10 sm:h-10 rounded-xl bg-red-50 text-red-600 border border-red-200/70 flex items-center justify-center shrink-0">
                                                <Icon name="arrow-up-right" size={17} />
                                            </div>

                                            <div className="min-w-0">
                                                <div className="font-bold text-slate-900 text-xs sm:text-sm truncate max-w-[220px]" title={item.item_name}>
                                                    {item.item_name}
                                                </div>
                                                <div className="text-[11px] text-slate-500 flex items-center gap-2 mt-1 flex-wrap">
                                                    <span className="inline-flex items-center gap-1">
                                                        <Icon name="map-pin" size={11} className="text-slate-400 shrink-0" />
                                                        <span>{item.job_site || 'ไม่ระบุ'}</span>
                                                    </span>
                                                    <span className="inline-flex items-center gap-1">
                                                        <Icon name="user" size={11} className="text-slate-400 shrink-0" />
                                                        <span>{item.technician || 'ผู้เบิก'}</span>
                                                    </span>
                                                    <span className="inline-flex items-center gap-1 text-slate-400">
                                                        <Icon name="clock" size={11} className="text-slate-400 shrink-0" />
                                                        <span>{new Date(item.created_at).toLocaleString('th-TH', { dateStyle: 'short', timeStyle: 'short' })}</span>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>

                                        <div className="text-right shrink-0">
                                            <span className="font-mono font-bold text-red-600 text-xs sm:text-sm bg-red-50 border border-red-200/80 px-2.5 py-1 rounded-xl shadow-2xs">
                                                -{item.qty} {item.unit}
                                            </span>
                                        </div>
                                    </div>
                                );
                            }
                        })}
                    </div>
                )}
            </div>
        </div>
    );
}

// ==========================================
// 3. SCANNER VIEW
// ==========================================
function ScannerView({ items, projects, currentUser, userRole, cart = [], onAddToCart, onUpdateCartQty, onRemoveCartItem, onNavigateToCheckout, onSuccess, showToast }) {
    const [step, setStep] = useState(1);
    const [scannedCode, setScannedCode] = useState('');
    const [matchedItem, setMatchedItem] = useState(null);
    const [selectedVariantId, setSelectedVariantId] = useState('');
    const [scannerActive, setScannerActive] = useState(false);
    const html5QrCodeRef = useRef(null);

    const [actionType, setActionType] = useState('checkout');
    const [qty, setQty] = useState(1);
    const [selectedProject, setSelectedProject] = useState('โครงการพราว น้ำพอง');
    const [reason, setReason] = useState('ติดตั้งใหม่');
    const [consentAgreed, setConsentAgreed] = useState(false);
    const [submitting, setSubmitting] = useState(false);
    const [isReviewing, setIsReviewing] = useState(false);

    useEffect(() => {
        if (matchedItem && matchedItem.variants && matchedItem.variants.length > 0) {
            setSelectedVariantId(matchedItem.variants[0].id);
        } else {
            setSelectedVariantId('');
        }
    }, [matchedItem]);

    const startScanner = async () => {
        try {
            getScanAudioContext(); // ปลดล็อค Web Audio API ทันทีที่แตะเปิดกล้อง
            setScannerActive(true);
            setTimeout(async () => {
                if (window.Html5Qrcode) {
                    html5QrCodeRef.current = new Html5Qrcode("scanner-viewfinder");
                    await html5QrCodeRef.current.start(
                        { facingMode: "environment" },
                        { fps: 12, qrbox: { width: 240, height: 220 } },
                        (decodedText) => {
                            handleBarcodeDetected(decodedText);
                        },
                        () => {}
                    );
                }
            }, 300);
        } catch (err) {
            setScannerActive(false);
            showToast("ไม่สามารถเปิดกล้องได้ กรุณาอนุญาตสิทธิ์กล้อง", "error");
        }
    };

    const stopScanner = async () => {
        if (html5QrCodeRef.current) {
            try {
                await html5QrCodeRef.current.stop();
                html5QrCodeRef.current.clear();
            } catch (e) {}
            html5QrCodeRef.current = null;
        }
        setScannerActive(false);
    };

    const handleBarcodeDetected = (code) => {
        stopScanner();
        setScannedCode(code);
        const trimmed = (code || '').trim().toLowerCase();
        const item = items.find(i => 
            (i.code && i.code.toLowerCase() === trimmed) || 
            (i.name && i.name.toLowerCase().includes(trimmed))
        );
        if (item) {
            playScanFeedback(true); // เสียงติ๊ดใส + สั่นเตือน
            setMatchedItem(item);
            setQty(1);
            setStep(2);
        } else {
            playScanFeedback(false); // เสียงเตือนไม่พบ
            showToast(`ไม่พบรหัสสินค้า ${code}`, "warning");
        }
    };

    useEffect(() => {
        return () => { stopScanner(); };
    }, []);

    // เพิ่มอุปกรณ์ลงในตะกร้าเบิก และกลับมาพร้อมสแกนชิ้นต่อไป
    const handleAddToCartAndScanMore = () => {
        if (!matchedItem) return;
        const numQty = Number(qty);
        if (numQty <= 0) return showToast("กรุณาระบุจำนวนที่มากกว่า 0", "error");

        const chosenVariant = matchedItem.variants?.find(v => v.id === selectedVariantId) || matchedItem.variants?.[0] || null;
        const availableStock = chosenVariant ? Number(chosenVariant.qty || 0) : Number(matchedItem.total_qty || 0);

        const existingInCart = cart.find(c => c.itemId === matchedItem.id && c.variantId === (chosenVariant?.id || ''));
        const totalRequested = (existingInCart?.qty || 0) + numQty;

        if (totalRequested > availableStock) {
            return showToast(`ยอดคงเหลือไม่พอ (มีเพียง ${availableStock} ${matchedItem.unit}, อยู่ในรายการแล้ว ${existingInCart?.qty || 0})`, "warning");
        }

        if (onAddToCart) {
            onAddToCart(matchedItem, chosenVariant, numQty);
            showToast(`เพิ่ม "${matchedItem.name}" (${numQty} ${matchedItem.unit}) ลงรายการเบิกแล้ว`);
            setStep(1);
            setScannedCode('');
            setMatchedItem(null);
            setQty(1);
        }
    };

    // เพิ่มอุปกรณ์ลงในตะกร้าเบิก และไปที่หน้าเบิกทันที
    const handleAddToCartAndGoToCheckout = () => {
        if (!matchedItem) return;
        const numQty = Number(qty);
        if (numQty <= 0) return showToast("กรุณาระบุจำนวนที่มากกว่า 0", "error");

        const chosenVariant = matchedItem.variants?.find(v => v.id === selectedVariantId) || matchedItem.variants?.[0] || null;
        const availableStock = chosenVariant ? Number(chosenVariant.qty || 0) : Number(matchedItem.total_qty || 0);

        const existingInCart = cart.find(c => c.itemId === matchedItem.id && c.variantId === (chosenVariant?.id || ''));
        const totalRequested = (existingInCart?.qty || 0) + numQty;

        if (totalRequested > availableStock) {
            return showToast(`ยอดคงเหลือไม่พอ (มีเพียง ${availableStock} ${matchedItem.unit}, อยู่ในรายการแล้ว ${existingInCart?.qty || 0})`, "warning");
        }

        if (onAddToCart) {
            onAddToCart(matchedItem, chosenVariant, numQty);
            showToast(`เพิ่ม "${matchedItem.name}" (${numQty} ${matchedItem.unit}) ลงรายการเบิกแล้ว`);
            setStep(1);
            setScannedCode('');
            setMatchedItem(null);
            setQty(1);
            if (onNavigateToCheckout) {
                onNavigateToCheckout();
            }
        }
    };

    const handleStartReview = () => {
        if (!matchedItem) return;
        if (Number(qty) <= 0) return showToast("กรุณาระบุจำนวนที่มากกว่า 0", "error");
        if (actionType === 'checkout' && Number(qty) > (Number(matchedItem.total_qty) || 0)) {
            return showToast(`ยอดคงเหลือไม่พอ (มีเพียง ${matchedItem.total_qty} ${matchedItem.unit})`, "warning");
        }
        if (actionType === 'checkout' && userRole?.mustRequestApproval && !consentAgreed) {
            return showToast("กรุณาทำเครื่องหมายยินยอมรับผิดชอบทุกกรณีหากนำสิ่งของออกก่อนการอนุมัติ", "warning");
        }
        setIsReviewing(true);
    };

    const handleConfirmAction = async () => {
        if (!matchedItem) return;
        setSubmitting(true);
        try {
            if (actionType === 'checkout') {
                if (userRole?.mustRequestApproval) {
                    const res = await StockApi.createRequisition({
                        itemId: matchedItem.id,
                        variantId: selectedVariantId || matchedItem.variants?.[0]?.id || '',
                        qty: Number(qty),
                        jobSite: selectedProject,
                        reason,
                        technician: currentUser.name,
                        note: 'สแกนขอเบิกผ่านมือถือ'
                    });
                    setIsReviewing(false);
                    setStep(3);
                    onSuccess();
                    showToast(`ส่งคำขอเบิก ${res.code} สำเร็จ! (รอ Admin อนุมัติ)`);
                    return;
                } else {
                    await StockApi.checkoutItem({
                        itemId: matchedItem.id,
                        variantId: selectedVariantId || matchedItem.variants?.[0]?.id || '',
                        qty: Number(qty),
                        jobSite: selectedProject,
                        reason,
                        technician: currentUser.name
                    });
                }
            } else {
                await StockApi.checkinItem({
                    itemId: matchedItem.id,
                    qty: Number(qty),
                    reason: 'รับเข้าคลังผ่านมือถือ',
                    technician: currentUser.name
                });
            }
            setIsReviewing(false);
            setStep(3);
            onSuccess();
        } catch (err) {
            showToast(toFriendlyError(err), "error");
        } finally {
            setSubmitting(false);
        }
    };

    const selectedVariantObj = matchedItem?.variants?.find(v => v.id === selectedVariantId) || matchedItem?.variants?.[0];

    return (
        <div className="max-w-xl mx-auto space-y-3">
            {/* Modern Saving & Loading Modal */}
            <ModernLoadingModal show={submitting} title="กำลังบันทึก..." />

            <div className="bg-white rounded-3xl p-5 sm:p-8 border border-slate-200/80 shadow-xs">
                <div className="flex items-center justify-between mb-5 pb-3 border-b border-slate-100">
                    <div className="flex items-center gap-2">
                        <span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${step >= 1 ? 'bg-emerald-600 text-white' : 'bg-slate-100 text-slate-400'}`}>1</span>
                        <span className="text-xs font-semibold text-slate-700">สแกน</span>
                    </div>
                    <div className="w-8 h-0.5 bg-slate-200"></div>
                    <div className="flex items-center gap-2">
                        <span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${step >= 2 ? 'bg-emerald-600 text-white' : 'bg-slate-100 text-slate-400'}`}>2</span>
                        <span className="text-xs font-semibold text-slate-700">เลือกรายการ</span>
                    </div>
                    <div className="w-8 h-0.5 bg-slate-200"></div>
                    <div className="flex items-center gap-2">
                        <span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${step === 3 ? 'bg-emerald-600 text-white' : 'bg-slate-100 text-slate-400'}`}>3</span>
                        <span className="text-xs font-semibold text-slate-700">เสร็จสิ้น</span>
                    </div>
                </div>

                {step === 1 && (
                    <div className="text-center space-y-4">
                        <div className="w-14 h-14 rounded-2xl bg-emerald-50 text-emerald-600 flex items-center justify-center mx-auto">
                            <Icon name="scan" size={28} />
                        </div>
                        <h3 className="font-bold text-base sm:text-lg text-slate-900">สแกน QR / บาร์โค้ดหน้ากล่อง</h3>

                        {scannerActive ? (
                            <div className="relative rounded-2xl overflow-hidden bg-black max-w-sm mx-auto shadow-inner">
                                <div id="scanner-viewfinder" className="w-full"></div>
                                <div className="scanner-laser"></div>
                                <button 
                                    onClick={stopScanner} 
                                    className="absolute top-3 right-3 px-3 py-1 bg-black/60 text-white text-xs rounded-xl backdrop-blur-xs">
                                    ปิดกล้อง
                                </button>
                            </div>
                        ) : (
                            <button
                                onClick={startScanner}
                                className="w-full py-3.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-2xl font-bold text-xs sm:text-sm shadow-md shadow-emerald-600/20 flex items-center justify-center gap-2 transition">
                                <Icon name="camera" size={18} />
                                <span>เปิดกล้อง</span>
                            </button>
                        )}

                        <div className="pt-3 border-t border-slate-100 text-left space-y-2">
                            <label className="block text-xs font-bold text-slate-500">พิมพ์รหัสค้นหา</label>
                            <div className="flex gap-2">
                                <input
                                    type="text"
                                    placeholder="เช่น STK-001 หรือ ท่อรีด"
                                    value={scannedCode}
                                    onChange={(e) => setScannedCode(e.target.value)}
                                    onKeyDown={(e) => { if (e.key === 'Enter') handleBarcodeDetected(scannedCode); }}
                                    className="flex-1 bg-slate-50 border border-slate-200 rounded-2xl px-3.5 py-2.5 text-xs sm:text-sm focus:outline-hidden"
                                />
                                <button
                                    onClick={() => handleBarcodeDetected(scannedCode)}
                                    className="px-4 py-2.5 bg-slate-800 text-white font-bold rounded-2xl text-xs">
                                    ค้นหา
                                </button>
                            </div>
                        </div>
                    </div>
                )}

            {step === 2 && matchedItem && (
                <div className="space-y-4">
                    {/* Equipment Match Banner with Thumbnail Image */}
                    <div className="p-3 sm:p-3.5 rounded-2xl bg-emerald-50/70 border border-emerald-200/90 flex items-center gap-3">
                        <div className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl overflow-hidden bg-white border border-emerald-200/80 shrink-0 flex items-center justify-center shadow-xs">
                            {matchedItem.image_url ? (
                                <img src={matchedItem.image_url} alt={matchedItem.name} className="w-full h-full object-cover" />
                            ) : (
                                <Icon name="package" size={26} className="text-slate-300" />
                            )}
                        </div>
                        <div className="flex-1 min-w-0">
                            <span className="text-[11px] font-mono text-emerald-700 font-bold">{matchedItem.code}</span>
                            <h4 className="font-bold text-slate-900 text-xs sm:text-sm mt-0.5 truncate">{matchedItem.name}</h4>
                            <span className="text-xs text-slate-500 block mt-0.5">
                                คงเหลือ: <b className="text-emerald-700">{matchedItem.total_qty} {matchedItem.unit}</b>
                            </span>
                        </div>
                        <button 
                            type="button"
                            onClick={() => { setStep(1); stopScanner(); }}
                            className="text-xs text-slate-400 hover:text-slate-600 font-medium px-2 py-1 rounded-lg hover:bg-white shrink-0">
                            เปลี่ยน
                        </button>
                    </div>

                    {userRole?.canManageStock && (
                        <div>
                            <label className="block text-xs font-bold text-slate-700 mb-1.5">ประเภท</label>
                            <div className="grid grid-cols-2 gap-2">
                                <button
                                    type="button"
                                    onClick={() => setActionType('checkout')}
                                    className={`py-2.5 rounded-2xl font-bold text-xs flex items-center justify-center gap-1.5 transition ${
                                        actionType === 'checkout' ? 'bg-amber-500 text-white shadow-xs' : 'bg-slate-100 text-slate-600'
                                    }`}>
                                    <Icon name="arrow-up-right" size={15} />
                                    <span>เพิ่มรายการเบิก</span>
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setActionType('checkin')}
                                    className={`py-2.5 rounded-2xl font-bold text-xs flex items-center justify-center gap-1.5 transition ${
                                        actionType === 'checkin' ? 'bg-emerald-600 text-white shadow-xs' : 'bg-slate-100 text-slate-600'
                                    }`}>
                                    <Icon name="arrow-down-left" size={15} />
                                    <span>รับเข้าคลัง</span>
                                </button>
                            </div>
                        </div>
                    )}

                    {/* Variant Condition Selector if multiple */}
                    {matchedItem.variants && matchedItem.variants.length > 1 && (
                        <div>
                            <label className="block text-xs font-bold text-slate-700 mb-1.5">สภาพสินค้า</label>
                            <select
                                value={selectedVariantId}
                                onChange={(e) => setSelectedVariantId(e.target.value)}
                                className="w-full bg-slate-50 border border-slate-200 rounded-2xl px-3.5 py-2.5 text-xs sm:text-sm font-semibold text-slate-800">
                                {matchedItem.variants.map(v => (
                                    <option key={v.id} value={v.id}>
                                        {v.name} (คงเหลือ: {v.qty} {matchedItem.unit})
                                    </option>
                                ))}
                            </select>
                        </div>
                    )}

                    <div>
                        <div className="flex items-center justify-between mb-1.5">
                            <label className="text-xs font-bold text-slate-700">จำนวน ({matchedItem.unit})</label>
                            {selectedVariantObj && (
                                <span className="text-[11px] text-slate-500">
                                    สภาพ {selectedVariantObj.name}: <b className="text-emerald-700">{selectedVariantObj.qty} {matchedItem.unit}</b>
                                </span>
                            )}
                        </div>
                        <div className="flex items-center gap-2">
                            <button
                                type="button"
                                onClick={() => setQty(Math.max(1, qty - 1))}
                                className="w-11 h-11 rounded-2xl bg-slate-100 text-slate-700 font-bold flex items-center justify-center text-lg">
                                -
                            </button>
                            <input
                                type="number"
                                min="1"
                                value={qty}
                                onChange={(e) => setQty(e.target.value)}
                                className="flex-1 bg-slate-50 border border-slate-200 rounded-2xl py-2.5 text-center text-base font-bold"
                            />
                            <button
                                type="button"
                                onClick={() => setQty(Number(qty) + 1)}
                                className="w-11 h-11 rounded-2xl bg-slate-100 text-slate-700 font-bold flex items-center justify-center text-lg">
                                +
                            </button>
                        </div>
                    </div>

                    {/* Action Buttons: Add to Cart */}
                    {actionType === 'checkout' ? (
                        <div className="pt-1">
                            <button
                                type="button"
                                onClick={handleAddToCartAndScanMore}
                                className="w-full py-3.5 px-4 bg-emerald-600 hover:bg-emerald-700 active:scale-[0.98] text-white rounded-2xl font-bold text-xs sm:text-sm flex items-center justify-center gap-2 transition tap-bounce shadow-md shadow-emerald-600/20"
                            >
                                <Icon name="plus" size={17} />
                                <span>เพิ่มรายการเบิก</span>
                            </button>
                        </div>
                    ) : (
                        <button
                            type="button"
                            onClick={handleStartReview}
                            disabled={submitting}
                            className="w-full py-3.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-2xl font-bold text-xs sm:text-sm shadow-md shadow-emerald-600/20 flex items-center justify-center gap-2 mt-2 transition tap-bounce">
                            <span>บันทึกรับเข้า</span>
                        </button>
                    )}
                </div>
            )}

            {/* Review Confirmation Modal */}
            {isReviewing && matchedItem && (
                <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto animate-fade-in">
                    <div className="bg-white rounded-3xl max-w-md w-full shadow-2xl border border-slate-100 my-auto flex flex-col max-h-[calc(100dvh-2rem)] sm:max-h-[92vh] overflow-hidden modal-responsive-card">
                        <div className="px-5 py-3.5 sm:py-4 border-b border-slate-100 flex items-center justify-between shrink-0 bg-white">
                            <div className="flex items-center gap-2">
                                <span className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${userRole?.mustRequestApproval ? 'bg-amber-100 text-amber-600' : 'bg-emerald-100 text-emerald-600'}`}>
                                    <Icon name={userRole?.mustRequestApproval ? "clipboard-list" : "check"} size={18} />
                                </span>
                                <div>
                                    <h3 className="font-bold text-slate-900 text-sm sm:text-base">
                                        {actionType === 'checkout' && userRole?.mustRequestApproval ? 'ตรวจสอบคำขอ' : 'ตรวจสอบ'}
                                    </h3>
                                    <p className="text-[11px] text-slate-400">กรุณาตรวจสอบความถูกต้องก่อนทำรายการ</p>
                                </div>
                            </div>
                            <button onClick={() => setIsReviewing(false)} className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition">
                                <Icon name="x" size={18} />
                            </button>
                        </div>

                        <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-3 text-xs">
                            <div className="p-3 bg-slate-50 rounded-2xl border border-slate-100 space-y-2">
                                <div className="flex justify-between">
                                    <span className="text-slate-400 font-medium">ประเภทรายการ:</span>
                                    <span className={`font-bold ${actionType === 'checkout' ? 'text-amber-600' : 'text-emerald-600'}`}>
                                        {actionType === 'checkout' ? (userRole?.mustRequestApproval ? 'ขอเบิก (รออนุมัติ)' : 'เบิกออกหน้างาน') : 'รับเข้าคลัง'}
                                    </span>
                                </div>
                                <div className="flex justify-between items-start">
                                    <span className="text-slate-400 font-medium">อุปกรณ์:</span>
                                    <span className="font-bold text-slate-800 text-right">{matchedItem.name} ({matchedItem.code})</span>
                                </div>
                                {selectedVariantObj && (
                                    <div className="flex justify-between">
                                        <span className="text-slate-400 font-medium">สภาพ:</span>
                                        <span className="font-semibold text-slate-700">{selectedVariantObj.name}</span>
                                    </div>
                                )}
                                <div className="flex justify-between">
                                    <span className="text-slate-400 font-medium">จำนวนที่ทำรายการ:</span>
                                    <span className="font-bold text-emerald-700 text-sm">{qty} {matchedItem.unit}</span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-slate-400 font-medium">คงเหลือ:</span>
                                    <span className="font-semibold text-slate-700">
                                        {matchedItem.total_qty} {matchedItem.unit}
                                    </span>
                                </div>
                                {actionType === 'checkout' && (
                                    <div className="flex justify-between">
                                        <span className="text-slate-400 font-medium">โครงการ / หน้างาน:</span>
                                        <span className="font-bold text-slate-800 text-right">{selectedProject}</span>
                                    </div>
                                )}
                                <div className="flex justify-between">
                                    <span className="text-slate-400 font-medium">ผู้ทำรายการ:</span>
                                    <span className="font-bold text-slate-800">{currentUser?.name || 'ช่างเทคนิค'}</span>
                                </div>
                            </div>
                        </div>

                        <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2.5 shrink-0">
                            <button
                                type="button"
                                onClick={() => setIsReviewing(false)}
                                disabled={submitting}
                                className="flex-1 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl font-bold text-xs sm:text-sm transition tap-bounce">
                                แก้ไข
                            </button>
                            <button
                                type="button"
                                onClick={handleConfirmAction}
                                disabled={submitting}
                                className={`flex-1 py-2.5 text-white rounded-xl font-bold text-xs sm:text-sm shadow-md transition flex items-center justify-center gap-1.5 tap-bounce ${
                                    actionType === 'checkout' && userRole?.mustRequestApproval
                                        ? 'bg-amber-600 hover:bg-amber-700 shadow-amber-600/20'
                                        : 'bg-emerald-600 hover:bg-emerald-700 shadow-emerald-600/20'
                                }`}>
                                <span>
                                    {submitting 
                                        ? 'กำลังบันทึก...' 
                                        : (actionType === 'checkout' && userRole?.mustRequestApproval ? 'ส่งคำขอ' : 'ยืนยัน')}
                                </span>
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {step === 3 && (
                <div className="text-center py-6 space-y-3">
                    <div className="w-14 h-14 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center mx-auto">
                        <Icon name="check" size={28} />
                    </div>
                    <h3 className="font-bold text-base text-slate-900">ทำรายการสำเร็จเรียบร้อย!</h3>
                    <p className="text-xs text-slate-500">
                        {actionType === 'checkout' && userRole?.mustRequestApproval 
                            ? 'ส่งคำขอเบิกไปยัง Admin เรียบร้อยแล้ว (รอการอนุมัติก่อนนำของออก)' 
                            : 'ตัดสต็อกและส่งแจ้งเตือน Telegram แล้ว'}
                    </p>

                    <div className="flex flex-col sm:flex-row gap-2 justify-center mt-3">
                        <button
                            onClick={() => { setStep(1); setScannedCode(''); setMatchedItem(null); setConsentAgreed(false); }}
                            className="px-5 py-2.5 bg-slate-800 text-white rounded-2xl font-bold text-xs hover:bg-slate-900 transition flex items-center justify-center gap-1.5">
                            <Icon name="scan" size={15} />
                            <span>สแกนรายการต่อไป</span>
                        </button>
                        {cart && cart.length > 0 && onNavigateToCheckout && (
                            <button
                                onClick={onNavigateToCheckout}
                                className="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-2xl font-bold text-xs shadow-md shadow-emerald-600/20 transition flex items-center justify-center gap-1.5 tap-bounce">
                                <Icon name="shopping-cart" size={15} />
                                <span>ไปหน้าเบิก ({cart.length} รายการ)</span>
                            </button>
                        )}
                    </div>
                </div>
            )}
            </div>

            {/* Scanned Items Review List (แสดงรายการที่เพิ่มแล้ว เรียงต่อกันลงมาเพื่อตรวจสอบก่อนไปหน้าเบิก) */}
            {cart && cart.length > 0 && (
                <div className="bg-white rounded-3xl p-4 sm:p-6 border border-slate-200/80 shadow-xs space-y-3.5 animate-fade-in">
                    <div className="flex items-center justify-between pb-3 border-b border-slate-100">
                        <div className="flex items-center gap-2.5">
                            <div className="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center font-bold">
                                <Icon name="clipboard-list" size={17} />
                            </div>
                            <div>
                                <h3 className="font-bold text-slate-900 text-sm sm:text-base">
                                    รายการสแกน ({cart.length} รายการ)
                                </h3>
                            </div>
                        </div>
                        <span className="text-xs font-bold px-2.5 py-1 rounded-full bg-emerald-100 text-emerald-800">
                            รวม {cart.reduce((s, c) => s + (c.qty || 1), 0)} ชิ้น
                        </span>
                    </div>

                    {/* Stacked list of items */}
                    <div className="divide-y divide-slate-100">
                        {cart.map((c, idx) => (
                            <div key={c.cartId || idx} className="py-2.5 sm:py-3 flex items-center justify-between gap-2.5 text-xs">
                                <div className="flex items-center gap-2.5 min-w-0">
                                    <div className="w-11 h-11 sm:w-12 sm:h-12 rounded-xl bg-slate-50 border border-slate-200 overflow-hidden shrink-0 flex items-center justify-center">
                                        {c.itemImage ? (
                                            <img src={c.itemImage} alt={c.itemName} className="w-full h-full object-cover" />
                                        ) : (
                                            <Icon name="package" size={20} className="text-slate-300" />
                                        )}
                                    </div>
                                    <div className="min-w-0">
                                        <div className="font-bold text-slate-900 text-xs sm:text-sm truncate" title={c.itemName}>
                                            {idx + 1}. {c.itemName}
                                        </div>
                                        <div className="text-[11px] text-slate-500 flex items-center gap-1.5 mt-0.5 flex-wrap">
                                            <span className="font-mono text-emerald-700 font-bold">{c.itemCode}</span>
                                            <span>• สภาพ: <b className="text-slate-700">{c.variantName || 'ปกติ'}</b></span>
                                        </div>
                                    </div>
                                </div>

                                {/* Quantity controls and remove */}
                                <div className="flex items-center gap-2 shrink-0">
                                    {onUpdateCartQty && (
                                        <div className="flex items-center bg-slate-100 rounded-xl p-0.5 border border-slate-200">
                                            <button
                                                type="button"
                                                onClick={() => onUpdateCartQty(c.cartId, Math.max(1, (c.qty || 1) - 1))}
                                                className="w-7 h-7 rounded-lg bg-white hover:bg-slate-50 text-slate-700 font-bold flex items-center justify-center shadow-2xs transition tap-bounce"
                                            >
                                                -
                                            </button>
                                            <span className="w-7 text-center font-bold text-slate-800 font-mono text-xs">
                                                {c.qty}
                                            </span>
                                            <button
                                                type="button"
                                                onClick={() => onUpdateCartQty(c.cartId, (c.qty || 1) + 1)}
                                                className="w-7 h-7 rounded-lg bg-white hover:bg-slate-50 text-slate-700 font-bold flex items-center justify-center shadow-2xs transition tap-bounce"
                                            >
                                                +
                                            </button>
                                        </div>
                                    )}
                                    <span className="text-[11px] text-slate-500 font-medium hidden sm:inline">{c.unit}</span>
                                    {onRemoveCartItem && (
                                        <button
                                            type="button"
                                            onClick={() => onRemoveCartItem(c.cartId)}
                                            title="ลบรายการนี้"
                                            className="w-8 h-8 rounded-xl bg-red-50 hover:bg-red-100 text-red-600 flex items-center justify-center transition tap-bounce shrink-0"
                                        >
                                            <Icon name="trash" size={14} />
                                        </button>
                                    )}
                                </div>
                            </div>
                        ))}
                    </div>

                    {/* Single Clean Checkout Button */}
                    {onNavigateToCheckout && (
                        <div className="pt-2 border-t border-slate-100">
                            <button
                                type="button"
                                onClick={onNavigateToCheckout}
                                className="w-full py-3.5 bg-emerald-600 hover:bg-emerald-700 active:scale-[0.98] text-white rounded-2xl font-bold text-sm shadow-md shadow-emerald-600/20 flex items-center justify-center gap-2 transition tap-bounce"
                            >
                                <span>ไปหน้าเบิก</span>
                                <span className="px-2 py-0.5 rounded-full bg-emerald-500 text-white text-xs">
                                    {cart.length} รายการ ({cart.reduce((s, c) => s + (c.qty || 1), 0)} ชิ้น)
                                </span>
                                <Icon name="arrow-right" size={16} />
                            </button>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}

// ==========================================
// 4. AUDIT MODE VIEW
// ==========================================
function AuditModeView({ items, currentUser, isAdmin, openConfirm, onSuccess, showToast }) {
    const [counts, setCounts] = useState({});
    const [submitting, setSubmitting] = useState(false);
    const [filterDiffOnly, setFilterDiffOnly] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedCategory, setSelectedCategory] = useState('all');
    const [isReviewing, setIsReviewing] = useState(false);

    useEffect(() => {
        const initial = {};
        items.forEach(i => { initial[i.id] = Number(i.total_qty) || 0; });
        setCounts(initial);
    }, [items]);

    const handleCountChange = (id, val) => {
        setCounts(prev => ({ ...prev, [id]: Number(val) || 0 }));
    };

    // Extract all unique categories
    const categories = useMemo(() => {
        const set = new Set();
        items.forEach(i => {
            if (i.category && i.category.trim()) set.add(i.category.trim());
            else set.add('ทั่วไป');
        });
        return Array.from(set).sort();
    }, [items]);

    const diffList = useMemo(() => {
        return items.map(item => {
            const counted = counts[item.id] !== undefined ? counts[item.id] : (Number(item.total_qty) || 0);
            const system = Number(item.total_qty) || 0;
            const diff = counted - system;
            return { item, system, counted, diff };
        });
    }, [items, counts]);

    const totalDiffCount = diffList.filter(d => d.diff !== 0).length;
    const changedItems = diffList.filter(d => d.diff !== 0);

    // Filter items by diff, category, and search query
    const filteredItems = useMemo(() => {
        return diffList.filter(d => {
            if (filterDiffOnly && d.diff === 0) return false;
            const itemCat = d.item.category?.trim() || 'ทั่วไป';
            if (selectedCategory !== 'all' && itemCat !== selectedCategory) return false;
            if (searchQuery.trim()) {
                const q = searchQuery.toLowerCase().trim();
                const matchName = d.item.name?.toLowerCase().includes(q);
                const matchCode = d.item.code?.toLowerCase().includes(q);
                const matchCat = itemCat.toLowerCase().includes(q);
                if (!matchName && !matchCode && !matchCat) return false;
            }
            return true;
        });
    }, [diffList, filterDiffOnly, selectedCategory, searchQuery]);

    // Group items by category
    const groupedByCategory = useMemo(() => {
        const groups = {};
        filteredItems.forEach(d => {
            const cat = d.item.category?.trim() || 'ทั่วไป';
            if (!groups[cat]) groups[cat] = [];
            groups[cat].push(d);
        });
        return groups;
    }, [filteredItems]);

    const handleStartReconcile = () => {
        if (!isAdmin) {
            return showToast("เฉพาะผู้ดูแลระบบ (Admin) เท่านั้นที่ปรับยอดสต็อกจริงได้", "error");
        }
        setIsReviewing(true);
    };

    const handleConfirmReconcile = async () => {
        setSubmitting(true);
        try {
            const records = diffList.map(d => ({
                itemId: d.item.id,
                systemQty: d.system,
                countedQty: d.counted,
                diffQty: d.diff
            }));

            await StockApi.reconcileAuditRecords({
                auditRecords: records,
                auditorName: currentUser.name
            });
            setIsReviewing(false);
            onSuccess();
        } catch (err) {
            showToast(toFriendlyError(err), "error");
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <div className="space-y-3.5">
            {/* Modern Saving & Loading Modal */}
            <ModernLoadingModal show={submitting} title="กำลังบันทึกยอดตรวจนับ..." />

            {/* Header Card */}
            <div className="bg-white rounded-3xl p-4 sm:p-5 border border-slate-200/80 shadow-xs flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
                <div>
                    <h2 className="font-bold text-slate-900 text-sm sm:text-base">ตรวจนับสต็อกประจำงวด</h2>
                </div>

                <div className="flex items-center gap-2 w-full sm:w-auto">
                    {isAdmin && (
                        <button
                            onClick={handleStartReconcile}
                            disabled={submitting}
                            className="flex-1 sm:flex-none px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold text-xs shadow-sm transition flex items-center justify-center gap-1.5">
                            <Icon name="check" size={14} />
                            <span>{submitting ? 'กำลังบันทึก...' : 'ปรับยอดตามจริง'}</span>
                        </button>
                    )}
                </div>
            </div>

            {/* Filter & Search Bar */}
            <div className="bg-white rounded-3xl p-3.5 sm:p-4 border border-slate-200/80 shadow-xs flex flex-col md:flex-row items-stretch md:items-center gap-2.5">
                {/* Search Input */}
                <div className="relative flex-1">
                    <Icon name="search" size={15} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400" />
                    <input
                        type="text"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        placeholder="ค้นหาชื่ออุปกรณ์, รหัสสินค้า..."
                        className="w-full bg-slate-50 border border-slate-200 rounded-2xl pl-9 pr-8 py-2 text-xs font-medium focus:bg-white focus:border-emerald-500 focus:outline-hidden transition"
                    />
                    {searchQuery && (
                        <button 
                            onClick={() => setSearchQuery('')}
                            className="absolute right-2.5 top-1/2 -translate-y-1/2 p-1 text-slate-400 hover:text-slate-600">
                            <Icon name="x" size={13} />
                        </button>
                    )}
                </div>

                {/* Category Select */}
                <div className="w-full md:w-56">
                    <select
                        value={selectedCategory}
                        onChange={(e) => setSelectedCategory(e.target.value)}
                        className="w-full bg-slate-50 border border-slate-200 rounded-2xl px-3 py-2 text-xs font-semibold text-slate-700 focus:bg-white focus:border-emerald-500 focus:outline-hidden transition">
                        <option value="all">ทุกหมวดหมู่ ({items.length})</option>
                        {categories.map(cat => {
                            const catCount = items.filter(i => (i.category?.trim() || 'ทั่วไป') === cat).length;
                            return (
                                <option key={cat} value={cat}>หมวดหมู่: {cat} ({catCount})</option>
                            );
                        })}
                    </select>
                </div>

                {/* Difference Filter Button */}
                <button
                    onClick={() => setFilterDiffOnly(!filterDiffOnly)}
                    className={`px-3.5 py-2 rounded-2xl text-xs font-bold transition flex items-center justify-center gap-1.5 shrink-0 ${
                        filterDiffOnly ? 'bg-amber-500 text-white shadow-xs' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
                    }`}>
                    <Icon name="filter" size={13} />
                    <span>ยอดต่าง ({totalDiffCount})</span>
                </button>
            </div>

            {/* Grouped by Category Tables */}
            {Object.keys(groupedByCategory).length === 0 ? (
                <div className="bg-white rounded-3xl p-10 text-center border border-slate-200/80 shadow-xs">
                    <div className="w-12 h-12 rounded-2xl bg-slate-100 text-slate-400 flex items-center justify-center mx-auto mb-2">
                        <Icon name="package" size={24} />
                    </div>
                    <p className="font-bold text-slate-700 text-xs sm:text-sm">ไม่พบรายการอุปกรณ์</p>
                    <p className="text-[11px] text-slate-400 mt-0.5">ลองค้นหาด้วยคำอื่น หรือเลือกหมวดหมู่อื่น</p>
                </div>
            ) : (
                <div className="space-y-4">
                    {Object.entries(groupedByCategory).map(([catName, groupItems]) => (
                        <div key={catName} className="bg-white rounded-3xl border border-slate-200/80 shadow-xs overflow-hidden">
                            <div className="bg-slate-50/80 px-4 py-2.5 border-b border-slate-100 flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <span className="w-2 h-2 rounded-full bg-emerald-500"></span>
                                    <span className="font-bold text-slate-800 text-xs sm:text-sm">หมวดหมู่: {catName}</span>
                                    <span className="px-2 py-0.2 rounded-full text-[10px] font-bold bg-white text-slate-500 border border-slate-200">
                                        {groupItems.length} รายการ
                                    </span>
                                </div>
                            </div>
                            <div className="overflow-x-auto">
                                <table className="w-full text-left text-xs">
                                    <thead className="bg-slate-50/40 border-b border-slate-100 text-slate-400 font-bold uppercase text-[10px]">
                                        <tr>
                                            <th className="py-2.5 px-3 sm:px-4">รหัส / อุปกรณ์</th>
                                            <th className="py-2.5 px-2 text-center">ยอดระบบ</th>
                                            <th className="py-2.5 px-2 text-center">นับจริง</th>
                                            <th className="py-2.5 px-3 text-center">ผลต่าง</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-slate-100">
                                        {groupItems.map(({ item, system, counted, diff }) => {
                                            const isMatch = diff === 0;
                                            const isShortage = diff < 0;
                                            return (
                                                <tr key={item.id} className="hover:bg-slate-50/50">
                                                    <td className="py-2.5 px-3 sm:px-4">
                                                        <div className="font-mono text-[10px] text-slate-400 font-bold">{item.code}</div>
                                                        <div className="font-semibold text-slate-800 line-clamp-1">{item.name}</div>
                                                    </td>
                                                    <td className="py-2.5 px-2 text-center font-bold text-slate-600 whitespace-nowrap">
                                                        {system} {item.unit}
                                                    </td>
                                                    <td className="py-2.5 px-2 text-center">
                                                        <div className="inline-flex items-center gap-1">
                                                            <button 
                                                                onClick={() => handleCountChange(item.id, Math.max(0, counted - 1))}
                                                                className="w-6 h-6 rounded-lg bg-slate-100 hover:bg-slate-200 font-bold text-xs">-</button>
                                                            <input
                                                                type="number"
                                                                min="0"
                                                                value={counted}
                                                                onChange={(e) => handleCountChange(item.id, e.target.value)}
                                                                className="w-12 text-center font-bold bg-slate-50 border border-slate-200 rounded-lg py-1 text-xs focus:bg-white focus:border-emerald-500 focus:outline-hidden"
                                                            />
                                                            <button 
                                                                onClick={() => handleCountChange(item.id, counted + 1)}
                                                                className="w-6 h-6 rounded-lg bg-slate-100 hover:bg-slate-200 font-bold text-xs">+</button>
                                                        </div>
                                                    </td>
                                                    <td className="py-2.5 px-3 text-center whitespace-nowrap">
                                                        {isMatch ? (
                                                            <span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-emerald-100 text-emerald-800">
                                                                ตรง
                                                            </span>
                                                        ) : isShortage ? (
                                                            <span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-100 text-red-700">
                                                                ขาด {Math.abs(diff)}
                                                            </span>
                                                        ) : (
                                                            <span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800">
                                                                เกิน +{diff}
                                                            </span>
                                                        )}
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {/* Review Confirmation Modal */}
            {isReviewing && (
                <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto animate-fade-in">
                    <div className="bg-white rounded-3xl max-w-lg w-full shadow-2xl border border-slate-100 my-auto flex flex-col max-h-[calc(100dvh-2rem)] sm:max-h-[92vh] overflow-hidden modal-responsive-card">
                        <div className="px-5 py-3.5 sm:py-4 border-b border-slate-100 flex items-center justify-between shrink-0 bg-white">
                            <div className="flex items-center gap-2">
                                <span className="w-8 h-8 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center shrink-0">
                                    <Icon name="check" size={18} />
                                </span>
                                <div>
                                    <h3 className="font-bold text-slate-900 text-sm sm:text-base">ตรวจสอบข้อมูลก่อนปรับยอดสต็อก</h3>
                                    <p className="text-[11px] text-slate-400">กรุณาตรวจสอบรายการที่มีส่วนต่างก่อนบันทึกเข้าระบบ</p>
                                </div>
                            </div>
                            <button 
                                onClick={() => setIsReviewing(false)} 
                                className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition">
                                <Icon name="x" size={18} />
                            </button>
                        </div>

                        <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-3.5 text-xs">
                            {/* Summary Badges */}
                            <div className="grid grid-cols-3 gap-2 text-center">
                                <div className="p-2.5 rounded-2xl bg-slate-50 border border-slate-100">
                                    <span className="text-[10px] text-slate-400 block font-medium">ตรวจนับทั้งหมด</span>
                                    <span className="text-sm font-bold text-slate-800">{items.length} รายการ</span>
                                </div>
                                <div className="p-2.5 rounded-2xl bg-emerald-50 border border-emerald-100">
                                    <span className="text-[10px] text-emerald-600 block font-medium">ยอดตรงกัน</span>
                                    <span className="text-sm font-bold text-emerald-700">{items.length - changedItems.length} รายการ</span>
                                </div>
                                <div className="p-2.5 rounded-2xl bg-amber-50 border border-amber-100">
                                    <span className="text-[10px] text-amber-600 block font-medium">มียอดต่าง</span>
                                    <span className="text-sm font-bold text-amber-700">{changedItems.length} รายการ</span>
                                </div>
                            </div>

                            <div className="p-3 rounded-2xl bg-slate-50 border border-slate-100 text-xs flex items-center justify-between">
                                <span className="text-slate-500 font-medium">ผู้ทำรายการตรวจนับ:</span>
                                <span className="font-bold text-slate-800 flex items-center gap-1.5">
                                    <Icon name="user" size={13} className="text-slate-400" />
                                    {currentUser?.name || 'ผู้ตรวจนับ'}
                                </span>
                            </div>

                            {/* Changed items list */}
                            <div>
                                <label className="block text-xs font-bold text-slate-700 mb-1.5">
                                    รายการที่จะถูกปรับยอด ({changedItems.length})
                                </label>
                                {changedItems.length === 0 ? (
                                    <div className="p-4 rounded-2xl bg-emerald-50 border border-emerald-100 text-center text-xs text-emerald-700 font-medium">
                                        ยอดตรวจนับตรงกับระบบทุกรายการ ไม่มียอดที่ต้องปรับ
                                    </div>
                                ) : (
                                    <div className="max-h-56 overflow-y-auto space-y-1.5 pr-1 divide-y divide-slate-100 border border-slate-100 rounded-2xl p-2.5 bg-slate-50/50">
                                        {changedItems.map(({ item, system, counted, diff }) => (
                                            <div key={item.id} className="pt-2 first:pt-0 flex items-center justify-between text-xs">
                                                <div className="min-w-0 pr-2">
                                                    <span className="text-[10px] font-mono text-slate-400 block">{item.code}</span>
                                                    <span className="font-semibold text-slate-800 truncate block">{item.name}</span>
                                                </div>
                                                <div className="text-right whitespace-nowrap">
                                                    <span className="text-slate-400 text-[11px]">{system} ➔ </span>
                                                    <span className="font-bold text-slate-800">{counted} {item.unit}</span>
                                                    <span className={`ml-1.5 px-1.5 py-0.2 rounded-md text-[10px] font-bold ${
                                                        diff < 0 ? 'bg-red-100 text-red-700' : 'bg-amber-100 text-amber-800'
                                                    }`}>
                                                        {diff < 0 ? `ขาด ${Math.abs(diff)}` : `เกิน +${diff}`}
                                                    </span>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>

                            <div className="p-3 bg-amber-50/70 border border-amber-200/60 rounded-2xl flex items-start gap-2">
                                <Icon name="alert-triangle" size={15} className="text-amber-600 shrink-0 mt-0.5" />
                                <p className="text-[11px] text-amber-800">
                                    เมื่อกดยืนยัน ยอดสต็อกในระบบจะถูกปรับให้ตรงกับยอดที่นับจริงทันที และจะบันทึกประวัติไว้ในระบบ
                                </p>
                            </div>
                        </div>

                        {/* Buttons (Fixed Bottom) */}
                        <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2.5 shrink-0">
                            <button
                                type="button"
                                onClick={() => setIsReviewing(false)}
                                disabled={submitting}
                                className="flex-1 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl font-bold text-xs sm:text-sm transition tap-bounce">
                                แก้ไข
                            </button>
                            <button
                                type="button"
                                onClick={handleConfirmReconcile}
                                disabled={submitting}
                                className="flex-1 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold text-xs sm:text-sm shadow-md shadow-emerald-600/20 transition flex items-center justify-center gap-1.5 tap-bounce">
                                {submitting ? 'กำลังบันทึก...' : 'ปรับยอด'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

// ==========================================
// 5. DASHBOARD VIEW
// ==========================================
function DashboardView({ stats, items, transactions, isAdmin, categorySafetyStocks = {}, onSelectFilter, onOpenScan, onOpenCheckout, onOpenAudit, onOpenCategorySafety, onExportExcel }) {
    const [chartAnimated, setChartAnimated] = useState(false);
    useEffect(() => {
        const timer = setTimeout(() => setChartAnimated(true), 80);
        return () => clearTimeout(timer);
    }, []);

    const criticalItems = items.filter(i => {
        const catThreshold = categorySafetyStocks[i.category];
        const reorder = (catThreshold !== undefined) ? Number(catThreshold) : (Number(i.reorder_point) || 5);
        return (Number(i.total_qty) || 0) <= reorder;
    });

    // Group critical items by category
    const criticalByCategory = useMemo(() => {
        const groups = {};
        criticalItems.forEach(item => {
            const cat = item.category?.trim() || 'ทั่วไป';
            if (!groups[cat]) groups[cat] = [];
            groups[cat].push(item);
        });
        return groups;
    }, [criticalItems]);

    // Top checked out items (รายการที่เบิกบ่อยสุด 5 อันดับแรก)
    const topCheckouts = useMemo(() => {
        const tally = {};
        (transactions || []).forEach(tx => {
            if (tx.type !== 'checkout') return;
            const key = tx.item_name || tx.code || 'ไม่ระบุ';
            if (!tally[key]) {
                tally[key] = {
                    name: key,
                    code: tx.code,
                    qty: 0,
                    count: 0,
                    unit: tx.unit || 'ชิ้น'
                };
            }
            tally[key].qty += Number(tx.qty) || 1;
            tally[key].count += 1;
        });
        return Object.values(tally)
            .sort((a, b) => b.qty - a.qty)
            .slice(0, 5);
    }, [transactions]);

    // Top shortage items (รายการที่ขาดมากที่สุด 5 อันดับแรก)
    const topShortages = useMemo(() => {
        return (items || [])
            .map(it => {
                const catThreshold = categorySafetyStocks[it.category];
                const reorder = (catThreshold !== undefined) ? Number(catThreshold) : (Number(it.reorder_point) || 5);
                const current = Number(it.total_qty) || 0;
                const deficit = Math.max(0, reorder - current);
                return {
                    id: it.id,
                    name: it.name,
                    code: it.code,
                    category: it.category,
                    unit: it.unit,
                    current,
                    reorder,
                    deficit
                };
            })
            .filter(it => it.deficit > 0)
            .sort((a, b) => b.deficit - a.deficit)
            .slice(0, 5);
    }, [items, categorySafetyStocks]);

    // Stock ratio calculations for Donut Chart
    const totalCount = stats.totalItems || 1;
    const outCount = stats.outOfStock || 0;
    const lowCount = stats.lowStock || 0;
    const normalCount = Math.max(0, totalCount - outCount - lowCount);

    const outPct = Math.round((outCount / totalCount) * 100);
    const lowPct = Math.round((lowCount / totalCount) * 100);
    const normalPct = Math.max(0, 100 - outPct - lowPct);

    // SVG Donut calculation (r=45, circumference ~ 282.74)
    const radius = 45;
    const circ = 2 * Math.PI * radius;
    const normalStroke = (normalCount / totalCount) * circ;
    const lowStroke = (lowCount / totalCount) * circ;
    const outStroke = (outCount / totalCount) * circ;
    const normalOffset = 0;
    const lowOffset = -normalStroke;
    const outOffset = -(normalStroke + lowStroke);

    return (
        <div className="space-y-4 sm:space-y-5">
            <div className="bg-gradient-to-r from-emerald-600 to-teal-700 rounded-3xl p-5 sm:p-6 text-white shadow-md relative overflow-hidden">
                <div className="relative z-10 max-w-xl">
                    <h2 className="text-xl sm:text-2xl font-bold tracking-tight">ระบบเบิก-จ่ายอุปกรณ์</h2>
                    
                    <div className="flex flex-wrap gap-2 mt-4">
                        <button 
                            onClick={onOpenScan}
                            className="flex items-center gap-1.5 px-3.5 py-2 bg-white text-emerald-800 rounded-xl font-bold text-xs shadow-sm hover:bg-emerald-50 transition tap-bounce">
                            <Icon name="qr-code" size={15} />
                            <span>เปิดกล้องสแกน</span>
                        </button>
                        <button 
                            onClick={onOpenCheckout}
                            className="flex items-center gap-1.5 px-3.5 py-2 bg-emerald-800/80 hover:bg-emerald-800 text-white rounded-xl font-semibold text-xs transition tap-bounce">
                            <Icon name="arrow-up-right" size={15} />
                            <span>เบิกของหน้างาน</span>
                        </button>
                    </div>
                </div>
            </div>

            {/* Stats Cards - Removed Total Value card, 3 balanced cards */}
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5 sm:gap-4">
                <div 
                    onClick={() => onSelectFilter('all')}
                    className="bg-white p-3.5 sm:p-5 rounded-2xl sm:rounded-3xl border border-slate-100 shadow-xs cursor-pointer hover:border-emerald-300 transition">
                    <span className="text-[11px] font-medium text-slate-500">อุปกรณ์ทั้งหมด</span>
                    <div className="text-xl sm:text-2xl font-bold text-slate-900 mt-1">{stats.totalItems}</div>
                    <div className="text-[10px] text-slate-400 mt-0.5">รายการในระบบ</div>
                </div>

                <div 
                    onClick={() => onSelectFilter('out')}
                    className="bg-white p-3.5 sm:p-5 rounded-2xl sm:rounded-3xl border border-red-100 shadow-xs cursor-pointer hover:border-red-300 transition bg-red-50/20">
                    <span className="text-[11px] font-bold text-red-600">หมดสต็อก (0)</span>
                    <div className="text-xl sm:text-2xl font-bold text-red-600 mt-1">{stats.outOfStock}</div>
                    <div className="text-[10px] text-red-500 mt-0.5">ต้องสั่งซื้อด่วน</div>
                </div>

                <div 
                    onClick={() => onSelectFilter('low')}
                    className="bg-white p-3.5 sm:p-5 rounded-2xl sm:rounded-3xl border border-amber-100 shadow-xs cursor-pointer hover:border-amber-300 transition bg-amber-50/20">
                    <span className="text-[11px] font-bold text-amber-600">ใกล้หมด</span>
                    <div className="text-xl sm:text-2xl font-bold text-amber-600 mt-1">{stats.lowStock}</div>
                    <div className="text-[10px] text-amber-500 mt-0.5">ต่ำกว่าเกณฑ์</div>
                </div>
            </div>

            {/* Visual Analytics Charts: Donut Chart & Top Checkouts / Deficit */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-3.5 sm:gap-4">
                {/* 1. กราฟวงกลม สัดส่วนสถานะสต็อก (Donut Chart) */}
                <div className="bg-white rounded-3xl p-4 sm:p-5 border border-slate-200/80 shadow-xs flex flex-col justify-between">
                    <div className="flex items-center justify-between pb-2 border-b border-slate-100">
                        <div className="flex items-center gap-2">
                            <div className="w-7 h-7 rounded-lg bg-emerald-50 text-emerald-600 flex items-center justify-center">
                                <Icon name="pie-chart" size={15} />
                            </div>
                            <h3 className="font-bold text-slate-900 text-xs sm:text-sm">สัดส่วนสถานะสต็อก</h3>
                        </div>
                        <span className="text-[11px] text-slate-400 font-medium">ภาพรวมคลัง</span>
                    </div>

                    <div className="py-3 flex flex-col sm:flex-row items-center justify-center gap-4">
                        {/* Pure SVG Donut Chart */}
                        <div className="relative w-36 h-36 shrink-0 flex items-center justify-center">
                            <svg className="w-full h-full -rotate-90" viewBox="0 0 120 120">
                                <circle
                                    cx="60"
                                    cy="60"
                                    r={radius}
                                    fill="none"
                                    stroke="#f1f5f9"
                                    strokeWidth="14"
                                />
                                {normalCount > 0 && (
                                    <circle
                                        cx="60"
                                        cy="60"
                                        r={radius}
                                        fill="none"
                                        stroke="#10b981"
                                        strokeWidth="14"
                                        strokeDasharray={chartAnimated ? `${normalStroke} ${circ}` : `0 ${circ}`}
                                        strokeDashoffset={normalOffset}
                                        strokeLinecap="round"
                                        className="transition-all duration-1000 ease-out"
                                    />
                                )}
                                {lowCount > 0 && (
                                    <circle
                                        cx="60"
                                        cy="60"
                                        r={radius}
                                        fill="none"
                                        stroke="#f59e0b"
                                        strokeWidth="14"
                                        strokeDasharray={chartAnimated ? `${lowStroke} ${circ}` : `0 ${circ}`}
                                        strokeDashoffset={lowOffset}
                                        strokeLinecap="round"
                                        className="transition-all duration-1000 ease-out"
                                    />
                                )}
                                {outCount > 0 && (
                                    <circle
                                        cx="60"
                                        cy="60"
                                        r={radius}
                                        fill="none"
                                        stroke="#ef4444"
                                        strokeWidth="14"
                                        strokeDasharray={chartAnimated ? `${outStroke} ${circ}` : `0 ${circ}`}
                                        strokeDashoffset={outOffset}
                                        strokeLinecap="round"
                                        className="transition-all duration-1000 ease-out"
                                    />
                                )}
                            </svg>
                            {/* Donut Center Label */}
                            <div className={`absolute inset-0 flex flex-col items-center justify-center text-center transition-all duration-700 ${chartAnimated ? 'opacity-100 scale-100' : 'opacity-0 scale-75'}`}>
                                <span className="text-xl sm:text-2xl font-black text-slate-900 leading-none">{stats.totalItems}</span>
                                <span className="text-[10px] text-slate-400 font-semibold mt-0.5">รายการ</span>
                            </div>
                        </div>

                        {/* Legend */}
                        <div className="w-full sm:w-auto flex-1 space-y-2 text-xs">
                            <div 
                                onClick={() => onSelectFilter('all')}
                                className="flex items-center justify-between p-2 rounded-xl bg-emerald-50/60 border border-emerald-100 hover:bg-emerald-100/50 cursor-pointer transition">
                                <div className="flex items-center gap-1.5 min-w-0">
                                    <span className="w-2.5 h-2.5 rounded-full bg-emerald-500 shrink-0"></span>
                                    <span className="font-semibold text-emerald-950 truncate">พร้อมใช้</span>
                                </div>
                                <span className="font-bold text-emerald-800 font-mono ml-2 shrink-0">{normalCount} ({normalPct}%)</span>
                            </div>
                            <div 
                                onClick={() => onSelectFilter('low')}
                                className="flex items-center justify-between p-2 rounded-xl bg-amber-50/60 border border-amber-100 hover:bg-amber-100/50 cursor-pointer transition">
                                <div className="flex items-center gap-1.5 min-w-0">
                                    <span className="w-2.5 h-2.5 rounded-full bg-amber-500 shrink-0"></span>
                                    <span className="font-semibold text-amber-950 truncate">ใกล้หมด</span>
                                </div>
                                <span className="font-bold text-amber-800 font-mono ml-2 shrink-0">{lowCount} ({lowPct}%)</span>
                            </div>
                            <div 
                                onClick={() => onSelectFilter('out')}
                                className="flex items-center justify-between p-2 rounded-xl bg-red-50/60 border border-red-100 hover:bg-red-100/50 cursor-pointer transition">
                                <div className="flex items-center gap-1.5 min-w-0">
                                    <span className="w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"></span>
                                    <span className="font-semibold text-red-950 truncate">หมดสต็อก</span>
                                </div>
                                <span className="font-bold text-red-800 font-mono ml-2 shrink-0">{outCount} ({outPct}%)</span>
                            </div>
                        </div>
                    </div>
                </div>

                {/* 2. รายการที่เบิกบ่อยสุด (Top Checkouts Bar Chart) */}
                <div className="bg-white rounded-3xl p-4 sm:p-5 border border-slate-200/80 shadow-xs flex flex-col justify-between">
                    <div className="flex items-center justify-between pb-2 border-b border-slate-100">
                        <div className="flex items-center gap-2">
                            <div className="w-7 h-7 rounded-lg bg-indigo-50 text-indigo-600 flex items-center justify-center">
                                <Icon name="trending-up" size={15} />
                            </div>
                            <h3 className="font-bold text-slate-900 text-xs sm:text-sm">รายการที่เบิกบ่อยสุด</h3>
                        </div>
                        <span className="text-[11px] text-slate-400 font-medium">5 อันดับแรก</span>
                    </div>

                    <div className="py-2 space-y-2.5">
                        {topCheckouts.length === 0 ? (
                            <div className="text-center py-8 text-slate-400 text-xs">
                                ยังไม่มีข้อมูลประวัติการเบิก
                            </div>
                        ) : (
                            (() => {
                                const maxQty = Math.max(...topCheckouts.map(t => t.qty), 1);
                                return topCheckouts.map((item, idx) => {
                                    const pct = Math.round((item.qty / maxQty) * 100);
                                    return (
                                        <div key={item.name + idx} className="space-y-1">
                                            <div className="flex items-center justify-between text-xs">
                                                <div className="flex items-center gap-1.5 min-w-0">
                                                    <span className={`w-4 h-4 rounded-full text-[10px] font-bold flex items-center justify-center shrink-0 ${
                                                        idx === 0 ? 'bg-amber-400 text-amber-950' :
                                                        idx === 1 ? 'bg-slate-300 text-slate-800' :
                                                        idx === 2 ? 'bg-amber-600/30 text-amber-900' :
                                                        'bg-slate-100 text-slate-500'
                                                    }`}>
                                                        {idx + 1}
                                                    </span>
                                                    <span className="font-medium text-slate-800 truncate" title={item.name}>
                                                        {item.name}
                                                    </span>
                                                </div>
                                                <span className="font-bold text-indigo-700 font-mono text-[11px] shrink-0 ml-2">
                                                    {item.qty} {item.unit}
                                                </span>
                                            </div>
                                            <div className="w-full bg-slate-100 rounded-full h-2 overflow-hidden">
                                                <div 
                                                    className="bg-indigo-600 h-full rounded-full transition-all duration-700 ease-out"
                                                    style={{ 
                                                        width: chartAnimated ? `${Math.max(8, pct)}%` : '0%',
                                                        transitionDelay: `${idx * 80}ms`
                                                    }}
                                                />
                                            </div>
                                        </div>
                                    );
                                });
                            })()
                        )}
                    </div>
                </div>

                {/* 3. รายการที่ขาดมากที่สุด (Most Out-of-Stock / Deficit) */}
                <div className="bg-white rounded-3xl p-4 sm:p-5 border border-slate-200/80 shadow-xs flex flex-col justify-between">
                    <div className="flex items-center justify-between pb-2 border-b border-slate-100">
                        <div className="flex items-center gap-2">
                            <div className="w-7 h-7 rounded-lg bg-red-50 text-red-600 flex items-center justify-center">
                                <Icon name="alert-octagon" size={15} />
                            </div>
                            <h3 className="font-bold text-slate-900 text-xs sm:text-sm">รายการที่ขาดมากที่สุด</h3>
                        </div>
                        <span className="text-[11px] text-red-500 font-bold">ต้องสั่งด่วน</span>
                    </div>

                    <div className="py-2 space-y-2.5">
                        {topShortages.length === 0 ? (
                            <div className="text-center py-8 text-emerald-600 font-medium text-xs flex flex-col items-center gap-1">
                                <Icon name="check-circle" size={20} className="text-emerald-500" />
                                <span>สต็อกทุกรายการอยู่ในเกณฑ์ปกติ</span>
                            </div>
                        ) : (
                            (() => {
                                const maxDeficit = Math.max(...topShortages.map(t => t.deficit), 1);
                                return topShortages.map((item, idx) => {
                                    const pct = Math.round((item.deficit / maxDeficit) * 100);
                                    return (
                                        <div key={item.id || idx} className="space-y-1">
                                            <div className="flex items-center justify-between text-xs">
                                                <div className="flex items-center gap-1.5 min-w-0">
                                                    <span className="w-4 h-4 rounded-full bg-red-100 text-red-700 text-[10px] font-bold flex items-center justify-center shrink-0">
                                                        {idx + 1}
                                                    </span>
                                                    <span className="font-medium text-slate-800 truncate" title={item.name}>
                                                        {item.name}
                                                    </span>
                                                </div>
                                                <span className="font-bold text-red-600 font-mono text-[11px] shrink-0 ml-2">
                                                    ขาด {item.deficit} {item.unit}
                                                </span>
                                            </div>
                                            <div className="w-full bg-slate-100 rounded-full h-2 overflow-hidden">
                                                <div 
                                                    className="bg-red-500 h-full rounded-full transition-all duration-700 ease-out"
                                                    style={{ 
                                                        width: chartAnimated ? `${Math.max(8, pct)}%` : '0%',
                                                        transitionDelay: `${idx * 80}ms`
                                                    }}
                                                />
                                            </div>
                                        </div>
                                    );
                                });
                            })()
                        )}
                    </div>
                </div>
            </div>

            {/* Critical Reorder Items Grouped by Category */}
            {criticalItems.length > 0 && (
                <div className="bg-white rounded-3xl p-4 sm:p-5 border border-slate-200/80 shadow-xs space-y-4">
                    <div className="flex items-center justify-between pb-3 border-b border-slate-100">
                        <div>
                            <h3 className="font-bold text-slate-900 text-xs sm:text-sm flex items-center gap-2">
                                <span className="w-2.5 h-2.5 rounded-full bg-red-500 animate-pulse"></span>
                                รายการที่ต้องสั่งซื้อ
                            </h3>
                        </div>
                        <div className="flex items-center gap-2">
                            <button onClick={() => onSelectFilter('low')} className="text-xs font-bold text-emerald-600 hover:text-emerald-700">
                                ดูทั้งหมด ({criticalItems.length})
                            </button>
                        </div>
                    </div>

                    <div className="space-y-4">
                        {Object.entries(criticalByCategory).map(([catName, catItems]) => (
                            <div key={catName} className="space-y-2">
                                <div className="flex items-center gap-2">
                                    <span className="w-2 h-2 rounded-full bg-amber-500"></span>
                                    <span className="text-xs font-bold text-slate-700">หมวดหมู่: {catName}</span>
                                    <span className="text-[10px] px-2 py-0.2 rounded-full bg-red-50 text-red-600 font-bold border border-red-100">
                                        {catItems.length} รายการ
                                    </span>
                                </div>
                                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 sm:gap-2.5">
                                    {catItems.map(item => {
                                        const isOut = (Number(item.total_qty) || 0) <= 0;
                                        const curThreshold = (categorySafetyStocks && categorySafetyStocks[item.category] !== undefined)
                                            ? categorySafetyStocks[item.category]
                                            : (item.reorder_point || 5);
                                        return (
                                            <div key={item.id} className="p-3 rounded-2xl border border-slate-100 bg-slate-50/70 flex items-center justify-between hover:bg-slate-50 transition">
                                                <div className="min-w-0 pr-2">
                                                    <div className="flex items-center gap-1.5">
                                                        <span className="text-[10px] font-mono text-slate-400 font-bold">{item.code}</span>
                                                        <span className={`text-[9px] font-bold px-1.5 py-0.2 rounded-md ${isOut ? 'bg-red-100 text-red-700' : 'bg-amber-100 text-amber-800'}`}>
                                                            {isOut ? 'หมดสต็อก' : 'ใกล้หมด'}
                                                        </span>
                                                    </div>
                                                    <p className="font-bold text-xs text-slate-800 truncate mt-1">{item.name}</p>
                                                    <span className="text-[10px] text-slate-400">จุดสั่งซื้อ: {curThreshold} {item.unit}</span>
                                                </div>
                                                <div className="text-right whitespace-nowrap">
                                                    <span className={`font-bold text-sm sm:text-base ${isOut ? 'text-red-600' : 'text-amber-600'}`}>{item.total_qty}</span>
                                                    <span className="text-[10px] text-slate-500 ml-1">{item.unit}</span>
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
}

// ==========================================
// 6. HISTORY VIEW
// ==========================================
function HistoryView({ transactions = [], items = [], loading, onRefresh }) {
    const [searchQuery, setSearchQuery] = useState('');

    const itemCategoryMap = useMemo(() => {
        const map = {};
        (items || []).forEach(it => {
            if (it.code) map[it.code.toLowerCase()] = it.category;
            if (it.id) map[it.id] = it.category;
            if (it.name) map[it.name.toLowerCase()] = it.category;
        });
        return map;
    }, [items]);

    const filteredTransactions = useMemo(() => {
        return (transactions || []).filter(tx => {
            if (searchQuery) {
                const q = searchQuery.toLowerCase().trim();
                const cat = (tx.category || itemCategoryMap[tx.code?.toLowerCase()] || itemCategoryMap[tx.item_id] || itemCategoryMap[tx.item_name?.toLowerCase()] || '').toLowerCase();
                const matchName = tx.item_name?.toLowerCase().includes(q);
                const matchCode = tx.code?.toLowerCase().includes(q);
                const matchSite = tx.job_site?.toLowerCase().includes(q);
                const matchTech = tx.technician?.toLowerCase().includes(q);
                const matchCat = cat.includes(q);
                return matchName || matchCode || matchSite || matchTech || matchCat;
            }
            return true;
        });
    }, [transactions, searchQuery, itemCategoryMap]);

    // จัดกลุ่มประวัติการทำรายการตามหมวดหมู่
    const transactionsByCategory = useMemo(() => {
        const groups = {};
        (filteredTransactions || []).forEach(tx => {
            const cat = tx.category || itemCategoryMap[tx.code?.toLowerCase()] || itemCategoryMap[tx.item_id] || itemCategoryMap[tx.item_name?.toLowerCase()] || 'ทั่วไป';
            if (!groups[cat]) groups[cat] = [];
            groups[cat].push(tx);
        });
        return groups;
    }, [filteredTransactions, itemCategoryMap]);

    const categoryEntries = useMemo(() => Object.entries(transactionsByCategory), [transactionsByCategory]);

    return (
        <div className="space-y-3.5">
            {/* Header: Title "ประวัติ", search */}
            <div className="bg-white p-4 sm:p-5 rounded-3xl border border-slate-200/80 shadow-xs space-y-3">
                <div className="flex items-center justify-between">
                    <h2 className="font-bold text-slate-900 text-sm sm:text-base">ประวัติ</h2>
                    <span className="text-xs text-slate-500 font-medium">
                        พบ {filteredTransactions.length} รายการ ({categoryEntries.length} หมวดหมู่)
                    </span>
                </div>

                {/* Search Bar */}
                <div className="relative">
                    <Icon name="search" size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400" />
                    <input
                        type="text"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        placeholder="ค้นหาชื่ออุปกรณ์, รหัส, หมวดหมู่, หน้างาน, ผู้เบิก..."
                        className="w-full pl-9 pr-8 py-2.5 bg-slate-50 border border-slate-200 rounded-2xl text-xs sm:text-sm focus:outline-hidden"
                    />
                    {searchQuery && (
                        <button onClick={() => setSearchQuery('')} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                            <Icon name="x" size={14} />
                        </button>
                    )}
                </div>
            </div>

            {/* Transactions List Grouped by Category */}
            {filteredTransactions.length === 0 ? (
                <div className="bg-white rounded-3xl border border-slate-200/80 shadow-xs p-12 text-center text-slate-400 text-xs">
                    {transactions.length === 0 ? 'ยังไม่มีประวัติการทำรายการ' : 'ไม่พบรายการที่ตรงกับการค้นหา'}
                </div>
            ) : (
                <div className="space-y-4">
                    {categoryEntries.map(([catName, txList]) => (
                        <div key={catName} className="space-y-2">
                            {/* Category Section Header */}
                            <div className="flex items-center justify-between px-3.5 py-2 bg-slate-100/90 rounded-2xl border border-slate-200/70">
                                <div className="flex items-center gap-2">
                                    <span className="w-2.5 h-2.5 rounded-full bg-emerald-600"></span>
                                    <span className="font-bold text-slate-800 text-xs sm:text-sm">หมวดหมู่: {catName}</span>
                                </div>
                                <span className="text-[11px] font-bold px-2.5 py-0.5 rounded-full bg-white text-slate-700 border border-slate-200 shadow-2xs">
                                    {txList.length} รายการ
                                </span>
                            </div>

                            {/* Transactions within this category */}
                            <div className="bg-white rounded-2xl border border-slate-200/80 shadow-xs divide-y divide-slate-100 overflow-hidden">
                                {txList.map(tx => (
                                    <div key={tx.id} className="p-3 sm:p-4 flex items-start sm:items-center justify-between gap-3 text-xs hover:bg-slate-50/50 transition">
                                        <div className="flex items-start gap-2.5 min-w-0">
                                            <div className={`w-8 h-8 rounded-xl flex items-center justify-center shrink-0 mt-0.5 ${
                                                tx.type === 'checkout' ? 'bg-amber-100 text-amber-700' :
                                                tx.type === 'checkin' ? 'bg-emerald-100 text-emerald-700' :
                                                tx.type === 'convert' ? 'bg-blue-100 text-blue-700' : 'bg-purple-100 text-purple-700'
                                            }`}>
                                                <Icon name={tx.type === 'checkout' ? 'arrow-up-right' : tx.type === 'checkin' ? 'arrow-down-left' : 'refresh-cw'} size={15} />
                                            </div>
                                            <div className="min-w-0">
                                                <div className="flex items-center gap-1.5 flex-wrap">
                                                    <span className="font-mono text-[10px] text-slate-400 font-bold">{tx.code}</span>
                                                    <span className="font-semibold text-slate-800 text-xs sm:text-sm truncate">{tx.item_name}</span>
                                                </div>
                                                <p className="text-slate-500 mt-1 text-[11px] flex items-center gap-1 flex-wrap">
                                                    <Icon name="map-pin" size={11} className="text-slate-400 shrink-0" />
                                                    <span><b>{tx.job_site || 'คลัง'}</b> • {tx.reason} • โดย {tx.technician}</span>
                                                </p>
                                            </div>
                                        </div>
                                        <div className="text-right shrink-0">
                                            <span className={`text-xs sm:text-sm font-bold block ${tx.type === 'checkout' ? 'text-amber-600' : 'text-emerald-600'}`}>
                                                {tx.type === 'checkout' ? '-' : '+'}{tx.qty} {tx.unit}
                                            </span>
                                            <span className="text-[10px] text-slate-400">
                                                {new Date(tx.created_at).toLocaleString('th-TH', { dateStyle: 'short', timeStyle: 'short' })}
                                            </span>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}

// ==========================================
// 2.5 APPROVAL & REQUISITIONS VIEW (ระบบอนุมัติการเบิก / รายการขอเบิก)
// ==========================================
function ApprovalManagementView({
    requisitions = [],
    items = [],
    currentUser,
    userRole,
    onSuccess,
    showToast,
    openConfirm
}) {
    const [statusFilter, setStatusFilter] = useState('all'); // 'all', 'pending', 'approved', 'rejected'
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedTech, setSelectedTech] = useState('all');
    const [rejectTarget, setRejectTarget] = useState(null);
    const [rejectReason, setRejectReason] = useState('สต็อกไม่เพียงพอ');
    const [customRejectReason, setCustomRejectReason] = useState('');
    const [submitting, setSubmitting] = useState(false);

    const isTechOnly = userRole?.isTech && !userRole?.isAdmin && !userRole?.isAds;
    const currentUserName = (currentUser?.name || '').toLowerCase();
    const currentUsername = (currentUser?.username || '').toLowerCase();

    // กรองคำขอที่เกี่ยวข้องตามสิทธิ์ (ช่างเทคนิคเห็นเฉพาะของตัวเอง, Admin/ADS เห็นทั้งหมด)
    const scopedRequisitions = useMemo(() => {
        if (isTechOnly) {
            return requisitions.filter(r => {
                const tech = (r.technician || r.technician_name || '').toLowerCase().trim();
                const usr = (r.created_by || r.technician_username || '').toLowerCase().trim();
                const cName = currentUserName.trim();
                const cUser = currentUsername.trim();
                if (!cName && !cUser) return true;
                const matchName = cName && (tech === cName || tech.includes(cName) || cName.includes(tech));
                const matchUser = cUser && (usr === cUser || usr.includes(cUser) || cUser.includes(usr));
                return matchName || matchUser;
            });
        }
        return requisitions;
    }, [requisitions, isTechOnly, currentUserName, currentUsername]);

    // รายชื่อช่างทั้งหมดสำหรับตัวเลือก Filter (เฉพาะ Admin / ADS)
    const techOptions = useMemo(() => {
        const set = new Set();
        requisitions.forEach(r => {
            const tech = (r.technician || r.technician_name || '').trim();
            if (tech) set.add(tech);
        });
        return Array.from(set).sort();
    }, [requisitions]);

    // นับจำนวนแต่ละสถานะ
    const counts = useMemo(() => {
        let all = scopedRequisitions.length;
        let pending = 0;
        let approved = 0;
        let rejected = 0;

        scopedRequisitions.forEach(r => {
            if (r.status === 'pending') pending++;
            else if (r.status === 'approved') approved++;
            else if (r.status === 'rejected') rejected++;
        });

        return { all, pending, approved, rejected };
    }, [scopedRequisitions]);

    // รายการที่ผ่านการกรองและค้นหา
    const filteredList = useMemo(() => {
        return scopedRequisitions.filter(r => {
            if (statusFilter !== 'all' && r.status !== statusFilter) return false;

            if (!isTechOnly && selectedTech !== 'all') {
                const tech = r.technician || r.technician_name;
                if (tech !== selectedTech) return false;
            }

            if (searchQuery.trim()) {
                const q = searchQuery.toLowerCase().trim();
                const matchCode = (r.code || r.req_code || '').toLowerCase().includes(q);
                const matchItemCode = (r.item_code || '').toLowerCase().includes(q);
                const matchItemName = (r.item_name || '').toLowerCase().includes(q);
                const matchSite = (r.job_site || '').toLowerCase().includes(q);
                const matchTech = (r.technician || r.technician_name || '').toLowerCase().includes(q);
                const matchReason = (r.reason || '').toLowerCase().includes(q);
                if (!matchCode && !matchItemCode && !matchItemName && !matchSite && !matchTech && !matchReason) {
                    return false;
                }
            }

            return true;
        });
    }, [scopedRequisitions, statusFilter, selectedTech, searchQuery, isTechOnly]);

    // อนุมัติการเบิก (Admin Only)
    const handleApprove = (req) => {
        if (!userRole?.canApprove) {
            showToast("เฉพาะผู้ดูแลระบบ (Admin) เท่านั้นที่สามารถอนุมัติได้", "error");
            return;
        }

        const currentItem = items.find(i => i.id === req.item_id);
        const currentQty = Number(currentItem?.total_qty) || 0;

        openConfirm({
            title: `อนุมัติคำขอ ${req.code}`,
            message: `ยืนยันการอนุมัติเบิก "${req.item_name}" จำนวน ${req.qty} ${req.unit} ให้ช่าง "${req.technician}" ใช่หรือไม่?\n(ระบบจะตัดยอดสต็อกและส่งแจ้งเตือน Telegram ไปยังกลุ่มงานทันที)`,
            confirmText: 'อนุมัติ',
            onConfirm: async () => {
                setSubmitting(true);
                try {
                    const res = await StockApi.approveRequisition({
                        requisitionId: req.id,
                        approverName: currentUser?.name || 'Admin'
                    });
                    if (res && res.success) {
                        showToast(`อนุมัติคำขอ ${req.code} เรียบร้อยแล้ว! ตัดสต็อกสำเร็จ`);
                        if (onSuccess) onSuccess();
                    } else {
                        showToast(res?.error || "ไม่สามารถอนุมัติได้", "error");
                    }
                } catch (err) {
                    showToast(toFriendlyError(err), "error");
                } finally {
                    setSubmitting(false);
                }
            }
        });
    };

    // เปิด Modal ปฏิเสธคำขอ
    const openRejectModal = (req) => {
        setRejectTarget(req);
        setRejectReason('สต็อกไม่เพียงพอ');
        setCustomRejectReason('');
    };

    // ยืนยันปฏิเสธคำขอ (Admin Only)
    const handleConfirmReject = async (e) => {
        e.preventDefault();
        if (!rejectTarget) return;
        const finalReason = rejectReason === 'อื่นๆ' ? customRejectReason.trim() : rejectReason;
        if (!finalReason) {
            return showToast("กรุณาระบุเหตุผลการไม่อนุมัติ", "error");
        }

        setSubmitting(true);
        try {
            const res = await StockApi.rejectRequisition({
                requisitionId: rejectTarget.id,
                rejectReason: finalReason,
                rejectorName: currentUser?.name || 'Admin'
            });
            if (res && res.success) {
                showToast(`ปฏิเสธคำขอ ${rejectTarget.code} แล้ว`);
                setRejectTarget(null);
                if (onSuccess) onSuccess();
            } else {
                showToast(res?.error || "เกิดข้อผิดพลาด", "error");
            }
        } catch (err) {
            showToast(toFriendlyError(err), "error");
        } finally {
            setSubmitting(false);
        }
    };

    // ยกเลิกคำขอ (ช่างยกเลิกของตัวเอง หรือ Admin)
    const handleCancelRequisition = (req) => {
        openConfirm({
            title: `ยกเลิกคำขอ ${req.code}`,
            message: `ต้องการยกเลิกคำขอเบิก "${req.item_name}" ใช่หรือไม่?`,
            confirmText: 'ยืนยันยกเลิก',
            isDanger: true,
            onConfirm: async () => {
                setSubmitting(true);
                try {
                    const res = await StockApi.deleteRequisition(req.id);
                    if (res && res.success) {
                        showToast(`ยกเลิกคำขอ ${req.code} สำเร็จ`);
                        if (onSuccess) onSuccess();
                    } else {
                        showToast(res?.error || "เกิดข้อผิดพลาด", "error");
                    }
                } catch (err) {
                    showToast(toFriendlyError(err), "error");
                } finally {
                    setSubmitting(false);
                }
            }
        });
    };

    return (
        <div className="space-y-4">
            {/* Modern Saving & Loading Modal */}
            <ModernLoadingModal show={submitting} title="กำลังบันทึก..." />

            {/* Modal ระบุเหตุผลการไม่อนุมัติ */}
            {rejectTarget && (
                <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto animate-fade-in">
                    <div className="bg-white rounded-3xl max-w-md w-full shadow-2xl border border-slate-100 my-auto flex flex-col max-h-[calc(100dvh-2rem)] sm:max-h-[92vh] overflow-hidden modal-responsive-card">
                        <div className="px-5 py-3.5 sm:py-4 border-b border-slate-100 flex items-center justify-between shrink-0 bg-white">
                            <div className="flex items-center gap-2.5">
                                <div className="w-9 h-9 rounded-2xl bg-red-50 text-red-600 flex items-center justify-center shrink-0">
                                    <Icon name="x-circle" size={20} />
                                </div>
                                <div>
                                    <h3 className="font-bold text-slate-900 text-sm sm:text-base">ไม่อนุมัติคำขอเบิก</h3>
                                    <p className="text-[11px] text-slate-400">รหัส {rejectTarget.code}</p>
                                </div>
                            </div>
                            <button
                                type="button"
                                onClick={() => setRejectTarget(null)}
                                disabled={submitting}
                                className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition"
                            >
                                <Icon name="x" size={18} />
                            </button>
                        </div>

                        <form onSubmit={handleConfirmReject} className="flex flex-col h-full max-h-[inherit] overflow-hidden">
                            <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-3.5 text-xs">
                                <div className="p-3 bg-slate-50 rounded-2xl border border-slate-200">
                                    <div className="font-bold text-slate-900">{rejectTarget.item_name}</div>
                                    <div className="text-[11px] text-slate-500 mt-0.5">
                                        จำนวน {rejectTarget.qty} {rejectTarget.unit} • ช่าง: {rejectTarget.technician}
                                    </div>
                                </div>

                                <div>
                                    <label className="block font-bold text-slate-700 mb-1.5">เลือกเหตุผลที่ไม่อนุมัติ *</label>
                                    <select
                                        value={rejectReason}
                                        onChange={(e) => {
                                            setRejectReason(e.target.value);
                                            if (e.target.value !== 'อื่นๆ') setCustomRejectReason('');
                                        }}
                                        className="w-full bg-slate-50 border border-slate-200 rounded-2xl p-2.5 font-medium focus:outline-hidden focus:border-red-500"
                                    >
                                        <option value="สต็อกไม่เพียงพอ">สต็อกไม่เพียงพอ</option>
                                        <option value="ข้อมูลโครงการ/หน้างานไม่ถูกต้อง">ข้อมูลโครงการ/หน้างานไม่ถูกต้อง</option>
                                        <option value="อุปกรณ์ยังอยู่ระหว่างการตรวจนับ">อุปกรณ์ยังอยู่ระหว่างการตรวจนับ</option>
                                        <option value="ให้ใช้อุปกรณ์เก่าซ่อมแซมก่อน">ให้ใช้อุปกรณ์เก่าซ่อมแซมก่อน</option>
                                        <option value="อื่นๆ">อื่นๆ (พิมพ์ระบุเอง)</option>
                                    </select>
                                </div>

                                {rejectReason === 'อื่นๆ' && (
                                    <div>
                                        <label className="block font-bold text-slate-700 mb-1">ระบุเหตุผลเพิ่มเติม *</label>
                                        <textarea
                                            rows="2"
                                            required
                                            value={customRejectReason}
                                            onChange={(e) => setCustomRejectReason(e.target.value)}
                                            placeholder="พิมพ์เหตุผลที่ไม่อนุมัติ..."
                                            className="w-full bg-white border border-slate-200 rounded-2xl p-2.5 font-medium focus:outline-hidden focus:border-red-500"
                                        />
                                    </div>
                                )}
                            </div>

                            <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2.5 shrink-0">
                                <button
                                    type="button"
                                    onClick={() => setRejectTarget(null)}
                                    disabled={submitting}
                                    className="flex-1 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl font-bold transition text-xs sm:text-sm tap-bounce"
                                >
                                    ยกเลิก
                                </button>
                                <button
                                    type="submit"
                                    disabled={submitting}
                                    className="flex-1 py-2.5 bg-red-600 hover:bg-red-700 text-white rounded-xl font-bold transition shadow-md shadow-red-600/20 text-xs sm:text-sm tap-bounce"
                                >
                                    {submitting ? 'กำลังบันทึก...' : 'ยืนยันปฏิเสธ'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Top Bar Banner */}
            <div className="bg-white p-4 sm:p-5 rounded-3xl border border-slate-200/80 shadow-xs flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                <div className="flex items-center gap-3">
                    <div className={`w-11 h-11 rounded-2xl flex items-center justify-center shrink-0 ${
                        userRole?.isAdmin ? 'bg-amber-500/10 text-amber-600' : userRole?.isAds ? 'bg-blue-500/10 text-blue-600' : 'bg-emerald-500/10 text-emerald-600'
                    }`}>
                        <Icon name={userRole?.isAdmin ? "shield-check" : userRole?.isAds ? "file-text" : "clipboard-list"} size={22} />
                    </div>
                    <div>
                        <h2 className="text-base sm:text-lg font-bold text-slate-900 tracking-tight">
                            {userRole?.isAdmin ? 'อนุมัติ' : userRole?.isAds ? 'อุปกรณ์ที่เบิก' : 'อุปกรณ์ที่เบิก'}
                        </h2>
                        {!userRole?.isAdmin && (
                            <p className="text-xs text-slate-400 mt-0.5">
                                {userRole?.isAds
                                    ? 'ดูรายการขอเบิกของทุกคน จัดเรียงและกรองข้อมูลแยกตามช่างได้ชัดเจน'
                                    : 'ตรวจสอบสถานะคำขอเบิกของท่าน (ต้องรอ Admin อนุมัติก่อนนำของออก)'}
                            </p>
                        )}
                    </div>
                </div>

                {counts.pending > 0 && (
                    <div className="flex items-center gap-2 px-3.5 py-1.5 bg-amber-50 text-amber-800 border border-amber-200/80 rounded-2xl text-xs font-bold w-fit">
                        <span className="w-2 h-2 rounded-full bg-amber-500 animate-ping"></span>
                        <span>รออนุมัติ {counts.pending} รายการ</span>
                    </div>
                )}
            </div>

            {/* Filter Tabs & Search Controls */}
            <div className="space-y-2.5">
                {/* 1. Status Filter Pills */}
                <div className="flex items-center gap-2 overflow-x-auto no-scrollbar py-1">
                    <button
                        onClick={() => setStatusFilter('all')}
                        className={`shrink-0 whitespace-nowrap px-3.5 py-1.5 rounded-xl text-xs font-semibold transition ${
                            statusFilter === 'all'
                                ? 'bg-slate-800 text-white shadow-xs'
                                : 'bg-white text-slate-600 hover:bg-slate-100 border border-slate-200'
                        }`}
                    >
                        ทั้งหมด ({counts.all})
                    </button>
                    <button
                        onClick={() => setStatusFilter('pending')}
                        className={`shrink-0 whitespace-nowrap flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl text-xs font-semibold transition ${
                            statusFilter === 'pending'
                                ? 'bg-amber-600 text-white shadow-xs'
                                : 'bg-amber-50 text-amber-800 hover:bg-amber-100 border border-amber-200'
                        }`}
                    >
                        <Icon name="clock" size={13} />
                        <span>รออนุมัติ ({counts.pending})</span>
                    </button>
                    <button
                        onClick={() => setStatusFilter('approved')}
                        className={`shrink-0 whitespace-nowrap flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl text-xs font-semibold transition ${
                            statusFilter === 'approved'
                                ? 'bg-emerald-600 text-white shadow-xs'
                                : 'bg-emerald-50 text-emerald-800 hover:bg-emerald-100 border border-emerald-200'
                        }`}
                    >
                        <Icon name="check-circle" size={13} />
                        <span>อนุมัติ ({counts.approved})</span>
                    </button>
                    <button
                        onClick={() => setStatusFilter('rejected')}
                        className={`shrink-0 whitespace-nowrap flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl text-xs font-semibold transition ${
                            statusFilter === 'rejected'
                                ? 'bg-red-600 text-white shadow-xs'
                                : 'bg-red-50 text-red-800 hover:bg-red-100 border border-red-200'
                        }`}
                    >
                        <Icon name="x-circle" size={13} />
                        <span>ไม่อนุมัติ ({counts.rejected})</span>
                    </button>
                </div>

                {/* 2. Search Input & Technician Dropdown Filter */}
                <div className="flex flex-col sm:flex-row gap-2">
                    <div className="relative flex-1">
                        <Icon name="search" size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400" />
                        <input
                            type="text"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            placeholder="ค้นหา..."
                            className="w-full pl-9 pr-8 py-2.5 bg-white border border-slate-200/90 rounded-2xl text-xs sm:text-sm focus:outline-hidden focus:border-emerald-500 shadow-xs"
                        />
                        {searchQuery && (
                            <button onClick={() => setSearchQuery('')} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                                <Icon name="x" size={14} />
                            </button>
                        )}
                    </div>

                    {!isTechOnly && (
                        <div className="sm:w-56 shrink-0">
                            <select
                                value={selectedTech}
                                onChange={(e) => setSelectedTech(e.target.value)}
                                className="w-full bg-white border border-slate-200/90 rounded-2xl px-3.5 py-2.5 text-xs font-medium text-slate-700 focus:outline-hidden focus:border-emerald-500 shadow-xs"
                            >
                                <option value="all">ช่างผู้ขอทุกคน ({techOptions.length})</option>
                                {techOptions.map(t => (
                                    <option key={t} value={t}>{t}</option>
                                ))}
                            </select>
                        </div>
                    )}
                </div>
            </div>

            {/* List of Requisition Cards */}
            {filteredList.length === 0 ? (
                <div className="text-center py-16 bg-white rounded-3xl border border-slate-200 shadow-xs">
                    <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center text-slate-400 mx-auto mb-3">
                        <Icon name="clipboard-check" size={28} />
                    </div>
                    <p className="font-bold text-slate-700 text-sm">ไม่พบรายการคำขอเบิก</p>
                    <p className="text-xs text-slate-400 mt-1">ไม่มีคำขอเบิกในหมวดหมู่นี้ หรือลองเปลี่ยนคำค้นหา</p>
                </div>
            ) : (
                <div className="space-y-3">
                    {filteredList.map(req => {
                        const currentItem = items.find(i => i.id === req.item_id);
                        const warehouseStock = Number(currentItem?.total_qty) || 0;
                        const isPending = req.status === 'pending';
                        const isApproved = req.status === 'approved';
                        const isRejected = req.status === 'rejected';
                        const batchCode = req.batch_code || (req.note && req.note.match(/\[ชุด:\s*([A-Za-z0-9-]+)\]/)?.[1]);

                        const itemImage = req.item_image || currentItem?.image_url;

                        return (
                            <div
                                key={req.id}
                                className={`bg-white rounded-3xl p-4 sm:p-5 border transition-all duration-200 shadow-xs flex flex-col justify-between gap-3.5 ${
                                    isPending ? 'border-amber-200/90 bg-amber-50/10' :
                                    isApproved ? 'border-emerald-200/90 bg-emerald-50/10' :
                                    'border-red-200/80 bg-red-50/10'
                                }`}
                            >
                                {/* 1. Header Bar: Code + Batch + Status + Date */}
                                <div className="flex items-center justify-between gap-2 pb-3 border-b border-slate-100 flex-wrap">
                                    <div className="flex items-center gap-2 flex-wrap">
                                        <span className="font-mono text-xs font-bold bg-slate-100 text-slate-700 px-2.5 py-1 rounded-xl border border-slate-200 shadow-2xs">
                                            {req.code || req.req_code}
                                        </span>
                                        {batchCode && (
                                            <span className="font-mono text-[11px] font-bold bg-indigo-50 text-indigo-700 border border-indigo-200/80 px-2 py-0.5 rounded-lg flex items-center gap-1 shadow-2xs">
                                                <Icon name="clipboard-list" size={11} />
                                                <span>ชุด: {batchCode}</span>
                                            </span>
                                        )}
                                        <span className={`text-[11px] font-bold px-2.5 py-0.5 rounded-full flex items-center gap-1.5 border shadow-2xs ${
                                            isPending ? 'bg-amber-100 text-amber-800 border-amber-300' :
                                            isApproved ? 'bg-emerald-100 text-emerald-800 border-emerald-300' :
                                            'bg-red-100 text-red-800 border-red-300'
                                        }`}>
                                            {isPending ? (
                                                <span className="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse"></span>
                                            ) : (
                                                <Icon name={isApproved ? "check-circle" : "x-circle"} size={12} />
                                            )}
                                            <span>{isPending ? 'รออนุมัติ' : isApproved ? 'อนุมัติ' : 'ไม่อนุมัติ'}</span>
                                        </span>
                                    </div>

                                    <div className="text-xs text-slate-400 flex items-center gap-1 font-medium">
                                        <Icon name="clock" size={12} className="text-slate-400" />
                                        <span>{new Date(req.created_at).toLocaleString('th-TH', { dateStyle: 'short', timeStyle: 'short' })}</span>
                                    </div>
                                </div>

                                {/* 2. Main Content: Thumbnail + Equipment Details + Stock Comparison */}
                                <div className="flex items-start gap-3 sm:gap-4">
                                    {/* Thumbnail Image */}
                                    <div className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl overflow-hidden bg-slate-100 border border-slate-200 shrink-0 flex items-center justify-center relative shadow-2xs">
                                        {itemImage ? (
                                            <img src={itemImage} alt={req.item_name} className="w-full h-full object-cover" />
                                        ) : (
                                            <Icon name="package" size={28} className="text-slate-300" />
                                        )}
                                    </div>

                                    {/* Details */}
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-2 flex-wrap">
                                            <span className="font-mono text-xs font-bold text-slate-500">{req.item_code}</span>
                                            <span className="text-[11px] text-slate-600 bg-slate-100 px-2 py-0.5 rounded-md font-medium">
                                                สภาพ: {req.variant_name || 'ของใหม่'}
                                            </span>
                                        </div>

                                        <h4 className="font-bold text-slate-900 text-sm sm:text-base leading-snug mt-0.5 line-clamp-2" title={req.item_name}>
                                            {req.item_name}
                                        </h4>

                                        {/* Stock Comparison Callout */}
                                        <div className="mt-2 p-2 sm:p-2.5 bg-slate-50/90 rounded-xl border border-slate-200/80 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs">
                                            <div>
                                                <span className="text-slate-500">จำนวน: </span>
                                                <b className="text-emerald-700 font-bold text-sm sm:text-base font-mono">{req.qty}</b>{' '}
                                                <span className="text-slate-500">{req.unit}</span>
                                            </div>
                                            <div>
                                                <span className="text-slate-500">คงเหลือ: </span>
                                                <b className="text-slate-700 font-semibold font-mono">{warehouseStock}</b>{' '}
                                                <span className="text-slate-500">{req.unit}</span>
                                            </div>
                                            {req.qty > warehouseStock && (
                                                <span className="bg-red-100 text-red-700 px-2 py-0.5 rounded-md font-bold text-[11px] flex items-center gap-1 border border-red-200">
                                                    <Icon name="alert-triangle" size={12} />
                                                    <span>สต็อกไม่พอ</span>
                                                </span>
                                            )}
                                        </div>

                                        {/* Context Badges (Site, Reason, Tech, Note) */}
                                        <div className="flex items-center gap-2 mt-2.5 flex-wrap text-xs">
                                            <span className="inline-flex items-center gap-1 text-slate-600 bg-white px-2.5 py-1 rounded-xl border border-slate-200/80 shadow-2xs font-medium">
                                                <Icon name="map-pin" size={12} className="text-slate-400 shrink-0" />
                                                <span>{req.job_site || 'ไม่ระบุหน้างาน'}</span>
                                            </span>
                                            <span className="inline-flex items-center gap-1 text-slate-600 bg-white px-2.5 py-1 rounded-xl border border-slate-200/80 shadow-2xs font-medium">
                                                <Icon name="file-text" size={12} className="text-slate-400 shrink-0" />
                                                <span>{req.reason}</span>
                                            </span>
                                            <span className="inline-flex items-center gap-1 text-slate-600 bg-white px-2.5 py-1 rounded-xl border border-slate-200/80 shadow-2xs font-medium">
                                                <Icon name="user" size={12} className="text-slate-400 shrink-0" />
                                                <span>{req.technician || req.technician_name || 'ช่างเทคนิค'}</span>
                                            </span>
                                            {req.note && (
                                                <span className="inline-flex items-center gap-1 text-slate-500 bg-white px-2.5 py-1 rounded-xl border border-slate-200/80 shadow-2xs" title={req.note}>
                                                    <Icon name="message-square" size={12} className="text-slate-400 shrink-0" />
                                                    <span className="truncate max-w-[200px]">{req.note}</span>
                                                </span>
                                            )}
                                        </div>
                                    </div>
                                </div>

                                {/* 3. Footer Bar: Status Info on Left, Action Buttons on Right */}
                                <div className="pt-3 border-t border-slate-100 flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3">
                                    {/* Left: Status Details */}
                                    <div className="text-xs">
                                        {isApproved && (
                                            <div className="text-emerald-800 bg-emerald-50 px-3 py-1.5 rounded-xl border border-emerald-200/60 flex items-center gap-1.5">
                                                <Icon name="check-circle" size={14} className="text-emerald-600 shrink-0" />
                                                <span>อนุมัติ: <b>{req.approved_by || 'ผู้อนุมัติ'}</b> {req.approved_at ? `เมื่อ ${new Date(req.approved_at).toLocaleString('th-TH', { dateStyle: 'short', timeStyle: 'short' })}` : ''}</span>
                                            </div>
                                        )}

                                        {isRejected && (
                                            <div className="text-red-800 bg-red-50 px-3 py-1.5 rounded-xl border border-red-200/60 flex flex-col sm:flex-row items-start sm:items-center gap-1 sm:gap-2">
                                                <span className="flex items-center gap-1 font-bold shrink-0">
                                                    <Icon name="x-circle" size={14} className="text-red-600" />
                                                    <span>ไม่อนุมัติโดย: {req.rejected_by || 'ผู้อนุมัติ'}</span>
                                                </span>
                                                <span className="text-red-700">เหตุผล: <b>{req.reject_reason || 'ไม่มีการระบุ'}</b></span>
                                            </div>
                                        )}

                                        {isPending && isTechOnly && (
                                            <div className="text-amber-800 bg-amber-50 px-3 py-1.5 rounded-xl border border-amber-200/60 flex items-center gap-1.5">
                                                <Icon name="clock" size={14} className="text-amber-600 shrink-0" />
                                                <span>คำขอนี้กำลังรอการอนุมัติ กรุณาอย่านำของออกจากคลังก่อนได้รับอนุมัติ</span>
                                            </div>
                                        )}

                                        {isPending && userRole?.canApprove && (
                                            <div className="text-slate-400 flex items-center gap-1.5 hidden sm:flex">
                                                <Icon name="shield-check" size={14} className="text-slate-400" />
                                                <span>ตรวจสอบข้อมูลและสต็อกคงเหลือก่อนกดยืนยัน</span>
                                            </div>
                                        )}
                                    </div>

                                    {/* Right: Action Buttons */}
                                    <div className="flex items-center gap-2 justify-end">
                                        {isPending && userRole?.canApprove && (
                                            <>
                                                <button
                                                    onClick={() => openRejectModal(req)}
                                                    disabled={submitting}
                                                    className="flex-1 sm:flex-none px-4 py-2 bg-red-50 hover:bg-red-100 text-red-700 rounded-xl text-xs font-bold flex items-center justify-center gap-1.5 transition tap-bounce"
                                                >
                                                    <Icon name="x" size={14} />
                                                    <span>ปฏิเสธ</span>
                                                </button>
                                                <button
                                                    onClick={() => handleApprove(req)}
                                                    disabled={submitting}
                                                    className="flex-1 sm:flex-none px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-xs font-bold flex items-center justify-center gap-1.5 shadow-sm shadow-emerald-600/20 transition tap-bounce active:scale-[0.98]"
                                                >
                                                    <Icon name="check" size={14} />
                                                    <span>อนุมัติ</span>
                                                </button>
                                            </>
                                        )}

                                        {isPending && userRole?.isAds && (
                                            <span className="text-[11px] font-semibold text-slate-400 bg-slate-100 px-3 py-1.5 rounded-xl">
                                                รอผู้อนุมัติ
                                            </span>
                                        )}

                                        {isPending && isTechOnly && (
                                            <button
                                                onClick={() => handleCancelRequisition(req)}
                                                disabled={submitting}
                                                className="px-3.5 py-1.5 bg-slate-100 hover:bg-red-50 hover:text-red-700 text-slate-600 rounded-xl text-xs font-semibold transition"
                                            >
                                                ยกเลิกคำขอ
                                            </button>
                                        )}
                                    </div>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}
        </div>
    );
}

// ==========================================
// MODALS
// ==========================================
function QuickCheckoutModal({ item, projects, currentUser, onAddToCart, onClose, onSuccess, showToast }) {
    const [variantId, setVariantId] = useState(item.variants?.[0]?.id || '');
    const [qty, setQty] = useState(1);
    const [project, setProject] = useState('โครงการพราว น้ำพอง');
    const [reason, setReason] = useState('ติดตั้งใหม่');
    const [customReason, setCustomReason] = useState('');
    const [submitting, setSubmitting] = useState(false);
    const [isReviewing, setIsReviewing] = useState(false);

    const selectedVariant = item.variants?.find(v => v.id === variantId) || item.variants?.[0];

    const handleStartReview = (e) => {
        e.preventDefault();
        if (Number(qty) <= 0) return showToast("กรุณาระบุจำนวนที่มากกว่า 0", "error");
        if (reason === 'อื่นๆ' && !customReason.trim()) {
            return showToast("กรุณาระบุเหตุผลการเบิกเพิ่มเติม", "error");
        }
        setIsReviewing(true);
    };

    const handleConfirmSubmit = async () => {
        const finalReason = reason === 'อื่นๆ' ? (customReason.trim() || 'อื่นๆ') : reason;
        setSubmitting(true);
        try {
            await StockApi.checkoutItem({
                itemId: item.id,
                variantId,
                qty: Number(qty),
                jobSite: project,
                reason: finalReason,
                technician: currentUser?.name || 'ช่างเทคนิค'
            });
            setIsReviewing(false);
            onSuccess();
        } catch (err) {
            showToast(toFriendlyError(err), "error");
        } finally {
            setSubmitting(false); // การันตี finally
        }
    };

    return (
        <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto animate-fade-in">
            {/* Modern Saving & Loading Modal */}
            <ModernLoadingModal show={submitting} title="กำลังบันทึก..." />

            <div className="bg-white rounded-3xl max-w-md w-full shadow-2xl border border-slate-100 my-auto flex flex-col max-h-[calc(100dvh-2rem)] sm:max-h-[92vh] overflow-hidden modal-responsive-card">
                {/* Header (Fixed Top) */}
                <div className="px-5 py-3.5 sm:py-4 border-b border-slate-100 flex items-center justify-between shrink-0 bg-white">
                    <h3 className="font-bold text-slate-900 text-sm sm:text-base">เบิกด่วน: {item.name}</h3>
                    <button onClick={onClose} className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition"><Icon name="x" size={18} /></button>
                </div>

                {!isReviewing ? (
                    <form onSubmit={handleStartReview} className="flex flex-col h-full max-h-[inherit] overflow-hidden">
                        <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-3.5 text-xs">
                            {item.variants && item.variants.length > 0 && (
                                <div>
                                    <label className="block font-bold text-slate-700 mb-1">เลือกสภาพ</label>
                                    <select
                                        value={variantId}
                                        onChange={(e) => setVariantId(e.target.value)}
                                        className="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5">
                                        {item.variants.map(v => (
                                            <option key={v.id} value={v.id}>{v.name} (คงเหลือ: {v.qty} {v.unit})</option>
                                        ))}
                                    </select>
                                </div>
                            )}

                            <div>
                                <label className="block font-bold text-slate-700 mb-1">จำนวนที่เบิก ({item.unit})</label>
                                <input
                                    type="number"
                                    min="1"
                                    value={qty}
                                    onChange={(e) => setQty(e.target.value)}
                                    className="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 font-bold text-sm"
                                />
                            </div>

                            <div>
                                <label className="block font-bold text-slate-700 mb-1">โครงการ / หน้างาน</label>
                                <select
                                    value={project}
                                    onChange={(e) => setProject(e.target.value)}
                                    className="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5">
                                    {projects.map(p => <option key={p.id} value={p.name}>{p.name}</option>)}
                                </select>
                            </div>

                            <div>
                                <label className="block font-bold text-slate-700 mb-1">เหตุผล</label>
                                <select
                                    value={reason}
                                    onChange={(e) => {
                                        setReason(e.target.value);
                                        if (e.target.value !== 'อื่นๆ') setCustomReason('');
                                    }}
                                    className="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5">
                                    <option value="ติดตั้งใหม่">ติดตั้งใหม่</option>
                                    <option value="ซ่อมแซม/เปลี่ยนอะไหล่">ซ่อมแซม / เปลี่ยนอะไหล่</option>
                                    <option value="สำรองติดรถช่าง">สำรองติดรถช่าง</option>
                                    <option value="ส่งมอบงานทดสอบ">ส่งมอบงานทดสอบ</option>
                                    <option value="อื่นๆ">อื่นๆ</option>
                                </select>
                                {reason === 'อื่นๆ' && (
                                    <input
                                        type="text"
                                        required
                                        value={customReason}
                                        onChange={(e) => setCustomReason(e.target.value)}
                                        placeholder="พิมพ์ระบุเหตุผลเพิ่มเติม..."
                                        className="w-full bg-white border border-slate-200 rounded-xl p-2.5 mt-2 text-xs font-semibold focus:border-emerald-500 focus:outline-hidden"
                                    />
                                )}
                            </div>

                            <div>
                                <label className="block font-bold text-slate-700 mb-1">ผู้ทำรายการ</label>
                                <div className="relative">
                                    <input
                                        type="text"
                                        readOnly
                                        disabled
                                        value={currentUser?.name || 'ช่างเทคนิค'}
                                        className="w-full bg-slate-100 text-slate-700 font-bold border border-slate-200 rounded-xl p-2.5 cursor-not-allowed select-none"
                                    />
                                </div>
                            </div>
                        </div>

                        {/* Footer (Fixed Bottom) */}
                        <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2 shrink-0">
                            <button type="button" onClick={onClose} className="px-3.5 py-2.5 bg-slate-100 text-slate-600 hover:bg-slate-200 rounded-xl font-bold transition text-xs sm:text-sm tap-bounce">
                                ยกเลิก
                            </button>
                            {onAddToCart && (
                                <button
                                    type="button"
                                    onClick={() => {
                                        if (Number(qty) <= 0) return showToast("กรุณาระบุจำนวนที่มากกว่า 0", "error");
                                        const maxStock = selectedVariant ? Number(selectedVariant.qty || 0) : Number(item.total_qty || 0);
                                        if (Number(qty) > maxStock) return showToast(`ยอดคงเหลือไม่พอ (มีเพียง ${maxStock} ${item.unit})`, "warning");
                                        onAddToCart(item, selectedVariant, Number(qty));
                                        showToast(`เพิ่ม "${item.name}" (${qty} ${item.unit}) ลงรายการเบิกแล้ว`);
                                        onClose();
                                    }}
                                    className="flex-1 py-2.5 bg-emerald-50 hover:bg-emerald-100 text-emerald-800 border border-emerald-300 rounded-xl font-bold transition tap-bounce text-xs sm:text-sm flex items-center justify-center gap-1.5 shadow-xs"
                                >
                                    <span>+ เพิ่มรายการ</span>
                                </button>
                            )}
                            <button type="submit" className="flex-1 py-2.5 bg-emerald-600 text-white rounded-xl font-bold hover:bg-emerald-700 shadow-sm shadow-emerald-600/20 transition tap-bounce text-xs sm:text-sm">
                                เบิกของ
                            </button>
                        </div>
                    </form>
                ) : (
                    <div className="flex flex-col h-full max-h-[inherit] overflow-hidden">
                        <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-3 text-xs">
                            <div className="p-3.5 bg-slate-50 rounded-2xl border border-slate-100 space-y-2">
                                <div className="flex justify-between items-start">
                                    <span className="text-slate-400 font-medium">อุปกรณ์:</span>
                                    <span className="font-bold text-slate-800 text-right">{item.name} ({item.code})</span>
                                </div>
                                {selectedVariant && (
                                    <div className="flex justify-between">
                                        <span className="text-slate-400 font-medium">สภาพ:</span>
                                        <span className="font-bold text-slate-700">{selectedVariant.name}</span>
                                    </div>
                                )}
                                <div className="flex justify-between">
                                    <span className="text-slate-400 font-medium">จำนวน:</span>
                                    <span className="font-bold text-emerald-700 text-sm">{qty} {item.unit}</span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-slate-400 font-medium">โครงการ / หน้างาน:</span>
                                    <span className="font-bold text-slate-800 text-right">{project}</span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-slate-400 font-medium">เหตุผล:</span>
                                    <span className="font-bold text-slate-800 text-right">{reason === 'อื่นๆ' ? customReason : reason}</span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-slate-400 font-medium">ผู้ทำรายการ:</span>
                                    <span className="font-bold text-slate-800">{currentUser?.name || 'ช่างเทคนิค'}</span>
                                </div>
                            </div>
                        </div>

                        {/* Footer (Fixed Bottom) */}
                        <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2.5 shrink-0">
                            <button
                                type="button"
                                onClick={() => setIsReviewing(false)}
                                disabled={submitting}
                                className="flex-1 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl font-bold text-xs sm:text-sm transition tap-bounce">
                                แก้ไข
                            </button>
                            <button
                                type="button"
                                onClick={handleConfirmSubmit}
                                disabled={submitting}
                                className="flex-1 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold text-xs sm:text-sm shadow-md shadow-emerald-600/20 transition flex items-center justify-center gap-1.5 tap-bounce">
                                {submitting ? 'กำลังบันทึก...' : 'ยืนยัน'}
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}

function ConvertVariantModal({ item, currentUser, onClose, onSuccess, showToast }) {
    const rawVariant = item.variants?.find(v => v.condition_type === 'raw_box') || item.variants?.[0];
    const readyVariant = item.variants?.find(v => v.condition_type === 'ready_to_use') || item.variants?.[1];

    const [fromQty, setFromQty] = useState(1);
    const [toQty, setToQty] = useState(50);
    const [submitting, setSubmitting] = useState(false);
    const [isReviewing, setIsReviewing] = useState(false);

    const handleStartReview = (e) => {
        e.preventDefault();
        if (!rawVariant || !readyVariant) return;
        if (Number(fromQty) <= 0 || Number(toQty) <= 0) {
            return showToast("กรุณาระบุจำนวนที่มากกว่า 0", "error");
        }
        if (Number(fromQty) > (rawVariant.qty || 0)) {
            return showToast(`สต็อกต้นทางไม่พอ (มีเพียง ${rawVariant.qty} ${rawVariant.unit})`, "warning");
        }
        setIsReviewing(true);
    };

    const handleConfirmConvert = async () => {
        if (!rawVariant || !readyVariant) return;
        setSubmitting(true);
        try {
            await StockApi.convertVariant({
                itemId: item.id,
                fromVariantId: rawVariant.id,
                toVariantId: readyVariant.id,
                fromQty: Number(fromQty),
                toQty: Number(toQty),
                technician: currentUser.name
            });
            setIsReviewing(false);
            onSuccess();
        } catch (err) {
            showToast(toFriendlyError(err), "error");
        } finally {
            setSubmitting(false); // การันตี finally
        }
    };

    return (
        <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto animate-fade-in">
            {/* Modern Saving & Loading Modal */}
            <ModernLoadingModal show={submitting} title="กำลังบันทึก..." />

            <div className="bg-white rounded-3xl max-w-md w-full shadow-2xl border border-slate-100 my-auto flex flex-col max-h-[calc(100dvh-2rem)] sm:max-h-[92vh] overflow-hidden modal-responsive-card">
                {/* Header (Fixed Top) */}
                <div className="px-5 py-3.5 sm:py-4 border-b border-slate-100 flex items-center justify-between shrink-0 bg-white">
                    <div className="flex items-center gap-2">
                        <Icon name="refresh-cw" size={17} className="text-blue-600" />
                        <h3 className="font-bold text-slate-900 text-sm sm:text-base">แปรรูปสินค้า: {item.name}</h3>
                    </div>
                    <button onClick={onClose} className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition"><Icon name="x" size={18} /></button>
                </div>

                {!isReviewing ? (
                    <form onSubmit={handleStartReview} className="flex flex-col h-full max-h-[inherit] overflow-hidden">
                        <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-3.5 text-xs">
                            <div className="p-3 bg-blue-50/60 rounded-2xl border border-blue-100 flex items-center justify-between">
                                <div>
                                    <span className="text-slate-500 block text-[10px]">ลดสต็อกต้นทาง</span>
                                    <span className="font-bold text-slate-800">{rawVariant?.name}</span>
                                    <span className="text-[11px] text-slate-400 block">(มีอยู่: {rawVariant?.qty} {rawVariant?.unit})</span>
                                </div>
                                <input
                                    type="number"
                                    min="1"
                                    max={rawVariant?.qty || 1}
                                    value={fromQty}
                                    onChange={(e) => setFromQty(e.target.value)}
                                    className="w-20 text-center bg-white border border-blue-200 rounded-xl p-2 font-bold"
                                />
                            </div>

                            <div className="flex justify-center text-slate-300">
                                <Icon name="arrow-down" size={18} />
                            </div>

                            <div className="p-3 bg-emerald-50/60 rounded-2xl border border-emerald-100 flex items-center justify-between">
                                <div>
                                    <span className="text-slate-500 block text-[10px]">เพิ่มสต็อกปลายทาง</span>
                                    <span className="font-bold text-slate-800">{readyVariant?.name}</span>
                                    <span className="text-[11px] text-slate-400 block">(มีอยู่เดิม: {readyVariant?.qty} {readyVariant?.unit})</span>
                                </div>
                                <input
                                    type="number"
                                    min="1"
                                    value={toQty}
                                    onChange={(e) => setToQty(e.target.value)}
                                    className="w-20 text-center bg-white border border-emerald-200 rounded-xl p-2 font-bold"
                                />
                            </div>
                        </div>

                        {/* Footer (Fixed Bottom) */}
                        <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2 shrink-0">
                            <button type="button" onClick={onClose} className="flex-1 py-2.5 bg-slate-100 text-slate-600 hover:bg-slate-200 rounded-xl font-bold transition text-xs sm:text-sm tap-bounce">
                                ยกเลิก
                            </button>
                            <button type="submit" disabled={submitting} className="flex-1 py-2.5 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-700 shadow-sm shadow-blue-600/20 transition tap-bounce text-xs sm:text-sm">
                                แปรรูป
                            </button>
                        </div>
                    </form>
                ) : (
                    <div className="flex flex-col h-full max-h-[inherit] overflow-hidden">
                        <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-3 text-xs">
                            <div className="p-3.5 bg-slate-50 rounded-2xl border border-slate-100 space-y-2.5">
                                <div className="flex justify-between items-start">
                                    <span className="text-slate-400 font-medium">อุปกรณ์:</span>
                                    <span className="font-bold text-slate-800 text-right">{item.name} ({item.code})</span>
                                </div>
                                <div className="p-2.5 bg-blue-50/80 rounded-xl border border-blue-100 flex justify-between items-center">
                                    <div>
                                        <span className="text-[10px] text-blue-600 block font-medium">ลดสต็อกต้นทาง ({rawVariant?.name})</span>
                                        <span className="font-bold text-slate-800">{rawVariant?.qty} ➔ {(rawVariant?.qty || 0) - Number(fromQty)} {rawVariant?.unit}</span>
                                    </div>
                                    <span className="text-sm font-bold text-blue-700">-{fromQty} {rawVariant?.unit}</span>
                                </div>
                                <div className="p-2.5 bg-emerald-50/80 rounded-xl border border-emerald-100 flex justify-between items-center">
                                    <div>
                                        <span className="text-[10px] text-emerald-600 block font-medium">เพิ่มสต็อกปลายทาง ({readyVariant?.name})</span>
                                        <span className="font-bold text-slate-800">{readyVariant?.qty} ➔ {(readyVariant?.qty || 0) + Number(toQty)} {readyVariant?.unit}</span>
                                    </div>
                                    <span className="text-sm font-bold text-emerald-700">+{toQty} {readyVariant?.unit}</span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-slate-400 font-medium">ผู้ทำรายการ:</span>
                                    <span className="font-bold text-slate-800">{currentUser?.name || 'ช่างเทคนิค'}</span>
                                </div>
                            </div>
                        </div>

                        {/* Footer (Fixed Bottom) */}
                        <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2.5 shrink-0">
                            <button
                                type="button"
                                onClick={() => setIsReviewing(false)}
                                disabled={submitting}
                                className="flex-1 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl font-bold text-xs sm:text-sm transition tap-bounce">
                                แก้ไข
                            </button>
                            <button
                                type="button"
                                onClick={handleConfirmConvert}
                                disabled={submitting}
                                className="flex-1 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-bold text-xs sm:text-sm shadow-md shadow-blue-600/20 transition flex items-center justify-center gap-1.5 tap-bounce">
                                {submitting ? 'กำลังแปรรูป...' : 'แปรรูปสินค้า'}
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}

function LabelPrintModal({ item, onClose }) {
    const qrContainerRef = useRef(null);
    const barcodeCanvasRef = useRef(null);

    useEffect(() => {
        if (qrContainerRef.current && window.QRCode) {
            qrContainerRef.current.innerHTML = '';
            new QRCode(qrContainerRef.current, {
                text: item.code,
                width: 100,
                height: 100,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.M
            });
        }
        if (barcodeCanvasRef.current && window.JsBarcode) {
            try {
                JsBarcode(barcodeCanvasRef.current, item.code, {
                    format: "CODE128",
                    width: 1.5,
                    height: 38,
                    displayValue: true,
                    fontSize: 11
                });
            } catch (e) {}
        }
    }, [item]);

    return (
        <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto animate-fade-in">
            <div className="bg-white rounded-3xl max-w-sm w-full shadow-2xl border border-slate-100 my-auto flex flex-col max-h-[calc(100dvh-2rem)] sm:max-h-[92vh] overflow-hidden modal-responsive-card">
                <div className="px-5 py-3.5 border-b border-slate-100 flex items-center justify-between shrink-0 bg-white no-print">
                    <h3 className="font-bold text-slate-900 text-sm">พิมพ์ป้ายสติกเกอร์บาร์โค้ด</h3>
                    <button onClick={onClose} className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition"><Icon name="x" size={18} /></button>
                </div>

                <div className="p-4 sm:p-5 overflow-y-auto flex-1">
                    <div className="sticker-card p-4 rounded-2xl border-2 border-dashed border-slate-300 text-center space-y-2 bg-slate-50/50">
                        <div className="font-bold text-[11px] text-slate-600">PAVARA STOCK SERVICE</div>
                        <div className="text-sm font-bold text-slate-900 line-clamp-1">{item.name}</div>
                        <div className="flex justify-center py-2" ref={qrContainerRef}></div>
                        <canvas ref={barcodeCanvasRef} className="mx-auto"></canvas>
                        <div className="text-[10px] text-slate-400">{item.category} • {item.unit}</div>
                    </div>
                </div>

                <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2 shrink-0 no-print">
                    <button onClick={onClose} className="flex-1 py-2.5 bg-slate-100 text-slate-600 hover:bg-slate-200 rounded-xl font-bold text-xs transition tap-bounce">
                        ปิด
                    </button>
                    <button onClick={() => window.print()} className="flex-1 py-2.5 bg-emerald-600 text-white rounded-xl font-bold text-xs hover:bg-emerald-700 flex items-center justify-center gap-1.5 shadow-sm shadow-emerald-600/20 transition tap-bounce">
                        <Icon name="printer" size={15} />
                        <span>สั่งพิมพ์</span>
                    </button>
                </div>
            </div>
        </div>
    );
}

// ==========================================
// MODERN COMBOBOX & AUTOCOMPLETE COMPONENTS
// ==========================================

function ComboboxField({
    label,
    required = false,
    value = '',
    onChange,
    placeholder = '',
    suggestions = [],
    onSelectOption
}) {
    const [open, setOpen] = useState(false);
    const containerRef = useRef(null);

    useEffect(() => {
        const handleClickOutside = (e) => {
            if (containerRef.current && !containerRef.current.contains(e.target)) {
                setOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const filtered = useMemo(() => {
        const list = (suggestions || []).filter(Boolean);
        if (!value || value.trim() === '') return list;
        const q = value.toLowerCase().trim();
        const matches = list.filter(s => s.toLowerCase().includes(q));
        return matches.length > 0 ? matches : list;
    }, [suggestions, value]);

    const handleSelect = (item) => {
        onChange(item);
        if (onSelectOption) onSelectOption(item);
        setOpen(false);
    };

    return (
        <div ref={containerRef} className="relative">
            {label && (
                <label className="block font-bold text-slate-700 text-xs mb-1">
                    {label} {required && <span className="text-red-500">*</span>}
                </label>
            )}
            <div className="relative">
                <input
                    type="text"
                    required={required}
                    value={value}
                    onChange={(e) => {
                        onChange(e.target.value);
                        setOpen(true);
                    }}
                    onFocus={() => setOpen(true)}
                    placeholder={placeholder}
                    className="w-full bg-slate-50 border border-slate-200/90 rounded-xl px-3 py-2 text-xs font-semibold focus:bg-white focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/20 focus:outline-hidden transition"
                />
                {value ? (
                    <button
                        type="button"
                        onClick={() => { onChange(''); setOpen(true); }}
                        className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-0.5 rounded-full"
                    >
                        <Icon name="x" size={13} />
                    </button>
                ) : (
                    <button
                        type="button"
                        onClick={() => setOpen(!open)}
                        className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-0.5"
                    >
                        <Icon name="chevron-down" size={13} />
                    </button>
                )}
            </div>

            {/* Floating Suggestions Dropdown Menu */}
            {open && filtered.length > 0 && (
                <div className="absolute left-0 right-0 top-full mt-1 bg-white border border-slate-200 rounded-2xl shadow-xl z-50 max-h-48 overflow-y-auto divide-y divide-slate-100 animate-fade-in py-1">
                    <div className="px-3 py-1.5 text-[10px] font-bold text-slate-400 uppercase tracking-wider bg-slate-50/70 flex items-center justify-between">
                        <span>ตัวเลือกในระบบ</span>
                        <span>{filtered.length} รายการ</span>
                    </div>
                    {filtered.map((opt, idx) => (
                        <button
                            key={idx}
                            type="button"
                            onMouseDown={(e) => {
                                e.preventDefault();
                                handleSelect(opt);
                            }}
                            className="w-full text-left px-3.5 py-2 text-xs font-semibold text-slate-700 hover:bg-emerald-50 hover:text-emerald-700 flex items-center justify-between transition group"
                        >
                            <span className="truncate">{opt}</span>
                            <Icon name="check" size={13} className="text-emerald-600 opacity-0 group-hover:opacity-100 transition" />
                        </button>
                    ))}
                </div>
            )}
        </div>
    );
}

function VariantConditionInput({ value, onChange, suggestions = [] }) {
    const [open, setOpen] = useState(false);
    const ref = useRef(null);

    useEffect(() => {
        const handleClickOutside = (e) => {
            if (ref.current && !ref.current.contains(e.target)) setOpen(false);
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const filtered = useMemo(() => {
        const list = (suggestions || []).filter(Boolean);
        if (!value) return list.slice(0, 8);
        return list.filter(s => s.toLowerCase().includes(value.toLowerCase()) && s !== value).slice(0, 8);
    }, [suggestions, value]);

    return (
        <div ref={ref} className="relative flex-1">
            <input
                type="text"
                placeholder="ชื่อสภาพ..."
                value={value}
                onChange={(e) => { onChange(e.target.value); setOpen(true); }}
                onFocus={() => setOpen(true)}
                className="w-full bg-white border border-slate-200 rounded-xl p-2 text-xs font-semibold focus:border-emerald-500 focus:outline-hidden"
            />
            {open && filtered.length > 0 && (
                <div className="absolute left-0 right-0 top-full mt-1 bg-white border border-slate-200 rounded-xl shadow-xl z-50 max-h-36 overflow-y-auto divide-y divide-slate-100 py-1 animate-fade-in">
                    {filtered.map((c, idx) => (
                        <button
                            key={idx}
                            type="button"
                            onMouseDown={(e) => {
                                e.preventDefault();
                                onChange(c);
                                setOpen(false);
                            }}
                            className="w-full text-left px-3 py-1.5 text-xs text-slate-700 hover:bg-emerald-50 hover:text-emerald-700 transition"
                        >
                            {c}
                        </button>
                    ))}
                </div>
            )}
        </div>
    );
}

// ==========================================
// CATEGORY SAFETY STOCK CONFIG MODAL
// ==========================================
function CategorySafetyModal({ categorySafetyStocks = {}, items = [], onClose, onSave, submitting }) {
    const categories = useMemo(() => {
        const seedCats = (window.SEED_CATEGORIES || []).filter(c => c && c !== 'ทั้งหมด');
        const itemCats = items.map(i => i.category).filter(Boolean);
        const combined = Array.from(new Set([...seedCats, ...itemCats]));
        return combined;
    }, [items]);

    const [thresholds, setThresholds] = useState(() => ({
        ...categorySafetyStocks
    }));
    const [applyToExisting, setApplyToExisting] = useState(true);

    const countByCategory = useMemo(() => {
        const counts = {};
        items.forEach(it => {
            const cat = it.category?.trim() || 'ทั่วไป';
            counts[cat] = (counts[cat] || 0) + 1;
        });
        return counts;
    }, [items]);

    const handleUpdate = (cat, val) => {
        const num = Math.max(0, parseInt(val, 10) || 0);
        setThresholds(prev => ({ ...prev, [cat]: num }));
    };

    const handleStep = (cat, delta) => {
        const curr = thresholds[cat] !== undefined ? thresholds[cat] : 5;
        const next = Math.max(0, curr + delta);
        setThresholds(prev => ({ ...prev, [cat]: next }));
    };

    const handleResetDefaults = () => {
        if (window.DEFAULT_CATEGORY_SAFETY) {
            setThresholds({ ...window.DEFAULT_CATEGORY_SAFETY });
        }
    };

    return (
        <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto animate-fade-in">
            <div className="relative bg-white rounded-3xl max-w-lg w-full shadow-2xl flex flex-col max-h-[calc(100dvh-2rem)] sm:max-h-[min(90vh,780px)] overflow-hidden my-auto border border-slate-100 modal-responsive-card">
                {/* Header */}
                <div className="px-5 py-3.5 sm:py-4 border-b border-slate-100 flex items-center justify-between shrink-0 bg-white">
                    <div className="flex items-center gap-2.5">
                        <div className="w-9 h-9 rounded-2xl bg-amber-50 text-amber-600 flex items-center justify-center shrink-0">
                            <Icon name="shield-alert" size={20} />
                        </div>
                        <div>
                            <h3 className="font-bold text-slate-900 text-sm sm:text-base">สต็อกขั้นต่ำรายหมวด</h3>
                            <p className="text-[11px] text-slate-400">เกณฑ์แจ้งเตือนสต็อกขั้นต่ำแยกตามหมวดหมู่</p>
                        </div>
                    </div>
                    <button 
                        type="button" 
                        onClick={onClose} 
                        disabled={submitting} 
                        className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition"
                    >
                        <Icon name="x" size={18} />
                    </button>
                </div>

                {/* Body List */}
                <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-2 text-xs">
                    <div className="flex items-center justify-between px-1 mb-1">
                        <span className="text-[11px] font-bold text-slate-500 uppercase tracking-wider">
                            หมวดหมู่อุปกรณ์ ({categories.length})
                        </span>
                        <button 
                            type="button"
                            onClick={handleResetDefaults}
                            className="text-[11px] text-amber-600 hover:text-amber-700 font-semibold"
                        >
                            คืนค่าเริ่มต้น
                        </button>
                    </div>

                    {categories.map(cat => {
                        const val = thresholds[cat] !== undefined ? thresholds[cat] : 5;
                        const count = countByCategory[cat] || 0;
                        return (
                            <div 
                                key={cat}
                                className="flex items-center justify-between p-2.5 sm:p-3 rounded-2xl bg-slate-50 border border-slate-200/70 hover:bg-slate-100/60 transition gap-2 sm:gap-3"
                            >
                                <div className="min-w-0 flex-1">
                                    <div className="font-bold text-slate-800 text-xs sm:text-sm truncate">
                                        {cat}
                                    </div>
                                    <div className="text-[10px] sm:text-[11px] text-slate-400 mt-0.5">
                                        {count} รายการในระบบ
                                    </div>
                                </div>

                                <div className="flex items-center gap-1 sm:gap-1.5 shrink-0">
                                    <button 
                                        type="button"
                                        onClick={() => handleStep(cat, -1)}
                                        className="w-7 h-7 rounded-lg bg-white border border-slate-200 text-slate-600 hover:bg-slate-100 flex items-center justify-center font-bold text-sm shadow-xs transition"
                                    >
                                        -
                                    </button>
                                    <input 
                                        type="number"
                                        min="0"
                                        value={val}
                                        onChange={(e) => handleUpdate(cat, e.target.value)}
                                        className="w-14 text-center font-bold text-xs bg-white border border-slate-200 rounded-lg py-1 focus:outline-hidden focus:border-amber-500"
                                    />
                                    <button 
                                        type="button"
                                        onClick={() => handleStep(cat, 1)}
                                        className="w-7 h-7 rounded-lg bg-white border border-slate-200 text-slate-600 hover:bg-slate-100 flex items-center justify-center font-bold text-sm shadow-xs transition"
                                    >
                                        +
                                    </button>
                                    <span className="text-[11px] text-slate-400 font-medium ml-1 hidden sm:inline">
                                        ชิ้น
                                    </span>
                                </div>
                            </div>
                        );
                    })}

                    {/* Checkbox apply to existing */}
                    <div className="pt-2 px-1">
                        <label className="flex items-start gap-2.5 cursor-pointer">
                            <input 
                                type="checkbox"
                                checked={applyToExisting}
                                onChange={(e) => setApplyToExisting(e.target.checked)}
                                className="mt-0.5 rounded text-amber-600 focus:ring-amber-500 rounded-md"
                            />
                            <div className="text-xs text-slate-600">
                                <span className="font-bold text-slate-800">ปรับปรุงอุปกรณ์ทั้งหมดในระบบ</span>
                                <p className="text-[11px] text-slate-400">อัปเดตจุดสั่งซื้อของสินค้าเดิมในแต่ละหมวดให้ตรงกับค่าสต็อกขั้นต่ำใหม่ทันที</p>
                            </div>
                        </label>
                    </div>
                </div>

                {/* Footer */}
                <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2.5 shrink-0">
                    <button 
                        type="button"
                        onClick={onClose}
                        disabled={submitting}
                        className="flex-1 py-2.5 bg-slate-100 text-slate-600 hover:bg-slate-200 rounded-xl font-bold transition text-xs sm:text-sm tap-bounce"
                    >
                        ยกเลิก
                    </button>
                    <button 
                        type="button"
                        onClick={() => onSave(thresholds, applyToExisting)}
                        disabled={submitting}
                        className="flex-1 py-2.5 bg-amber-600 text-white hover:bg-amber-700 rounded-xl font-bold transition text-xs sm:text-sm shadow-sm shadow-amber-600/20 tap-bounce flex items-center justify-center gap-1.5"
                    >
                        {submitting ? (
                            <>
                                <Icon name="loader-2" size={15} className="animate-spin" />
                                <span>กำลังบันทึก...</span>
                            </>
                        ) : (
                            <span>บันทึก</span>
                        )}
                    </button>
                </div>
            </div>
        </div>
    );
}

// ==========================================
// ITEM EDIT MODAL
// ==========================================
function ItemEditModal({ item, existingItems = [], categorySafetyStocks = {}, isAdmin, onClose, onSave, submitting }) {
    const defaultReorder = (!item.id && categorySafetyStocks && categorySafetyStocks[item.category || 'อุปกรณ์หัวจ่าย']) 
        ? categorySafetyStocks[item.category || 'อุปกรณ์หัวจ่าย'] 
        : 5;

    const [formData, setFormData] = useState({
        ...item,
        code: item.code || '',
        name: item.name || '',
        category: item.category || 'อุปกรณ์หัวจ่าย',
        unit: item.unit || 'ชิ้น',
        reorder_point: item.reorder_point !== undefined ? item.reorder_point : defaultReorder,
        cost_price: item.cost_price || 0,
        notes: item.notes || '',
        image_url: item.image_url || '',
        variants: (item.variants && item.variants.length > 0) 
            ? [...item.variants] 
            : [{ id: 'var-' + Date.now(), condition_type: 'new', name: 'ของใหม่', qty: 0, unit: item.unit || 'ชิ้น' }]
    });

    const [isReviewing, setIsReviewing] = useState(false);
    const [imageCompressing, setImageCompressing] = useState(false);
    const [imageInfo, setImageInfo] = useState(null);
    const fileInputRef = useRef(null);

    // ดึงข้อมูลที่มีอยู่ในระบบมาเป็นตัวเลือก (ชื่ออุปกรณ์, หน่วยนับ, สภาพย่อย, หมายเหตุ)
    const existingData = useMemo(() => {
        const names = new Set();
        const categories = new Set((window.SEED_CATEGORIES || []).filter(c => c && c !== 'ทั้งหมด'));
        const units = new Set(['ชิ้น', 'ตัว', 'กล่อง', 'ชุด', 'ม้วน', 'เมตร', 'แพ็ค', 'อัน', 'แผ่น', 'เส้น']);
        const conditions = new Set(['ของใหม่', 'มือสอง', 'ยังไม่ประกอบ', 'กล่องดิบ', 'พร้อมใช้', 'รอส่งซ่อม']);
        const notes = new Set(['สำหรับประกอบตู้จ่าย', 'สั่งเผื่อสำรอง', 'รอส่งซ่อม', 'พร้อมติดตั้งหน้างาน', 'สต็อกกลาง']);

        (existingItems || []).forEach(it => {
            if (it.name) names.add(it.name.trim());
            if (it.category) categories.add(it.category.trim());
            if (it.unit) units.add(it.unit.trim());
            if (it.notes && it.notes.trim()) notes.add(it.notes.trim());
            (it.variants || []).forEach(v => {
                if (v.name) conditions.add(v.name.trim());
            });
        });

        return {
            names: Array.from(names),
            categories: Array.from(categories),
            units: Array.from(units),
            conditions: Array.from(conditions),
            notes: Array.from(notes)
        };
    }, [existingItems]);

    // จัดการอัปโหลดรูปภาพ บีบอัดเป็น .webp ขนาด 100-150 KB คมชัดสูงอัตโนมัติ
    const handleImageChange = async (e) => {
        const file = e.target.files[0];
        if (file) {
            setImageCompressing(true);
            try {
                if (window.compressImageToWebp) {
                    const res = await window.compressImageToWebp(file, 900);
                    if (res && res.dataUrl) {
                        setFormData(prev => ({ ...prev, image_url: res.dataUrl }));
                        setImageInfo({ sizeKb: res.sizeKb, format: 'WebP' });
                    } else {
                        const reader = new FileReader();
                        reader.onload = () => setFormData(prev => ({ ...prev, image_url: reader.result }));
                        reader.readAsDataURL(file);
                    }
                } else {
                    const reader = new FileReader();
                    reader.onload = () => setFormData(prev => ({ ...prev, image_url: reader.result }));
                    reader.readAsDataURL(file);
                }
            } catch (err) {
                console.error("Image compression error:", err);
            } finally {
                setImageCompressing(false);
            }
        }
    };

    // ฟังก์ชันเลือกชื่ออุปกรณ์แล้วเติมหมวดหมู่และหน่วยนับให้อัตโนมัติถ้าตรงกับข้อมูลเดิม
    const handleSelectName = (selectedName) => {
        const matched = (existingItems || []).find(it => it.name === selectedName);
        if (matched) {
            setFormData(prev => ({
                ...prev,
                name: matched.name,
                category: matched.category || prev.category,
                unit: matched.unit || prev.unit
            }));
        } else {
            setFormData(prev => ({ ...prev, name: selectedName }));
        }
    };

    const addVariant = () => {
        setFormData(prev => ({
            ...prev,
            variants: [
                ...prev.variants,
                { id: 'var-' + Date.now(), condition_type: 'new', name: 'ของใหม่', qty: 0, unit: formData.unit }
            ]
        }));
    };

    const removeVariant = (idx) => {
        setFormData(prev => ({
            ...prev,
            variants: prev.variants.filter((_, i) => i !== idx)
        }));
    };

    const updateVariant = (idx, field, val) => {
        setFormData(prev => {
            const updated = [...prev.variants];
            updated[idx] = { ...updated[idx], [field]: val };
            return { ...prev, variants: updated };
        });
    };

    return (
        <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto">
            <div className="relative bg-white rounded-3xl max-w-lg w-full shadow-2xl flex flex-col max-h-[calc(100dvh-2rem)] sm:max-h-[min(90vh,780px)] overflow-hidden my-auto border border-slate-100 modal-responsive-card animate-fade-in">
                {/* Modern Saving Overlay Inside Modal */}
                {submitting && (
                    <div className="absolute inset-0 bg-white/95 backdrop-blur-sm rounded-3xl z-20 flex flex-col items-center justify-center p-6 text-center animate-fade-in">
                        <div className="relative w-16 h-16 flex items-center justify-center mb-3">
                            <div className="absolute inset-0 rounded-full border-4 border-emerald-100"></div>
                            <div className="absolute inset-0 rounded-full border-4 border-emerald-600 border-t-transparent animate-spin"></div>
                            <div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shadow-xs">
                                <Icon name="package-check" size={22} className="animate-pulse" />
                            </div>
                        </div>
                        <h4 className="font-bold text-base text-slate-900">กำลังบันทึก...</h4>
                        <div className="w-48 bg-slate-100 rounded-full h-1.5 overflow-hidden mt-3">
                            <div className="bg-gradient-to-r from-emerald-500 via-teal-400 to-emerald-600 h-full w-full animate-pulse rounded-full"></div>
                        </div>
                    </div>
                )}

                {isReviewing ? (
                    /* 3. หน้าตรวจสอบข้อมูลก่อนบันทึก พร้อมตัวเลือก แก้ไข / บันทึก */
                    <div className="flex flex-col h-full max-h-[inherit] overflow-hidden animate-fade-in">
                        {/* Header ตรวจสอบ (Fixed Top) */}
                        <div className="px-5 py-3.5 sm:py-4 border-b border-slate-100 flex items-center justify-between shrink-0 bg-white">
                            <div className="flex items-center gap-2.5">
                                <div className="w-9 h-9 rounded-2xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0">
                                    <Icon name="clipboard-check" size={20} />
                                </div>
                                <div>
                                    <h3 className="font-bold text-slate-900 text-sm sm:text-base">
                                        ตรวจสอบ
                                    </h3>
                                    <p className="text-[11px] text-slate-400">ตรวจสอบความถูกต้องก่อนบันทึก</p>
                                </div>
                            </div>
                            <button 
                                type="button"
                                onClick={() => setIsReviewing(false)} 
                                disabled={submitting} 
                                className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition"
                            >
                                <Icon name="x" size={18} />
                            </button>
                        </div>

                        {/* Details Preview Card (Scrollable Body) */}
                        <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-3.5 text-xs">
                            {/* รูปภาพและข้อมูลหลัก */}
                            <div className="p-3.5 bg-slate-50/90 rounded-2xl border border-slate-200/80 flex items-center gap-3.5">
                                <div className="w-20 h-20 rounded-2xl overflow-hidden bg-white border border-slate-200 shrink-0 flex items-center justify-center shadow-xs">
                                    {formData.image_url ? (
                                        <img src={formData.image_url} alt={formData.name} className="w-full h-full object-cover" />
                                    ) : (
                                        <Icon name="package" size={28} className="text-slate-300" />
                                    )}
                                </div>
                                <div className="flex-1 min-w-0 space-y-1">
                                    <div className="flex items-center gap-1.5 flex-wrap">
                                        <span className="font-mono text-xs font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-lg border border-emerald-200/60">
                                            {formData.code || '-'}
                                        </span>
                                        <span className="text-[10px] font-semibold text-slate-600 bg-white border border-slate-200/80 px-2 py-0.5 rounded-lg">
                                            {formData.category}
                                        </span>
                                    </div>
                                    <div className="font-bold text-slate-900 text-sm truncate">
                                        {formData.name}
                                    </div>
                                    <div className="text-[11px] text-slate-500">
                                        หน่วยนับ: <span className="font-bold text-slate-800">{formData.unit}</span>
                                        <span className="mx-1.5">•</span>
                                        จุดสั่งซื้อ: <span className="font-bold text-slate-800">{formData.reorder_point}</span>
                                    </div>
                                </div>
                            </div>

                            {/* รายการสภาพสินค้าและจำนวน */}
                            <div className="p-3.5 bg-slate-50/90 rounded-2xl border border-slate-200/80 space-y-2">
                                <div className="flex items-center justify-between text-xs font-bold text-slate-700">
                                    <span>สภาพสินค้าและจำนวนตั้งต้น</span>
                                    <span className="text-[11px] font-bold text-emerald-700 bg-emerald-100/70 px-2.5 py-0.5 rounded-full">
                                        รวม {formData.variants.reduce((sum, v) => sum + Number(v.qty || 0), 0)} {formData.unit}
                                    </span>
                                </div>
                                <div className="space-y-1.5">
                                    {formData.variants.map((v, i) => (
                                        <div key={i} className="flex items-center justify-between bg-white px-3 py-2 rounded-xl border border-slate-200/60 text-xs">
                                            <span className="font-semibold text-slate-700 flex items-center gap-1.5">
                                                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500"></span>
                                                {v.name || 'ไม่ระบุสภาพ'}
                                            </span>
                                            <span className="font-mono font-bold text-slate-900">
                                                {Number(v.qty || 0)} <span className="text-slate-400 font-normal text-[11px]">{formData.unit}</span>
                                            </span>
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {/* หมายเหตุถ้ามี */}
                            {formData.notes && (
                                <div className="p-3 bg-slate-50/90 rounded-2xl border border-slate-200/80 text-xs">
                                    <span className="font-bold text-slate-700 block mb-0.5">หมายเหตุ:</span>
                                    <p className="text-slate-600 leading-relaxed">{formData.notes}</p>
                                </div>
                            )}
                        </div>

                        {/* Action Buttons: แก้ไข vs บันทึก (Fixed Footer) */}
                        <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2.5 shrink-0">
                            <button
                                type="button"
                                onClick={() => setIsReviewing(false)}
                                disabled={submitting}
                                className="flex-1 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl font-bold transition flex items-center justify-center gap-1.5 text-xs sm:text-sm tap-bounce"
                            >
                                <span>แก้ไข</span>
                            </button>
                            <button
                                type="button"
                                onClick={() => {
                                    const payload = { ...formData };
                                    if (!payload.variants || payload.variants.length === 0) {
                                        payload.variants = [
                                            { id: 'var-' + Date.now(), condition_type: 'new', name: 'ของใหม่', qty: 0, unit: payload.unit || 'ชิ้น' }
                                        ];
                                    }
                                    onSave(payload);
                                }}
                                disabled={submitting}
                                className="flex-1 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold shadow-md shadow-emerald-600/20 transition flex items-center justify-center text-xs sm:text-sm tap-bounce"
                            >
                                <span>บันทึก</span>
                            </button>
                        </div>
                    </div>
                ) : (
                    /* Regular Form Mode */
                    <form onSubmit={(e) => { 
                        e.preventDefault(); 
                        if (!formData.code || !formData.name) return;
                        setIsReviewing(true);
                    }} className="flex flex-col h-full max-h-[inherit] overflow-hidden">
                        {/* Header (Fixed Top) */}
                        <div className="px-5 py-3.5 sm:py-4 border-b border-slate-100 flex items-center justify-between shrink-0 bg-white">
                            <div className="flex items-center gap-2">
                                <div className="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0">
                                    <Icon name="package" size={18} />
                                </div>
                                <h3 className="font-bold text-slate-900 text-sm sm:text-base">
                                    {item.id ? 'แก้ไขข้อมูลอุปกรณ์' : 'เพิ่มอุปกรณ์ใหม่'}
                                </h3>
                            </div>
                            <button 
                                type="button" 
                                onClick={onClose} 
                                disabled={submitting} 
                                className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition"
                            >
                                <Icon name="x" size={18} />
                            </button>
                        </div>

                        {/* Scrollable Form Body */}
                        <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-4 text-xs">
                            {/* 1. อัปโหลดรูปภาพอุปกรณ์ */}
                            <div className="p-3.5 bg-slate-50/80 rounded-2xl border border-slate-200/80">
                                <input 
                                    type="file" 
                                    ref={fileInputRef} 
                                    onChange={handleImageChange} 
                                    accept="image/*" 
                                    className="hidden" 
                                />

                                {formData.image_url ? (
                                    <div className="flex items-center gap-3.5">
                                        <div className="relative w-20 h-20 sm:w-24 sm:h-24 rounded-2xl overflow-hidden bg-white border border-slate-200 shadow-xs shrink-0 group">
                                            <img 
                                                src={formData.image_url} 
                                                alt="preview" 
                                                className="w-full h-full object-cover" 
                                            />
                                            {imageCompressing && (
                                                <div className="absolute inset-0 bg-slate-900/70 flex items-center justify-center text-white text-[10px] font-bold">
                                                    กำลังโหลด...
                                                </div>
                                            )}
                                        </div>
                                        <div className="flex-1 min-w-0 space-y-1.5">
                                            <div className="flex items-center gap-2">
                                                <span className="font-bold text-slate-800 text-xs">รูปภาพอุปกรณ์</span>
                                            </div>
                                            <div className="flex items-center gap-2 pt-0.5">
                                                <button
                                                    type="button"
                                                    onClick={() => fileInputRef.current?.click()}
                                                    disabled={imageCompressing}
                                                    className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-white border border-slate-200 rounded-xl text-slate-700 text-xs font-bold hover:bg-slate-50 shadow-xs transition tap-bounce"
                                                >
                                                    <Icon name="camera" size={13} />
                                                    <span>เปลี่ยนรูป</span>
                                                </button>
                                                <button
                                                    type="button"
                                                    onClick={() => {
                                                        setFormData(prev => ({ ...prev, image_url: '' }));
                                                        setImageInfo(null);
                                                    }}
                                                    className="inline-flex items-center gap-1.5 px-2.5 py-1.5 bg-white border border-red-200 text-red-600 rounded-xl text-xs font-semibold hover:bg-red-50 transition tap-bounce"
                                                    title="ลบรูปภาพ"
                                                >
                                                    <Icon name="trash" size={13} />
                                                    <span>ลบรูป</span>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                ) : (
                                    <div
                                        onClick={() => fileInputRef.current?.click()}
                                        className="flex flex-col items-center justify-center py-4 px-3 bg-white border-2 border-dashed border-slate-300 hover:border-emerald-500 rounded-2xl cursor-pointer transition text-center group"
                                    >
                                        <div className="w-11 h-11 rounded-2xl bg-emerald-50 text-emerald-600 flex items-center justify-center mb-1.5 group-hover:scale-105 transition">
                                            <Icon name="camera" size={20} />
                                        </div>
                                        <span className="text-xs font-bold text-slate-800">อัปโหลดรูปภาพ</span>
                                        <p className="text-[11px] text-slate-400 mt-0.5">
                                            แตะเพื่อเลือกรูปถ่ายหรือไฟล์ภาพ
                                        </p>
                                    </div>
                                )}
                            </div>

                            {/* รหัสสินค้า & หมวดหมู่ */}
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                                <div>
                                    <label className="block font-bold text-slate-700 mb-1">รหัสสินค้า *</label>
                                    <input
                                        type="text"
                                        required
                                        value={formData.code}
                                        onChange={(e) => setFormData({ ...formData, code: e.target.value })}
                                        className="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 font-mono focus:bg-white focus:border-emerald-500 focus:outline-hidden transition"
                                    />
                                </div>
                                <div>
                                    <ComboboxField
                                        label="หมวดหมู่"
                                        required={true}
                                        value={formData.category}
                                        onChange={(val) => setFormData(prev => ({ 
                                            ...prev, 
                                            category: val,
                                            reorder_point: (!item.id && categorySafetyStocks && categorySafetyStocks[val] !== undefined)
                                                ? categorySafetyStocks[val]
                                                : prev.reorder_point
                                        }))}
                                        placeholder="เลือกหรือพิมพ์หมวดหมู่..."
                                        suggestions={existingData.categories}
                                    />
                                </div>
                            </div>

                            {/* 2. ช่องชื่ออุปกรณ์ (Combobox Dropdown - ลบไกด์และข้อความย่อยออก) */}
                            <ComboboxField
                                label="ชื่ออุปกรณ์"
                                required={true}
                                value={formData.name}
                                onChange={(val) => setFormData(prev => ({ ...prev, name: val }))}
                                onSelectOption={handleSelectName}
                                placeholder="ค้นหาหรือพิมพ์ชื่ออุปกรณ์..."
                                suggestions={existingData.names}
                            />

                            {/* 3. ช่องหน่วยนับ, จุดสั่งซื้อ */}
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                                <div>
                                    <ComboboxField
                                        label="หน่วยนับ"
                                        required={true}
                                        value={formData.unit}
                                        onChange={(val) => setFormData(prev => ({ ...prev, unit: val }))}
                                        placeholder="เช่น ชิ้น, ตัว"
                                        suggestions={existingData.units}
                                    />
                                </div>
                                <div>
                                    <label className="block font-bold text-slate-700 mb-1">จุดสั่งซื้อ *</label>
                                    <input
                                        type="number"
                                        min="0"
                                        value={formData.reorder_point}
                                        onChange={(e) => setFormData({ ...formData, reorder_point: e.target.value })}
                                        className="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 focus:bg-white focus:border-emerald-500 focus:outline-hidden transition font-semibold"
                                    />
                                </div>
                            </div>

                            {/* 4. สภาพ / สถานะย่อย (ลบไกด์ชิปและข้อความย่อยออก) */}
                            <div className="pt-2 border-t border-slate-100">
                                <div className="flex items-center justify-between mb-1.5">
                                    <label className="font-bold text-slate-700 block">สภาพ / สถานะย่อย</label>
                                    <button 
                                        type="button" 
                                        onClick={addVariant} 
                                        className="flex items-center gap-1 text-emerald-600 font-bold hover:text-emerald-700 text-xs px-2 py-1 rounded-lg hover:bg-emerald-50 transition"
                                    >
                                        <Icon name="plus" size={13} />
                                        <span>เพิ่มสภาพย่อย</span>
                                    </button>
                                </div>

                                <div className="space-y-2">
                                    {formData.variants.map((v, i) => (
                                        <div key={i} className="bg-slate-50 p-2.5 rounded-2xl border border-slate-200/70">
                                            <div className="flex gap-2 items-center">
                                                <VariantConditionInput
                                                    value={v.name}
                                                    onChange={(val) => updateVariant(i, 'name', val)}
                                                    suggestions={existingData.conditions}
                                                />
                                                <div className="flex items-center gap-1 bg-white border border-slate-200 rounded-xl px-2 py-1">
                                                    <input
                                                        type="number"
                                                        min="0"
                                                        placeholder="0"
                                                        value={v.qty}
                                                        onChange={(e) => updateVariant(i, 'qty', e.target.value)}
                                                        className="w-14 text-center text-xs font-bold focus:outline-hidden"
                                                    />
                                                    <span className="text-[10px] text-slate-400 font-medium">{formData.unit}</span>
                                                </div>
                                                <button 
                                                    type="button" 
                                                    onClick={() => removeVariant(i)} 
                                                    className="p-1.5 text-slate-400 hover:text-red-600 rounded-lg hover:bg-red-50 transition"
                                                    title="ลบสภาพนี้"
                                                >
                                                    <Icon name="trash" size={14} />
                                                </button>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {/* 5. ช่องหมายเหตุ (ลบไกด์และข้อความย่อยออก) */}
                            <ComboboxField
                                label="หมายเหตุ"
                                value={formData.notes}
                                onChange={(val) => setFormData(prev => ({ ...prev, notes: val }))}
                                placeholder="ระบุหมายเหตุเพิ่มเติม (ถ้ามี)..."
                                suggestions={existingData.notes}
                            />
                        </div>

                        {/* Footer / Actions (Fixed Bottom) */}
                        <div className="px-5 py-3.5 border-t border-slate-100 bg-white flex gap-2.5 shrink-0">
                            <button 
                                type="button" 
                                onClick={onClose} 
                                disabled={submitting} 
                                className="flex-1 py-2.5 bg-slate-100 text-slate-600 hover:bg-slate-200 rounded-xl font-bold transition text-xs sm:text-sm tap-bounce"
                            >
                                ยกเลิก
                            </button>
                            <button 
                                type="submit" 
                                disabled={submitting} 
                                className="flex-1 py-2.5 bg-emerald-600 text-white rounded-xl font-bold hover:bg-emerald-700 shadow-sm shadow-emerald-600/20 transition tap-bounce flex items-center justify-center text-xs sm:text-sm"
                            >
                                <span>บันทึก</span>
                            </button>
                        </div>
                    </form>
                )}
            </div>
        </div>
    );
}

// Render React App
ReactDOM.render(<App />, document.getElementById('root'));
