/* ----------------------------------------------------
 * KOPERASI DIGITAL MERAH PUTIH 2026 - APP ENGINE
 * ---------------------------------------------------- */

// Patch window.fetch to support subdirectories (like /kopdigi/public/)
const originalFetch = window.fetch;
window.fetch = function (url, options) {
    if (typeof url === 'string' && url.startsWith('/api/')) {
        const pathname = window.location.pathname;
        let base = '/';
        
        if (pathname.includes('/public')) {
            base = pathname.substring(0, pathname.indexOf('/public') + 7) + '/';
        } else if (pathname.includes('/index.php')) {
            base = pathname.substring(0, pathname.indexOf('/index.php')) + '/';
        } else {
            const parts = pathname.split('/').filter(p => p !== '');
            if (parts.length > 0 && parts[0] === 'kopdigi') {
                base = '/kopdigi/public/';
            }
        }
        
        if (!base.endsWith('/')) base += '/';
        url = base + url.substring(1);
    }
    return originalFetch(url, options);
};

// Global State
const state = {
    // Admin state
    activeRole: 'superadmin', // 'superadmin', 'dinasadmin', 'coopadmin'
    activeTab: 'super-dashboard',
    
    // Loaded database records
    cooperatives: [],
    regions: [],
    products: [],
    orders: [],
    auditLogs: [],
    rolePermissions: null,
    messages: [],        // seller inbox threads
    // Desktop Marketplace State
    marketView: 'home', 
    selectedMarketCoop: null,
    selectedMarketProduct: null,
    marketCart: [],
    marketSearchQuery: '',
    marketCategoryFilter: '',
    
    // Active Coop Admin context (affiliates with Koperasi Pegawai A by default)
    coopAdminId: 3, 
    coopId: 1,

    // Active message thread
    activeMessageThread: null,

    // Customer App (Simulator) state
    customerSession: null,
    cart: [],
    selectedCoop: null,
    selectedCoopCategory: 0, // 0 = Semua
    searchQuery: '',
    shippingAddress: 'Jl. Jenderal Sudirman No. 24, Limboto, Gorontalo',
    selectedCourier: 'KopExpress',
    currentPhoneView: 'login', // 'login', 'register', 'home', 'store', 'product-detail', 'cart', 'checkout', 'payment', 'tracking', 'history', 'chat'
    activePhoneTab: 'home',
    activeProductDetail: null,
    activeOrderTracking: null,
    chatMessages: [
        { sender: 'AI', text: 'Halo! Saya AI Assistant Koperasi Digital Merah Putih. Ada yang bisa saya bantu hari ini?' }
    ]
};

// Application Init
document.addEventListener('DOMContentLoaded', () => {
    logConsole('Sistem Koperasi Digital Merah Putih berhasil dimuat.');
    initPermissions();
    loadAllData();
    setupEventListeners();
    renderPhoneScreen();
});

// Developer Console Log
function logConsole(message, type = 'success') {
    const consoles = document.querySelectorAll('.console-log');
    consoles.forEach(con => {
        const time = new Date().toLocaleTimeString();
        con.innerHTML += `<div style="margin-bottom: 4px;"><span style="color: #64748B;">[${time}]</span> <span style="color: ${type === 'error' ? '#EF4444' : '#10B981'}">${message}</span></div>`;
        con.scrollTop = con.scrollHeight;
    });
}

// REST API Fetching with Mock Fallbacks
async function loadAllData() {
    try {
        // Fetch Cooperatives
        const coopRes = await fetch('/api/cooperatives');
        if (!coopRes.ok) throw new Error('Cooperative API offline');
        const res = await coopRes.json();
        state.cooperatives = res.data;

        // Fetch Regions
        const regionRes = await fetch('/api/regions');
        if (!regionRes.ok) throw new Error('Regions API offline');
        const resRegion = await regionRes.json();
        state.regions = resRegion.data;

        // Fetch Products
        const prodRes = await fetch('/api/products');
        if (!prodRes.ok) throw new Error('Products API offline');
        const resProd = await prodRes.json();
        state.products = resProd.data;

        // Fetch Orders
        const orderRes = await fetch('/api/orders');
        if (!orderRes.ok) throw new Error('Orders API offline');
        const resOrder = await orderRes.json();
        state.orders = resOrder.data;

        // Fetch Audit Logs
        const logRes = await fetch('/api/audit-logs');
        if (!logRes.ok) throw new Error('Audit Logs API offline');
        const resLog = await logRes.json();
        state.auditLogs = resLog.data;

        // Fetch Users
        const userRes = await fetch('/api/users');
        if (!userRes.ok) throw new Error('Users API offline');
        const resUser = await userRes.json();
        state.users = resUser.data;

        logConsole('Sinkronisasi database dengan REST API Backend berhasil dilakukan.');
    } catch (err) {
        logConsole('REST API sedang offline/setup. Menjalankan fallback database simulasi.', 'error');
        // Setup local mock data if server offline
        setupLocalMockData();
    }
    
    // Sync dashboard and stats
    updateStatsDashboard();

    // Populate region dropdowns
    populateRegionDropdowns();
    
    // Check and apply web admin session
    checkWebSession();
    
    renderPhoneScreen();
}

function setupLocalMockData() {
    state.regions = [
        { id: 1, nama_wilayah: 'Kota Gorontalo', provinsi: 'Gorontalo', deskripsi: 'Pusat administratif dan ekonomi Provinsi Gorontalo.', created_at: '2026-05-29 08:00:00' },
        { id: 2, nama_wilayah: 'Kabupaten Gorontalo', provinsi: 'Gorontalo', deskripsi: 'Kawasan pengawasan sentral dengan jumlah anggota koperasi terbesar.', created_at: '2026-05-29 08:00:00' },
        { id: 3, nama_wilayah: 'Kabupaten Bone Bolango', provinsi: 'Gorontalo', deskripsi: 'Kawasan timur Gorontalo yang kaya akan potensi pertanian & kopi Pinogu.', created_at: '2026-05-29 08:00:00' },
        { id: 4, nama_wilayah: 'Kabupaten Boalemo', provinsi: 'Gorontalo', deskripsi: 'Wilayah barat Gorontalo yang fokus pada pengolahan kelapa dan jagung.', created_at: '2026-05-29 08:00:00' },
        { id: 5, nama_wilayah: 'Kabupaten Gorontalo Utara', provinsi: 'Gorontalo', deskripsi: 'Wilayah pesisir utara dengan fokus pada koperasi perikanan laut.', created_at: '2026-05-29 08:00:00' },
        { id: 6, nama_wilayah: 'Kabupaten Pohuwato', provinsi: 'Gorontalo', deskripsi: 'Wilayah ujung barat Gorontalo dengan fokus pertambangan rakyat & perkebunan.', created_at: '2026-05-29 08:00:00' }
    ];
    state.cooperatives = [
        { id: 1, kode_koperasi: 'KOP-PEGAWAI-A', nama_koperasi: 'Koperasi Pegawai Republik Indonesia (KPRI) Gorontalo', alamat: 'Jl. Jenderal Sudirman No. 12, Kota Gorontalo', kabupaten: 'Kota Gorontalo', provinsi: 'Gorontalo', logo: 'https://images.unsplash.com/photo-1543269865-cbf427effbad?w=150', status: 'aktif' },
        { id: 2, kode_koperasi: 'KOP-MERAH-PUTIH', nama_koperasi: 'Koperasi Merah Putih Sejahtera', alamat: 'Jl. Merdeka No. 45, Limboto, Kab. Gorontalo', kabupaten: 'Kabupaten Gorontalo', provinsi: 'Gorontalo', logo: 'https://images.unsplash.com/photo-1556742049-0cfed4f6a45d?w=150', status: 'aktif' },
        { id: 3, kode_koperasi: 'KOP-UMKM-MAJU', nama_koperasi: 'Koperasi UMKM Bina Mandiri', alamat: 'Jl. Trans Sulawesi, Boalemo', kabupaten: 'Kabupaten Boalemo', provinsi: 'Gorontalo', logo: 'https://images.unsplash.com/photo-1513519245088-0e12902e5a38?w=150', status: 'pending' },
        { id: 4, kode_koperasi: 'KOP-TANI-MAKMUR', nama_koperasi: 'Koperasi Tani Makmur Gorontalo', alamat: 'Kawasan Pertanian Raya, Kabila, Bone Bolango', kabupaten: 'Kabupaten Bone Bolango', provinsi: 'Gorontalo', logo: 'https://images.unsplash.com/photo-1500937386664-56d1dfef3854?w=150', status: 'aktif' }
    ];
    state.products = [
        { id: 1, koperasi_id: 1, kategori_id: 1, nama_produk: 'Beras Pandan Wangi 5kg', harga: 78000, stok: 40, deskripsi: 'Beras Pandan Wangi kualitas premium asli Gorontalo. Butiran bersih, pulen, dan harum alami.', foto: 'https://images.unsplash.com/photo-1586201375761-83865001e31c?w=500', rating: 4.9, tags: 'beras, sembako', status: 'aktif' },
        { id: 2, koperasi_id: 1, kategori_id: 1, nama_produk: 'Minyak Goreng Kita 2L', harga: 34000, stok: 100, deskripsi: 'Minyak goreng kelapa sawit berkualitas, jernih. Cocok untuk hidangan gorengan keluarga.', foto: 'https://images.unsplash.com/photo-1474979266404-7eaacbcd87c5?w=500', rating: 4.8, tags: 'minyak, sembako', status: 'aktif' },
        { id: 3, koperasi_id: 2, kategori_id: 3, nama_produk: 'Kaos Merah Putih Digital', harga: 95000, stok: 25, deskripsi: 'Kaos eksklusif Koperasi Merah Putih dengan bahan Cotton Combed 30s. Sablon plastisol.', foto: 'https://images.unsplash.com/photo-1521572267360-ee0c2909d518?w=500', rating: 5.0, tags: 'kaos, umkm', status: 'aktif' },
        { id: 4, koperasi_id: 2, kategori_id: 3, nama_produk: 'Tas Anyaman Bambu Limboto', harga: 120000, stok: 15, deskripsi: 'Tas anyaman bambu premium kerajinan tangan lokal Gorontalo. Kuat, awet, dan bergaya.', foto: 'https://images.unsplash.com/photo-1544816155-12df9643f363?w=500', rating: 4.7, tags: 'tas, anyaman', status: 'aktif' },
        { id: 5, koperasi_id: 2, kategori_id: 1, nama_produk: 'Kopi Arabika Pinogu 250g', harga: 75000, stok: 35, deskripsi: 'Kopi Arabika organik khas daerah terpencil Pinogu, Bone Bolango, Gorontalo. Diolah secara higienis.', foto: 'https://images.unsplash.com/photo-1559056199-641a0ac8b55e?w=500', rating: 4.9, tags: 'kopi, pinogu', status: 'aktif' },
        { id: 6, koperasi_id: 4, kategori_id: 4, nama_produk: 'Pupuk Organik Cair Makmur', harga: 45000, stok: 80, deskripsi: 'Pupuk organik cair formula khusus Koperasi Tani Makmur. Mempercepat pertumbuhan tanaman.', foto: 'https://images.unsplash.com/photo-1592417817098-8f3d6eb19675?w=500', rating: 4.8, tags: 'pupuk, tani', status: 'aktif' }
    ];
    state.orders = [
        { id: 1, invoice: 'INV-20260528-98F5B1', customer_id: 7, customer_name: 'Budi Santoso', koperasi_id: 2, total: 185000, status: 'completed', ongkir: 15000, kurir: 'KopExpress', alamat: 'Jl. Merdeka No. 45, Limboto, Gorontalo', created_at: '2026-05-28 14:22:00' },
        { id: 2, invoice: 'INV-20260529-00A2C9', customer_id: 8, customer_name: 'Siti Aminah', koperasi_id: 1, total: 127000, status: 'paid', ongkir: 15000, kurir: 'POS Indonesia', alamat: 'Jl. Nani Wartabone No. 100, Gorontalo', created_at: '2026-05-29 08:30:00' }
    ];
    state.auditLogs = [
        { id: 1, user_name: 'System Admin', role_name: 'Super Admin', action: 'Inisialisasi Sistem', notes: 'Melakukan seeding data awal portal.', created_at: '2026-05-29 08:00:00' },
        { id: 2, user_name: 'Hendra Wijaya', role_name: 'Admin', action: 'Verifikasi Koperasi', notes: 'Menyetujui pendaftaran Koperasi Pegawai KPRI Gorontalo.', created_at: '2026-05-29 08:15:00' }
    ];
    state.users = [
        { id: 1, nama: 'Yusuf Fikri', email: 'superadmin@kopdigi.id', role_name: 'Super Admin', koperasi_name: 'Dinas Pusat', status: 'active' },
        { id: 2, nama: 'Hendra Wijaya', email: 'dinas@kopdigi.id', role_name: 'Admin', koperasi_name: 'Dinas Gorontalo', status: 'active' },
        { id: 3, nama: 'Admin Koperasi Pegawai A', email: 'admin.kopa@kopdigi.id', role_name: 'User', koperasi_name: 'KPRI Gorontalo', status: 'active' },
        { id: 4, nama: 'Admin Koperasi Merah Putih', email: 'admin.kopmp@kopdigi.id', role_name: 'User', koperasi_name: 'Kop Merah Putih Sejahtera', status: 'active' },
        { id: 7, nama: 'Budi Santoso', email: 'budi@gmail.com', role_name: 'Customer', koperasi_name: '-', status: 'active' },
        { id: 8, nama: 'Siti Aminah', email: 'siti@gmail.com', role_name: 'Customer', koperasi_name: '-', status: 'active' }
    ];
}

// Stats & Dashboard Data Recalculation
function updateStatsDashboard() {
    // Recalculate Super Admin statistics
    const totalCoops = state.cooperatives.length;
    const activeCoops = state.cooperatives.filter(c => c.status === 'aktif').length;
    const pendingCoops = state.cooperatives.filter(c => c.status === 'pending').length;

    let revenue = 0;
    state.orders.forEach(o => {
        if (['paid', 'processing', 'shipped', 'completed'].includes(o.status)) {
            revenue += parseFloat(o.total);
        }
    });

    const sCoopTotal = document.getElementById('s-stat-total-coops');
    if (sCoopTotal) sCoopTotal.innerText = totalCoops;
    const sSalesTotal = document.getElementById('s-stat-total-sales');
    if (sSalesTotal) sSalesTotal.innerText = 'Rp ' + revenue.toLocaleString('id-ID');

    // Dinas Admin stats
    const dActive = document.getElementById('d-stat-active-coops');
    if (dActive) dActive.innerText = activeCoops;
    const dPending = document.getElementById('d-stat-pending-coops');
    if (dPending) dPending.innerText = pendingCoops;

    // Coop Admin stats
    let coopSales = 0;
    let coopSuccess = 0;
    state.orders.forEach(o => {
        if (o.koperasi_id == state.coopId) {
            coopSales += parseFloat(o.total);
            if (o.status === 'completed') {
                coopSuccess++;
            }
        }
    });

    const cSales = document.getElementById('c-stat-sales');
    if (cSales) cSales.innerText = 'Rp ' + coopSales.toLocaleString('id-ID');
    const cOrders = document.getElementById('c-stat-orders');
    if (cOrders) cOrders.innerText = coopSuccess;
}

// Sidebars & Workspaces Setup
function setupEventListeners() {
    // Role selector switcher
    const switcher = document.getElementById('role-switcher');
    switcher.addEventListener('change', (e) => {
        const role = e.target.value;
        state.activeRole = role;
        
        // Hide all sidebar menu groups
        document.querySelectorAll('.sidebar-menu-group').forEach(el => el.style.display = 'none');
        // Show selected group
        document.getElementById(`menu-${role}`).style.display = 'block';

        // Select the first tab of this role
        const activeTabBtn = document.querySelector(`#menu-${role} .menu-item`);
        if (activeTabBtn) {
            document.querySelectorAll('.menu-item').forEach(el => el.classList.remove('active'));
            activeTabBtn.classList.add('active');
            state.activeTab = activeTabBtn.dataset.tab;
        }
        
        // Context setup for Coop Admin
        if (role === 'coopadmin') {
            const activeCoop = state.cooperatives.find(c => c.id == state.coopId);
            if (activeCoop) {
                document.getElementById('c-store-title-dashboard').innerText = 'Dashboard ' + activeCoop.nama_koperasi;
                document.getElementById('c-store-badge-dashboard').innerText = 'Koperasi ' + activeCoop.status;
            }
        }

        logConsole(`Beralih workspace admin: ${role.toUpperCase()}`);
        renderWorkspace();
    });

    // Sidebar tab clicks
    document.querySelectorAll('.menu-item').forEach(btn => {
        btn.addEventListener('click', (e) => {
            document.querySelectorAll('.menu-item').forEach(el => el.classList.remove('active'));
            const clicked = e.currentTarget;
            clicked.classList.add('active');
            state.activeTab = clicked.dataset.tab;
            
            renderWorkspace();
        });
    });

    // Mobile Phone Bottom Nav clicks
    document.querySelectorAll('.phone-bottom-nav .nav-tab').forEach(tab => {
        tab.addEventListener('click', (e) => {
            document.querySelectorAll('.phone-bottom-nav .nav-tab').forEach(el => el.classList.remove('active'));
            const clicked = e.currentTarget;
            clicked.classList.add('active');
            state.activePhoneTab = clicked.dataset.tab;

            // Route simulator view
            if (clicked.dataset.tab === 'home') {
                state.currentPhoneView = 'home';
            } else if (clicked.dataset.tab === 'koperasi') {
                state.currentPhoneView = 'coop-select';
            } else if (clicked.dataset.tab === 'history') {
                state.currentPhoneView = 'history';
            } else if (clicked.dataset.tab === 'ai-cs') {
                state.currentPhoneView = 'chat';
            }
            renderPhoneScreen();
        });
    });

    // Workspace panel scroll detection for sticky drawer header
    document.querySelectorAll('.workspace-panel').forEach(panel => {
        panel.addEventListener('scroll', () => {
            const header = panel.querySelector('.panel-header');
            if (header) {
                if (panel.scrollTop > 10) {
                    header.classList.add('is-scrolled');
                } else {
                    header.classList.remove('is-scrolled');
                }
            }
        });
    });
}

// Workspace Panels Switcher
function renderWorkspace() {
    // Hide all workspace panels
    document.querySelectorAll('.workspace-panel').forEach(panel => panel.style.display = 'none');

    // Show active panel
    const activePanel = document.getElementById(`${state.activeTab}-panel`);
    if (activePanel) {
        activePanel.style.display = 'flex';
        // Reset or apply scrolled state for new active panel
        const header = activePanel.querySelector('.panel-header');
        if (header) {
            if (activePanel.scrollTop > 10) {
                header.classList.add('is-scrolled');
            } else {
                header.classList.remove('is-scrolled');
            }
        }
    }

    // Update active workspace badge in top navbar
    const activeBadge = document.getElementById('active-workspace-badge');
    if (activeBadge) {
        if (state.activeRole === 'superadmin') {
            activeBadge.innerText = 'Super Admin';
        } else if (state.activeRole === 'dinasadmin') {
            activeBadge.innerText = 'Admin Dinas Koperasi';
        } else if (state.activeRole === 'coopadmin') {
            const coop = state.cooperatives.find(c => c.id == state.coopId);
            activeBadge.innerText = coop ? coop.nama_koperasi : 'Admin Koperasi';
        }
    }

    // Render contents specifically for active tabs
    switch (state.activeTab) {
        // Super Admin Workspace
        case 'super-dashboard':
            renderSuperDashboardRegions();
            break;
        case 'super-coops-daftar':
            renderSuperCoopsList();
            break;
        case 'super-coops-verif':
            renderSuperCoopsVerif();
            break;
        case 'super-coops-wilayah':
            renderSuperCoopsWilayah();
            break;
        case 'super-users':
            renderSuperUsersTable();
            break;
        case 'super-users-verif':
            renderSuperUsersVerifTable();
            break;
        case 'super-permissions':
            renderSuperPermissionsTable();
            break;
        case 'super-settings':
            loadSystemSettings();
            break;
        case 'super-products':
            renderSuperProductsTable();
            break;
        case 'super-orders':
            renderSuperOrdersTable();
            break;
        case 'super-reports':
            renderSuperReports();
            break;
        case 'super-audit':
            renderSuperAuditTable();
            break;

        // Dinas Admin Workspace
        case 'dinas-dashboard':
            renderDinasPendingCoops();
            break;
        case 'dinas-coops-daftar':
            renderDinasAllCoops();
            break;
        case 'dinas-coops-verif':
            renderDinasLegalCoops();
            break;
        case 'dinas-products':
            renderDinasProductsTable();
            break;
        case 'dinas-orders':
            renderDinasOrdersTable();
            break;

        // Coop Admin Workspace
        case 'coop-dashboard':
            renderCoopDashboardIncoming();
            break;
        case 'coop-profile':
            renderCoopProfileData();
            break;
        case 'coop-products-daftar':
            renderCoopProductsDaftar();
            break;
        case 'coop-messages':
            renderSellerInbox();
            break;
        case 'coop-orders':
            renderCoopIncomingOrdersFull();
            break;
        case 'coop-shipping':
            renderCoopShippingData();
            break;
        case 'coop-reports':
            renderCoopReportsSummary();
            break;
        case 'coop-customers':
            renderCoopCustomersList();
            break;
        case 'coop-settings':
            initCoopSettings();
            break;
    }
}

/* ----------------------------------------------------
 * WEB WORKSPACE RENDERERS (DOM Injection)
 * ---------------------------------------------------- */

// 1. Super Admin tabs
function renderSuperDashboardRegions() {
    const tbody = document.getElementById('s-regions-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    state.regions.forEach(r => {
        const activeCount = state.cooperatives.filter(c => c.kabupaten === r.nama_wilayah && c.status === 'aktif').length;
        const pendingCount = state.cooperatives.filter(c => c.kabupaten === r.nama_wilayah && c.status === 'pending').length;
        
        let statusStr = '';
        if (activeCount > 0) statusStr += `${activeCount} Unit Aktif`;
        if (pendingCount > 0) {
            if (statusStr) statusStr += ' / ';
            statusStr += `${pendingCount} Unit Pending`;
        }
        if (!statusStr) statusStr = '0 Unit';

        tbody.innerHTML += `
            <tr>
                <td class="py-3 px-4 text-slate-100 font-semibold">${r.nama_wilayah}</td>
                <td class="py-3 px-4 text-slate-400">${r.provinsi}</td>
                <td class="py-3 px-4 text-emerald-400 font-medium">${statusStr}</td>
            </tr>
        `;
    });
}

function renderSuperCoopsList() {
    const tbody = document.getElementById('s-coops-list-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    
    if (state.cooperatives.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center py-4 text-slate-500">Belum ada data koperasi.</td></tr>';
        return;
    }

    state.cooperatives.forEach(c => {
        let badgeClass = 'pending';
        if (c.status === 'aktif') badgeClass = 'approved';
        if (c.status === 'nonaktif') badgeClass = 'rejected';

        tbody.innerHTML += `
            <tr class="border-b border-slate-800/40">
                <td class="py-3 px-4"><img src="${c.logo}" style="width: 32px; height: 32px; border-radius: 6px; object-fit: cover;"></td>
                <td class="py-3 px-4"><strong class="text-slate-200">${c.kode_koperasi}</strong></td>
                <td class="py-3 px-4 text-slate-300">${c.nama_koperasi}</td>
                <td class="py-3 px-4 text-slate-400">${c.kabupaten}</td>
                <td class="py-3 px-4"><span class="badge ${badgeClass}">${c.status.toUpperCase()}</span></td>
                <td class="py-3 px-4">
                    <div class="flex gap-2">
                        <button class="px-2.5 py-1.5 bg-blue-600/90 hover:bg-blue-500 text-white rounded-xl text-[10px] font-bold transition flex items-center gap-1" onclick="openEditCoopModal(${c.id})">
                            <span class="material-symbols-outlined text-[12px]">edit</span>
                            <span>EDIT</span>
                        </button>
                        <button class="px-2.5 py-1.5 bg-rose-600/95 hover:bg-rose-500 text-white rounded-xl text-[10px] font-bold transition flex items-center gap-1" onclick="deleteCooperative(${c.id})">
                            <span class="material-symbols-outlined text-[12px]">delete</span>
                            <span>HAPUS</span>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
}

async function toggleCoopStatus(id, newStatus) {
    try {
        const userSession = JSON.parse(localStorage.getItem('web_user') || '{}');
        const userId = userSession.id || 1;

        await fetch(`/api/cooperatives/${id}/status`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `status=${newStatus}&user_id=${userId}`
        });
    } catch (e) {}
    
    // Local update
    const coop = state.cooperatives.find(c => c.id == id);
    if (coop) {
        coop.status = newStatus;
        logConsole(`Status koperasi "${coop.nama_koperasi}" diubah menjadi ${newStatus.toUpperCase()}`);
    }
    await loadAllData();
}

function renderSuperCoopsVerif() {
    const tbody = document.getElementById('s-coops-verif-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    
    const pending = state.cooperatives.filter(c => c.status === 'pending');
    if (!pending.length) {
        tbody.innerHTML = '<tr><td colspan="5" class="text-center py-4 text-slate-500">Tidak ada pengajuan koperasi baru.</td></tr>';
        return;
    }
    
    pending.forEach(c => {
        tbody.innerHTML += `
            <tr class="border-b border-slate-800/40">
                <td class="py-3 px-4"><strong class="text-slate-200">${c.kode_koperasi}</strong></td>
                <td class="py-3 px-4 text-slate-300">${c.nama_koperasi}</td>
                <td class="py-3 px-4 text-slate-400">${c.alamat} (${c.kabupaten})</td>
                <td class="py-3 px-4"><span class="badge pending">PENDING REVIEW</span></td>
                <td class="py-3 px-4">
                    <div class="flex gap-2">
                        <button class="px-2.5 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white rounded-xl text-[10px] font-bold transition flex items-center gap-1" onclick="toggleCoopStatus(${c.id}, 'aktif')">
                            <span class="material-symbols-outlined text-[12px]">check_circle</span>
                            <span>SETUJUI</span>
                        </button>
                        <button class="px-2.5 py-1.5 bg-amber-600 hover:bg-amber-500 text-white rounded-xl text-[10px] font-bold transition flex items-center gap-1" onclick="toggleCoopStatus(${c.id}, 'nonaktif')">
                            <span class="material-symbols-outlined text-[12px]">cancel</span>
                            <span>TOLAK</span>
                        </button>
                        <button class="px-2.5 py-1.5 bg-rose-700 hover:bg-rose-600 text-white rounded-xl text-[10px] font-bold transition flex items-center gap-1" onclick="deleteCooperative(${c.id})">
                            <span class="material-symbols-outlined text-[12px]">delete_forever</span>
                            <span>HAPUS</span>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
}

function renderSuperUsersTable() {
    const tbody = document.getElementById('s-users-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    
    const usersList = (Array.isArray(state.users) && state.users.length) ? state.users : [
        { id: 1, nama: 'Yusuf Fikri', email: 'superadmin@kopdigi.id', role_name: 'Super Admin', koperasi_name: 'Dinas Pusat', status: 'active', role_id: 1, koperasi_id: null },
        { id: 2, nama: 'Hendra Wijaya', email: 'dinas@kopdigi.id', role_name: 'Admin', koperasi_name: 'Dinas Gorontalo', status: 'active', role_id: 2, koperasi_id: null },
        { id: 3, nama: 'Admin KPRI Gorontalo', email: 'admin.kopa@kopdigi.id', role_name: 'User', koperasi_name: 'KPRI Gorontalo', status: 'active', role_id: 3, koperasi_id: 1 },
        { id: 7, nama: 'Budi Santoso', email: 'budi@gmail.com', role_name: 'Customer', koperasi_name: '-', status: 'active', role_id: 4, koperasi_id: null }
    ];

    usersList.forEach(u => {
        // Map status badges
        let statusBadge = u.status === 'active' ? '<span class="px-2 py-0.5 bg-emerald-950/40 text-emerald-400 border border-emerald-800/30 rounded-full text-[10px] font-bold">ACTIVE</span>' : '<span class="px-2 py-0.5 bg-rose-950/40 text-rose-400 border border-rose-800/30 rounded-full text-[10px] font-bold">SUSPENDED</span>';

        // Map role badges
        let roleBadge = '';
        if (u.role_name === 'Super Admin') {
            roleBadge = '<span class="px-2 py-0.5 bg-rose-950/40 text-primary border border-rose-800/30 rounded-full text-[10px] font-bold">Super Admin</span>';
        } else if (u.role_name === 'Admin') {
            roleBadge = '<span class="px-2 py-0.5 bg-blue-950/40 text-blue-400 border border-blue-800/30 rounded-full text-[10px] font-bold">Admin</span>';
        } else if (u.role_name === 'User') {
            roleBadge = '<span class="px-2 py-0.5 bg-amber-950/40 text-amber-400 border border-amber-800/30 rounded-full text-[10px] font-bold">User</span>';
        } else {
            roleBadge = '<span class="px-2 py-0.5 bg-slate-800 text-slate-400 border border-slate-700/60 rounded-full text-[10px] font-bold">Customer</span>';
        }

        tbody.innerHTML += `
            <tr class="hover:bg-slate-800/10">
                <td class="py-3.5 px-4 text-slate-400 font-medium">${u.id}</td>
                <td class="py-3.5 px-4 font-bold text-white">${u.nama}</td>
                <td class="py-3.5 px-4 text-slate-300 font-mono text-xs">${u.email}</td>
                <td class="py-3.5 px-4 text-slate-400">${u.koperasi_name || '-'}</td>
                <td class="py-3.5 px-4">${roleBadge}</td>
                <td class="py-3.5 px-4">${statusBadge}</td>
                <td class="py-3.5 px-4 text-center">
                    <button onclick="openEditUserModal(${u.id})" class="mx-auto px-2 py-1 bg-slate-800 hover:bg-primary/20 hover:text-primary hover:border-primary/40 border border-slate-700 rounded-lg text-[10px] font-bold flex items-center justify-center gap-1 transition duration-150">
                        <span class="material-symbols-outlined text-[12px]">edit</span>
                        <span>Ubah</span>
                    </button>
                </td>
            </tr>
        `;
    });
}

function renderSuperProductsTable() {
    const tbody = document.getElementById('s-products-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    state.products.forEach(p => {
        const coop = state.cooperatives.find(c => c.id == p.koperasi_id);
        tbody.innerHTML += `
            <tr>
                <td><img src="${p.foto}" style="width: 32px; height: 32px; border-radius: 6px; object-fit: cover;"></td>
                <td><strong>${p.nama_produk}</strong></td>
                <td>${coop ? coop.nama_koperasi : 'Koperasi'}</td>
                <td>Rp ${Number(p.harga).toLocaleString('id-ID')}</td>
                <td>${p.stok} pcs</td>
                <td>⭐ ${p.rating}</td>
                <td><span class="badge approved">AKTIF</span></td>
            </tr>
        `;
    });
}function renderSuperOrdersTable() {
    const tbody = document.getElementById('s-orders-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    state.orders.forEach(o => {
        const coop = state.cooperatives.find(c => c.id == o.koperasi_id);
        tbody.innerHTML += `
            <tr>
                <td><strong>${o.invoice}</strong></td>
                <td>${coop ? coop.nama_koperasi : 'Koperasi'}</td>
                <td>${o.customer_name || 'Customer'}</td>
                <td>${o.kurir}</td>
                <td style="font-weight: 700; color: #E11D48;">Rp ${Number(o.total).toLocaleString('id-ID')}</td>
                <td>${getStatusBadge(o.status)}</td>
            </tr>
        `;
    });
}

function renderSuperAuditTable() {
    const tbody = document.getElementById('s-audit-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    state.auditLogs.forEach(l => {
        tbody.innerHTML += `
            <tr>
                <td>${l.created_at}</td>
                <td><strong>${l.user_name || 'System Admin'}</strong></td>
                <td>${l.role_name || 'Super Admin'}</td>
                <td><span class="badge lvl1">${l.action}</span></td>
                <td>${l.notes}</td>
            </tr>
        `;
    });
}

// 2. Dinas Admin tabs
function renderDinasPendingCoops() {
    const tbody = document.getElementById('d-coops-pending-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    const pending = state.cooperatives.filter(c => c.status === 'pending');
    if (!pending.length) {
        tbody.innerHTML = '<tr><td colspan="5" style="text-align: center;">Tidak ada pengajuan koperasi baru.</td></tr>';
        return;
    }
    pending.forEach(c => {
        tbody.innerHTML += `
            <tr>
                <td><strong>${c.kode_koperasi}</strong></td>
                <td>${c.nama_koperasi}</td>
                <td>${c.kabupaten}</td>
                <td><span class="badge pending">PENDING VERIFIKASI</span></td>
                <td>
                    <button class="btn btn-sm btn-primary" onclick="toggleCoopStatus(${c.id}, 'aktif')">Setujui & Aktifkan</button>
                </td>
            </tr>
        `;
    });
}

function renderDinasAllCoops() {
    const tbody = document.getElementById('d-coops-all-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    state.cooperatives.forEach(c => {
        tbody.innerHTML += `
            <tr>
                <td><strong>${c.kode_koperasi}</strong></td>
                <td>${c.nama_koperasi}</td>
                <td>${c.kabupaten}</td>
                <td>${c.created_at || '2026-05-29'}</td>
                <td><span class="badge ${c.status === 'aktif' ? 'approved' : 'pending'}">${c.status.toUpperCase()}</span></td>
            </tr>
        `;
    });
}

function renderDinasLegalCoops() {
    const tbody = document.getElementById('d-coops-legal-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    state.cooperatives.forEach(c => {
        tbody.innerHTML += `
            <tr>
                <td><strong>${c.nama_koperasi}</strong></td>
                <td>${c.kabupaten}</td>
                <td><span class="badge ${c.status === 'aktif' ? 'approved' : 'pending'}">${c.status.toUpperCase()}</span></td>
                <td>
                    <button class="btn btn-sm btn-primary" onclick="toggleCoopStatus(${c.id}, 'aktif')">Sahkan Koperasi</button>
                </td>
            </tr>
        `;
    });
}

function renderDinasProductsTable() {
    const tbody = document.getElementById('d-products-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    state.products.forEach(p => {
        const coop = state.cooperatives.find(c => c.id == p.koperasi_id);
        tbody.innerHTML += `
            <tr>
                <td><img src="${p.foto}" style="width: 32px; height: 32px; border-radius: 6px; object-fit: cover;"></td>
                <td><strong>${p.nama_produk}</strong></td>
                <td>${coop ? coop.nama_koperasi : 'Koperasi'}</td>
                <td>Rp ${Number(p.harga).toLocaleString('id-ID')}</td>
                <td>${p.stok} pcs</td>
                <td><span class="badge approved">AKTIF</span></td>
            </tr>
        `;
    });
}

function renderDinasOrdersTable() {
    const tbody = document.getElementById('d-orders-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    state.orders.forEach(o => {
        const coop = state.cooperatives.find(c => c.id == o.koperasi_id);
        tbody.innerHTML += `
            <tr>
                <td><strong>${o.invoice}</strong></td>
                <td>${coop ? coop.nama_koperasi : 'Koperasi'}</td>
                <td>Rp ${Number(o.total).toLocaleString('id-ID')}</td>
                <td>${getStatusBadge(o.status)}</td>
            </tr>
        `;
    });
}

// 3. Admin Koperasi tabs
function renderCoopDashboardIncoming() {
    const tbody = document.getElementById('c-incoming-orders-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    const incoming = state.orders.filter(o => o.koperasi_id == state.coopId && !['COMPLETED', 'CANCELLED_BY_CUSTOMER', 'REJECTED_BY_SELLER', 'PAYMENT_FAILED', 'REFUNDED'].includes(o.status));
    if (!incoming.length) {
        tbody.innerHTML = '<tr><td colspan="5" style="text-align: center;">Tidak ada pesanan masuk aktif.</td></tr>';
        return;
    }
    incoming.forEach(o => {
        let actionButtons = '';
        if (o.status === 'WAITING_PROCESS' || o.status === 'paid' || o.status === 'processing') {
            actionButtons = `
                <button class="btn btn-sm btn-primary text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'VERIFIKASI_KOPERASI')">Verifikasi Pesanan</button>
                <button class="btn btn-sm btn-danger text-[10px] font-bold uppercase py-1 ml-1.5" onclick="updateOrderStatus(${o.id}, 'REJECTED_BY_SELLER')">Tolak</button>
            `;
        } else if (o.status === 'PAYMENT_VERIFIED') {
            actionButtons = `
                <button class="btn btn-sm btn-primary text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'VERIFIKASI_KOPERASI')">Verifikasi Pesanan</button>
            `;
        } else if (o.status === 'VERIFIKASI_KOPERASI') {
            actionButtons = `<button class="btn btn-sm btn-primary bg-fuchsia-600 border-fuchsia-600 hover:bg-fuchsia-700 text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'PACKING')">Kemas Barang</button>`;
        } else if (o.status === 'PACKING') {
            actionButtons = `<button class="btn btn-sm btn-primary bg-cyan-600 border-cyan-600 hover:bg-cyan-700 text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'READY_TO_SHIP')">Siap Kirim</button>`;
        } else if (o.status === 'READY_TO_SHIP') {
            actionButtons = `<button class="btn btn-sm btn-primary bg-sky-600 border-sky-600 hover:bg-sky-700 text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'SHIPPED')">Serahkan ke Kurir</button>`;
        } else if (o.status === 'SHIPPED') {
            actionButtons = `<button class="btn btn-sm btn-accent text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'IN_TRANSIT')">Simulasikan Transit</button>`;
        } else if (o.status === 'IN_TRANSIT') {
            actionButtons = `<button class="btn btn-sm btn-accent text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'ARRIVED_DESTINATION')">Simulasikan Tiba</button>`;
        } else if (o.status === 'ARRIVED_DESTINATION') {
            actionButtons = `<button class="btn btn-sm btn-accent text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'OUT_FOR_DELIVERY')">Simulasikan Diantar</button>`;
        } else if (o.status === 'OUT_FOR_DELIVERY') {
            actionButtons = `<button class="btn btn-sm btn-accent text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'DELIVERED')">Simulasikan Diterima</button>`;
        } else if (o.status === 'RETURN_REQUEST') {
            actionButtons = `
                <button class="btn btn-sm btn-primary text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'RETURN_APPROVED')">Setujui Retur</button>
                <button class="btn btn-sm btn-danger text-[10px] font-bold uppercase py-1 ml-1.5" onclick="updateOrderStatus(${o.id}, 'REJECTED_BY_SELLER')">Tolak Retur</button>
            `;
        } else if (o.status === 'RETURN_APPROVED') {
            actionButtons = `<button class="btn btn-sm btn-primary bg-slate-650 border-slate-650 hover:bg-slate-700 text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'REFUNDED')">Kembalikan Dana</button>`;
        } else if (o.status === 'PENDING_PAYMENT') {
            actionButtons = `<span class="text-slate-500 font-semibold text-[10px]">Menunggu Pembayaran</span>`;
        } else {
            actionButtons = `<span class="text-slate-500 font-semibold text-[10px]">-</span>`;
        }

        tbody.innerHTML += `
            <tr>
                <td><strong>${o.invoice}</strong></td>
                <td>${o.customer_name || 'Customer'}</td>
                <td style="font-weight: 700;">Rp ${Number(o.total).toLocaleString('id-ID')}</td>
                <td>${getStatusBadge(o.status)}</td>
                <td>
                    ${actionButtons}
                </td>
            </tr>
        `;
    });
}

async function updateOrderStatus(id, newStatus) {
    await updateOrderStatusLocalAndRemote(id, newStatus);
}

function renderCoopProfileData() {
    const coop = state.cooperatives.find(c => c.id == state.coopId);
    if (!coop) return;
    
    document.getElementById('c-profile-id').value = coop.id;
    document.getElementById('c-profile-nama').value = coop.nama_koperasi;
    document.getElementById('c-profile-kode').value = coop.kode_koperasi;
    document.getElementById('c-profile-kab').value = coop.kabupaten;
    document.getElementById('c-profile-prov').value = coop.provinsi;
    document.getElementById('c-profile-alamat').value = coop.alamat;
    document.getElementById('c-profile-logo').value = coop.logo;
}

async function saveCoopProfile() {
    const id = document.getElementById('c-profile-id').value;
    const name = document.getElementById('c-profile-nama').value;
    const kab = document.getElementById('c-profile-kab').value;
    const prov = document.getElementById('c-profile-prov').value;
    const alamat = document.getElementById('c-profile-alamat').value;
    const logo = document.getElementById('c-profile-logo').value;

    try {
        await fetch(`/api/cooperatives/${id}/update`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `nama_koperasi=${encodeURIComponent(name)}&kabupaten=${encodeURIComponent(kab)}&provinsi=${encodeURIComponent(prov)}&alamat=${encodeURIComponent(alamat)}&logo=${encodeURIComponent(logo)}&user_id=${state.coopAdminId}`
        });
    } catch (e) {}

    const coop = state.cooperatives.find(c => c.id == id);
    if (coop) {
        coop.nama_koperasi = name;
        coop.kabupaten = kab;
        coop.provinsi = prov;
        coop.alamat = alamat;
        coop.logo = logo;
        logConsole('Profil koperasi berhasil diperbarui.');
    }
    loadAllData();
}

function renderCoopProductsDaftar() {
    const tbody = document.getElementById('c-products-list-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    const search = (document.getElementById('prod-search-input') || {value: ''}).value.toLowerCase();
    const catFilter = (document.getElementById('prod-filter-cat') || {value: ''}).value;
    let myProds = state.products.filter(p => p.koperasi_id == state.coopId);
    if (search) myProds = myProds.filter(p => p.nama_produk.toLowerCase().includes(search));
    if (catFilter) myProds = myProds.filter(p => p.kategori_id == catFilter);
    
    if (!myProds.length) {
        tbody.innerHTML = `<tr><td colspan="8" class="py-10 text-center text-slate-500 text-xs">Belum ada produk. <span class="text-primary cursor-pointer" onclick="switchTab('coop-products-add')">Tambah produk sekarang</span></td></tr>`;
        return;
    }
    const catNames = {1:'Sembako', 2:'Elektronik', 3:'UMKM', 4:'Pertanian'};
    myProds.forEach(p => {
        const stockClass = p.stok <= 5 ? 'text-rose-400 font-bold' : p.stok <= 20 ? 'text-amber-400 font-semibold' : 'text-emerald-400';
        const statusBadge = p.status === 'aktif'
            ? `<span class="px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-[10px] font-bold rounded-full">Aktif</span>`
            : `<span class="px-2 py-0.5 bg-slate-600/40 text-slate-400 text-[10px] font-bold rounded-full">Non-aktif</span>`;
        tbody.innerHTML += `
            <tr class="hover:bg-slate-800/30 transition">
                <td class="py-3 px-4">
                    <img src="${p.foto || 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=80'}" 
                         style="width:38px;height:38px;border-radius:8px;object-fit:cover;border:1px solid rgba(255,255,255,0.08)">
                </td>
                <td class="py-3 px-4">
                    <div class="font-semibold text-slate-100 text-xs max-w-[160px] truncate">${p.nama_produk}</div>
                    <div class="text-slate-500 text-[10px] mt-0.5 truncate max-w-[160px]">${p.tags || '-'}</div>
                </td>
                <td class="py-3 px-4 text-slate-400 text-xs">${catNames[p.kategori_id] || '-'}</td>
                <td class="py-3 px-4 text-white font-semibold text-xs">Rp ${Number(p.harga).toLocaleString('id-ID')}</td>
                <td class="py-3 px-4 text-xs ${stockClass}">${p.stok} pcs</td>
                <td class="py-3 px-4 text-amber-400 text-xs">⭐ ${p.rating}</td>
                <td class="py-3 px-4">${statusBadge}</td>
                <td class="py-3 px-4">
                    <div class="flex gap-1.5 justify-center">
                        <button onclick="openEditProductModal(${p.id})" title="Edit" class="p-1.5 rounded-lg bg-primary/20 text-primary hover:bg-primary/40 transition">
                            <span class="material-symbols-outlined text-sm">edit</span>
                        </button>
                        <button onclick="deleteCoopProduct(${p.id}, '${p.nama_produk.replace(/'/g, "\\'")}')" title="Hapus" class="p-1.5 rounded-lg bg-rose-500/20 text-rose-400 hover:bg-rose-500/40 transition">
                            <span class="material-symbols-outlined text-sm">delete</span>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
}

window.filterCoopProducts = function() {
    renderCoopProductsDaftar();
};

// AI Assistant box trigger
async function askSellerAi() {
    const kw = document.getElementById('ai-product-keyword').value;
    if (!kw) {
        alert('Masukkan kata kunci produk terlebih dahulu.');
        return;
    }
    const aiOutput = document.getElementById('ai-product-output');
    aiOutput.style.display = 'block';
    aiOutput.innerHTML = '<div style="color:var(--primary);">KopMerahPutih AI sedang menyusun deskripsi produk...</div>';

    try {
        const response = await fetch('/api/ai/seller-assistant', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `keywords=${encodeURIComponent(kw)}`
        });
        const res = await response.json();
        
        if (response.ok) {
            aiOutput.innerHTML = `
                <div style="font-size:0.7rem; color:var(--primary); font-weight:700; margin-bottom:0.4rem;">MODEL AI: ${res.ai_model}</div>
                <div style="font-weight:700; font-size:0.8rem; margin-bottom:4px;">Rekomendasi Judul:</div>
                <div style="background:rgba(255,255,255,0.05); padding:6px; border-radius:6px; margin-bottom:8px; border:1px solid var(--border-color); font-weight:600;">${res.generated.title}</div>
                <div style="font-weight:700; font-size:0.8rem; margin-bottom:4px;">Rekomendasi Deskripsi:</div>
                <div style="background:rgba(255,255,255,0.05); padding:6px; border-radius:6px; margin-bottom:8px; border:1px solid var(--border-color); font-size:0.75rem; white-space:pre-line;">${res.generated.description}</div>
                <button class="btn btn-sm btn-primary" onclick="useAiContent('${res.generated.title.replace(/'/g, "\\'")}', '${res.generated.description.replace(/\n/g, '\\n').replace(/'/g, "\\'")}', '${res.generated.tags}')" style="width:100%;">Terapkan Content Ke Form</button>
            `;
        }
    } catch (e) {
        aiOutput.innerHTML = '<div style="color:var(--danger)">Koneksi AI Writer Terputus.</div>';
    }
}

window.useAiContent = function(title, description, tags) {
    document.getElementById('c-new-prod-name').value = title;
    document.getElementById('c-new-prod-desc').value = description;
    document.getElementById('c-new-prod-tags').value = tags;
    document.getElementById('ai-product-output').style.display = 'none';
    document.getElementById('ai-product-keyword').value = '';
    logConsole('AI Content berhasil diterapkan ke form manual.');
};

window.handleProductImageUpload = async function(input, inputId = 'c-new-prod-foto', previewId = 'c-new-prod-preview', imgId = 'c-new-prod-preview-img') {
    if (!input.files || input.files.length === 0) return;
    const file = input.files[0];
    
    // Show preview immediately
    const previewUrl = URL.createObjectURL(file);
    const previewContainer = document.getElementById(previewId);
    const previewImg = document.getElementById(imgId);
    if (previewContainer && previewImg) {
        previewContainer.classList.remove('hidden');
        previewImg.src = previewUrl;
    }
    
    // Set loading text
    const urlInput = document.getElementById(inputId);
    if (!urlInput) return;
    urlInput.value = 'Sedang mengunggah...';
    urlInput.disabled = true;

    // Upload to server
    const formData = new FormData();
    formData.append('image', file);

    try {
        const res = await fetch('/api/upload/image', {
            method: 'POST',
            body: formData
        });
        const data = await res.json();
        if (data.status === 'success') {
            urlInput.value = data.url;
        } else {
            urlInput.value = '';
            alert(data.message || 'Gagal mengunggah gambar');
        }
    } catch(e) {
        urlInput.value = '';
        alert('Terjadi kesalahan saat unggah gambar');
    }
    urlInput.disabled = false;
};

async function submitNewProduct() {
    const name = document.getElementById('c-new-prod-name').value;
    const cat = document.getElementById('c-new-prod-cat').value;
    const price = document.getElementById('c-new-prod-price').value;
    const satuan = document.getElementById('c-new-prod-satuan').value;
    const stock = document.getElementById('c-new-prod-stock').value;
    const foto = document.getElementById('c-new-prod-foto').value || 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=500';
    const tags = document.getElementById('c-new-prod-tags').value;
    const desc = document.getElementById('c-new-prod-desc').value;

    if (!name || !price || !stock) {
        alert('Form input nama, harga, dan stok wajib diisi.');
        return;
    }

    try {
        await fetch('/api/products', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `koperasi_id=${state.coopId}&category_id=${cat}&name=${encodeURIComponent(name)}&price=${price}&satuan=${encodeURIComponent(satuan)}&stock=${stock}&description=${encodeURIComponent(desc)}&image=${encodeURIComponent(foto)}&tags=${encodeURIComponent(tags)}&user_id=${state.coopAdminId}`
        });
    } catch(e) {}

    // Local Insert
    const newId = state.products.length + 1;
    state.products.push({
        id: newId,
        koperasi_id: state.coopId,
        kategori_id: parseInt(cat),
        nama_produk: name,
        harga: parseFloat(price),
        satuan: satuan,
        stok: parseInt(stock),
        deskripsi: desc,
        foto: foto,
        rating: 5.00,
        tags: tags,
        status: 'aktif'
    });

    logConsole(`Produk "${name}" berhasil di-publish ke marketplace.`);
    
    // Clear inputs
    document.getElementById('c-new-prod-name').value = '';
    document.getElementById('c-new-prod-price').value = '';
    document.getElementById('c-new-prod-stock').value = '';
    document.getElementById('c-new-prod-tags').value = '';
    document.getElementById('c-new-prod-desc').value = '';
    document.getElementById('c-new-prod-foto').value = '';
    document.getElementById('c-new-prod-preview').classList.add('hidden');
    document.getElementById('c-new-prod-preview-img').src = '';

    loadAllData();
    state.activeTab = 'coop-products-daftar';
    renderWorkspace();
}

function renderCoopIncomingOrdersFull() {
    const tbody = document.getElementById('c-orders-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    const myOrders = state.orders.filter(o => o.koperasi_id == state.coopId);
    if (!myOrders.length) {
        tbody.innerHTML = '<tr><td colspan="5" style="text-align: center;">Tidak ada transaksi masuk.</td></tr>';
        return;
    }
    myOrders.forEach(o => {
        let actionButtons = '';
        if (o.status === 'WAITING_PROCESS' || o.status === 'paid' || o.status === 'processing') {
            actionButtons = `
                <button class="btn btn-sm btn-primary text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'VERIFIKASI_KOPERASI')">Verifikasi Pesanan</button>
                <button class="btn btn-sm btn-danger text-[10px] font-bold uppercase py-1 ml-1.5" onclick="updateOrderStatus(${o.id}, 'REJECTED_BY_SELLER')">Tolak</button>
            `;
        } else if (o.status === 'PAYMENT_VERIFIED') {
            actionButtons = `
                <button class="btn btn-sm btn-primary text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'VERIFIKASI_KOPERASI')">Verifikasi Pesanan</button>
            `;
        } else if (o.status === 'VERIFIKASI_KOPERASI') {
            actionButtons = `<button class="btn btn-sm btn-primary bg-fuchsia-600 border-fuchsia-600 hover:bg-fuchsia-700 text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'PACKING')">Kemas Barang</button>`;
        } else if (o.status === 'PACKING') {
            actionButtons = `<button class="btn btn-sm btn-primary bg-cyan-600 border-cyan-600 hover:bg-cyan-700 text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'READY_TO_SHIP')">Siap Kirim</button>`;
        } else if (o.status === 'READY_TO_SHIP') {
            actionButtons = `<button class="btn btn-sm btn-primary bg-sky-600 border-sky-600 hover:bg-sky-700 text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'SHIPPED')">Serahkan ke Kurir</button>`;
        } else if (o.status === 'SHIPPED') {
            actionButtons = `<button class="btn btn-sm btn-accent text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'IN_TRANSIT')">Simulasikan Transit</button>`;
        } else if (o.status === 'IN_TRANSIT') {
            actionButtons = `<button class="btn btn-sm btn-accent text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'ARRIVED_DESTINATION')">Simulasikan Tiba</button>`;
        } else if (o.status === 'ARRIVED_DESTINATION') {
            actionButtons = `<button class="btn btn-sm btn-accent text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'OUT_FOR_DELIVERY')">Simulasikan Diantar</button>`;
        } else if (o.status === 'OUT_FOR_DELIVERY') {
            actionButtons = `<button class="btn btn-sm btn-accent text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'DELIVERED')">Simulasikan Diterima</button>`;
        } else if (o.status === 'RETURN_REQUEST') {
            actionButtons = `
                <button class="btn btn-sm btn-primary text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'RETURN_APPROVED')">Setujui Retur</button>
                <button class="btn btn-sm btn-danger text-[10px] font-bold uppercase py-1 ml-1.5" onclick="updateOrderStatus(${o.id}, 'REJECTED_BY_SELLER')">Tolak Retur</button>
            `;
        } else if (o.status === 'RETURN_APPROVED') {
            actionButtons = `<button class="btn btn-sm btn-primary bg-slate-650 border-slate-650 hover:bg-slate-700 text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'REFUNDED')">Kembalikan Dana</button>`;
        } else if (o.status === 'PENDING_PAYMENT') {
            actionButtons = `<span class="text-slate-500 font-semibold text-[10px]">Menunggu Pembayaran</span>`;
        } else {
            actionButtons = `<span class="text-slate-500 font-semibold text-[10px]">-</span>`;
        }

        tbody.innerHTML += `
            <tr>
                <td><strong>${o.invoice}</strong></td>
                <td>${o.customer_name || 'Customer'}</td>
                <td style="font-weight: 700;">Rp ${Number(o.total).toLocaleString('id-ID')}</td>
                <td>${getStatusBadge(o.status)}</td>
                <td>
                    ${actionButtons}
                </td>
            </tr>
        `;
    });
}

function renderCoopShippingData() {
    const tbody = document.getElementById('c-shipping-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    const myOrders = state.orders.filter(o => o.koperasi_id == state.coopId && ['READY_TO_SHIP', 'SHIPPED', 'IN_TRANSIT', 'ARRIVED_DESTINATION', 'OUT_FOR_DELIVERY', 'DELIVERED', 'COMPLETED'].includes(o.status));
    if (!myOrders.length) {
        tbody.innerHTML = '<tr><td colspan="5" style="text-align: center;">Tidak ada data pengiriman aktif.</td></tr>';
        return;
    }
    myOrders.forEach(o => {
        let action = '';
        if (o.status === 'READY_TO_SHIP') {
            action = `<button class="btn btn-sm btn-accent text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'SHIPPED')">Kirim Kurir Resi-KOPEX123</button>`;
        } else if (o.status === 'SHIPPED') {
            action = `<button class="btn btn-sm btn-primary text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'IN_TRANSIT')">Simulasikan Transit</button>`;
        } else if (o.status === 'IN_TRANSIT') {
            action = `<button class="btn btn-sm btn-primary text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'ARRIVED_DESTINATION')">Simulasikan Tiba</button>`;
        } else if (o.status === 'ARRIVED_DESTINATION') {
            action = `<button class="btn btn-sm btn-primary text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'OUT_FOR_DELIVERY')">Simulasikan Diantar</button>`;
        } else if (o.status === 'OUT_FOR_DELIVERY') {
            action = `<button class="btn btn-sm btn-primary text-[10px] font-bold uppercase py-1" onclick="updateOrderStatus(${o.id}, 'DELIVERED')">Simulasikan Diterima</button>`;
        } else {
            action = `<span class="text-slate-500 text-[10px] font-semibold">-</span>`;
        }

        tbody.innerHTML += `
            <tr>
                <td><strong>${o.invoice}</strong></td>
                <td>${o.kurir}</td>
                <td>${o.alamat}</td>
                <td>${getStatusBadge(o.status)}</td>
                <td>${action}</td>
            </tr>
        `;
    });
}

function renderCoopReportsSummary() {
    const el = document.getElementById('c-reports-text');
    if (!el) return;
    let total = 0;
    state.orders.forEach(o => {
        if (o.koperasi_id == state.coopId && o.status === 'completed') {
            total += parseFloat(o.total);
        }
    });
    el.innerHTML = `Total omset toko koperasi yang terkumpul dari seluruh pesanan bertatus <strong>SELESAI</strong> saat ini adalah: <strong>Rp ${total.toLocaleString('id-ID')}</strong>`;
}

function renderCoopCustomersList() {
    const tbody = document.getElementById('c-customers-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    
    // Find users who have bought from state.coopId
    const customerIds = [];
    state.orders.forEach(o => {
        if (o.koperasi_id == state.coopId) {
            customerIds.push(o.customer_id);
        }
    });

    const customers = state.users.filter(u => customerIds.includes(u.id) || u.role_name === 'Customer');
    customers.forEach(c => {
        tbody.innerHTML += `
            <tr>
                <td><strong>${c.nama}</strong></td>
                <td>${c.email}</td>
                <td>${c.phone || '-'}</td>
                <td><span class="badge approved">${c.status.toUpperCase()}</span></td>
            </tr>
        `;
    });
}

/* ----------------------------------------------------
 * SMARTPHONE RENDERERS (Customer Mobile App Simulator)
 * ---------------------------------------------------- */
function renderPhoneScreen() {
    const area = document.getElementById('phone-content-area');
    if (!area) return;
    area.innerHTML = '';

    const nav = document.getElementById('phone-bottom-nav');
    if (state.currentPhoneView === 'login' || state.currentPhoneView === 'register') {
        nav.style.display = 'none';
    } else {
        nav.style.display = 'flex';
    }

    switch (state.currentPhoneView) {
        case 'login':
            renderPhoneLogin(area);
            break;
        case 'register':
            renderPhoneRegister(area);
            break;
        case 'home':
            renderPhoneHome(area);
            break;
        case 'coop-select':
            renderPhoneCoopSelect(area);
            break;
        case 'store':
            renderPhoneStore(area);
            break;
        case 'product-detail':
            renderPhoneProductDetail(area);
            break;
        case 'cart':
            renderPhoneCart(area);
            break;
        case 'checkout':
            renderPhoneCheckout(area);
            break;
        case 'payment':
            renderPhonePayment(area);
            break;
        case 'tracking':
            renderPhoneTracking(area);
            break;
        case 'history':
            renderPhoneHistory(area);
            break;
        case 'chat':
            renderPhoneChat(area);
            break;
    }
}

// 1. Phone Login View
function renderPhoneLogin(container) {
    container.innerHTML = `
        <div style="flex:1; display:flex; flex-direction:column; padding:1.5rem; justify-content:center; background:#1E293B; color:white;">
            <div style="text-align:center; margin-bottom:2rem;">
                <div style="background:var(--primary); color:white; width:54px; height:54px; border-radius:16px; display:inline-flex; align-items:center; justify-content:center; font-weight:800; font-size:1.6rem; margin-bottom:10px; box-shadow:0 4px 10px var(--primary-glow);">KM</div>
                <h2 style="font-family:var(--font-heading); font-size:1.25rem;">Koperasi Digital</h2>
                <p style="font-size:0.75rem; color:#94A3B8; margin-top:4px;">Portal & Marketplace Merah Putih</p>
            </div>
            
            <div class="form-group">
                <label style="color:#E2E8F0;">Email Customer</label>
                <input type="email" id="phone-login-email" class="form-control" value="budi@gmail.com" style="background:#0F172A;">
            </div>
            <div class="form-group" style="margin-bottom: 1.5rem;">
                <label style="color:#E2E8F0;">Password</label>
                <input type="password" id="phone-login-pass" class="form-control" value="password123" style="background:#0F172A;">
            </div>
            
            <button class="btn btn-primary" onclick="handlePhoneLogin()" style="width:100%; border-radius:8px;">MASUK SEBAGAI CUSTOMER</button>
            <p style="text-align:center; font-size:0.75rem; color:#94A3B8; margin-top:1.5rem;">
                Belum punya akun? <a href="#" onclick="switchPhoneView('register')" style="color:var(--primary); font-weight:600; text-decoration:none;">Registrasi</a>
            </p>
        </div>
    `;
}

async function handlePhoneLogin() {
    const email = document.getElementById('phone-login-email').value;
    const password = document.getElementById('phone-login-pass').value;

    try {
        const response = await fetch('/api/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `email=${encodeURIComponent(email)}&password=${encodeURIComponent(password)}`
        });
        const res = await response.json();
        if (response.ok) {
            state.customerSession = res.user;
            state.currentPhoneView = 'home';
            state.activePhoneTab = 'home';
            logConsole(`Customer logged in: ${res.user.nama}`);
            
            // Sync bottom nav highlighted tab
            document.querySelectorAll('.phone-bottom-nav .nav-tab').forEach(el => el.classList.remove('active'));
            const homeTab = document.querySelector(`.phone-bottom-nav .nav-tab[data-tab="home"]`);
            if (homeTab) homeTab.classList.add('active');
        } else {
            alert(res.message);
        }
    } catch (e) {
        // Local simulation fallback login
        if (email === 'budi@gmail.com') {
            state.customerSession = { id: 7, nama: 'Budi Santoso', email: 'budi@gmail.com', phone: '081234567896' };
        } else {
            state.customerSession = { id: 8, nama: 'Siti Aminah', email: 'siti@gmail.com', phone: '081234567897' };
        }
        state.currentPhoneView = 'home';
        state.activePhoneTab = 'home';
        logConsole(`Customer logged in (Simulasi Lokal): ${state.customerSession.nama}`);
        
        document.querySelectorAll('.phone-bottom-nav .nav-tab').forEach(el => el.classList.remove('active'));
        const homeTab = document.querySelector(`.phone-bottom-nav .nav-tab[data-tab="home"]`);
        if (homeTab) homeTab.classList.add('active');
    }
    renderPhoneScreen();
}

function switchPhoneView(view) {
    state.currentPhoneView = view;
    renderPhoneScreen();
}

// 2. Phone Register View
function renderPhoneRegister(container) {
    container.innerHTML = `
        <div style="flex:1; display:flex; flex-direction:column; padding:1.5rem; justify-content:center; background:#1E293B; color:white;">
            <div style="text-align:center; margin-bottom:1.5rem;">
                <h2 style="font-family:var(--font-heading); font-size:1.25rem;">Registrasi Customer</h2>
                <p style="font-size:0.75rem; color:#94A3B8; margin-top:2px;">Bergabung dengan portal Koperasi Digital</p>
            </div>
            
            <div class="form-group">
                <label style="color:#E2E8F0;">Nama Lengkap</label>
                <input type="text" id="phone-reg-name" class="form-control" placeholder="Nama Anda" style="background:#0F172A;">
            </div>
            <div class="form-group">
                <label style="color:#E2E8F0;">Email</label>
                <input type="email" id="phone-reg-email" class="form-control" placeholder="nama@gmail.com" style="background:#0F172A;">
            </div>
            <div class="form-group">
                <label style="color:#E2E8F0;">Nomor Telp</label>
                <input type="text" id="phone-reg-phone" class="form-control" placeholder="0812..." style="background:#0F172A;">
            </div>
            <div class="form-group" style="margin-bottom: 1.5rem;">
                <label style="color:#E2E8F0;">Password</label>
                <input type="password" id="phone-reg-pass" class="form-control" placeholder="Minimal 6 karakter" style="background:#0F172A;">
            </div>
            
            <button class="btn btn-primary" onclick="handlePhoneRegister()" style="width:100%; border-radius:8px;">DAFTAR SEKARANG</button>
            <p style="text-align:center; font-size:0.75rem; color:#94A3B8; margin-top:1.5rem;">
                Sudah punya akun? <a href="#" onclick="switchPhoneView('login')" style="color:var(--primary); font-weight:600; text-decoration:none;">Login</a>
            </p>
        </div>
    `;
}

async function handlePhoneRegister() {
    const name = document.getElementById('phone-reg-name').value;
    const email = document.getElementById('phone-reg-email').value;
    const phone = document.getElementById('phone-reg-phone').value;
    const password = document.getElementById('phone-reg-pass').value;

    try {
        const response = await fetch('/api/auth/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}&phone=${encodeURIComponent(phone)}&password=${encodeURIComponent(password)}`
        });
        const res = await response.json();
        if (response.ok) {
            alert('Registrasi sukses. Silakan login.');
            state.currentPhoneView = 'login';
        } else {
            alert(res.message);
        }
    } catch (e) {
        state.users.push({
            id: state.users.length + 1,
            nama: name,
            email: email,
            role_name: 'Customer',
            koperasi_name: '-',
            status: 'active'
        });
        alert('Simulasi Lokal: Registrasi sukses!');
        state.currentPhoneView = 'login';
    }
    renderPhoneScreen();
}

// 3. Phone Home View (Portal Awal Koperasi Digital)
function renderPhoneHome(container) {
    const activeCoops = state.cooperatives.filter(c => c.status === 'aktif');
    
    container.innerHTML = `
        <!-- Portal Header -->
        <div class="phone-header">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
                <span style="font-family:var(--font-heading); font-weight:800; font-size:0.85rem; letter-spacing:0.5px; text-transform:uppercase;">KopMerahPutih</span>
                <span class="material-symbols-outlined" style="cursor:pointer;" onclick="switchPhoneView('cart')">shopping_cart</span>
                <div class="cart-badge">${state.cart.reduce((s, i) => s + i.qty, 0)}</div>
            </div>
            <div class="search-bar-row">
                <span class="material-symbols-outlined">search</span>
                <input type="text" id="phone-search-coop" placeholder="Cari koperasi terdaftar..." onkeyup="filterCoopSearch(event)">
            </div>
        </div>

        <div class="phone-body">
            <!-- Banner Nasional -->
            <div class="banner-slider">
                <h3>Portal Koperasi Nasional</h3>
                <p>Wadah kolaboratif di bawah naungan Dinas Koperasi & UMKM.</p>
                <div style="display:flex; gap:4px; margin-top:8px;">
                    <div style="width:12px; height:4px; border-radius:2px; background:white;"></div>
                    <div style="width:4px; height:4px; border-radius:2px; background:rgba(255,255,255,0.4);"></div>
                </div>
            </div>

            <!-- Nearest coops -->
            <div class="phone-sec-title">
                <h3>Koperasi Terdekat</h3>
                <a href="#" onclick="setPhoneTab('koperasi')">Lihat Semua</a>
            </div>

            <div class="horizontal-scroll">
                ${activeCoops.map(c => `
                    <div class="mini-product-card" onclick="visitCoopStore(${c.id})" style="min-width: 140px; padding: 0.5rem; text-align: center;">
                        <img src="${c.logo}" style="width:40px; height:40px; border-radius:10px; object-fit:cover; margin:0 auto 8px auto;">
                        <div class="mini-title" style="font-size:0.7rem; font-weight:700; white-space:normal; height:32px; overflow:hidden;">${c.nama_koperasi}</div>
                        <div style="font-size:0.55rem; color:#64748B; margin-top:2px;">📍 ${c.kabupaten}</div>
                    </div>
                `).join('')}
            </div>

            <!-- Popular coops -->
            <div class="phone-sec-title" style="margin-top: 1.25rem;">
                <h3>Koperasi Populer</h3>
            </div>

            <div class="coop-grid-phone" style="padding-top: 0;">
                ${activeCoops.slice(0, 3).map(c => `
                    <div class="coop-card-phone" onclick="visitCoopStore(${c.id})">
                        <div class="coop-logo-phone" style="background-image: url('${c.logo}')"></div>
                        <div class="coop-info-phone">
                            <div class="coop-name-phone">${c.nama_koperasi}</div>
                            <div class="coop-loc-phone">⭐ 4.9 | 📍 ${c.kabupaten}</div>
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>
    `;
}

function filterCoopSearch(e) {
    if (e.key === 'Enter') {
        state.searchQuery = e.target.value;
        state.currentPhoneView = 'coop-select';
        renderPhoneScreen();
    }
}

// 4. Phone Coop Selection view
function renderPhoneCoopSelect(container) {
    let filtered = state.cooperatives.filter(c => c.status === 'aktif');
    if (state.searchQuery) {
        filtered = filtered.filter(c => c.nama_koperasi.toLowerCase().includes(state.searchQuery.toLowerCase()) || c.kabupaten.toLowerCase().includes(state.searchQuery.toLowerCase()));
    }

    container.innerHTML = `
        <div class="phone-header" style="display:flex; align-items:center; gap:8px;">
            <span class="material-symbols-outlined" style="cursor:pointer;" onclick="setPhoneTab('home')">arrow_back</span>
            <span style="font-weight:700; font-size:0.85rem;">Pilih Koperasi</span>
        </div>
        <div class="phone-body" style="padding-top: 8px;">
            <div style="padding: 0 0.75rem; margin-bottom: 0.5rem; font-size:0.7rem; color:#64748B;">
                Hasil pencarian: ${filtered.length} Koperasi Aktif
            </div>
            <div class="coop-grid-phone">
                ${filtered.map(c => `
                    <div class="coop-card-phone" onclick="visitCoopStore(${c.id})">
                        <div class="coop-logo-phone" style="background-image: url('${c.logo}')"></div>
                        <div class="coop-info-phone">
                            <div class="coop-name-phone">${c.nama_koperasi}</div>
                            <div class="coop-loc-phone">📍 ${c.alamat}</div>
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>
    `;
}

// Visit a cooperative store
function visitCoopStore(id) {
    const coop = state.cooperatives.find(c => c.id == id);
    if (coop) {
        state.selectedCoop = coop;
        state.selectedCoopCategory = 0; // reset
        state.currentPhoneView = 'store';
        renderPhoneScreen();
    }
}

// 5. Phone Cooperative Store view
function renderPhoneStore(container) {
    const c = state.selectedCoop;
    let storeProducts = state.products.filter(p => p.koperasi_id == c.id && p.status === 'aktif');
    if (state.selectedCoopCategory !== 0) {
        storeProducts = storeProducts.filter(p => p.kategori_id == state.selectedCoopCategory);
    }

    container.innerHTML = `
        <!-- Shop Store Header -->
        <div class="phone-header" style="display:flex; align-items:center; gap:10px;">
            <span class="material-symbols-outlined" style="cursor:pointer;" onclick="setPhoneTab('home')">arrow_back</span>
            <span style="font-weight:700; font-size:0.85rem; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; flex:1;">${c.nama_koperasi}</span>
        </div>

        <div class="store-header-phone">
            <div class="store-logo-phone" style="background-image: url('${c.logo}')"></div>
            <div>
                <div class="store-name-phone">${c.nama_koperasi}</div>
                <div class="store-meta-phone">⭐ 4.9 | 📍 ${c.kabupaten}</div>
            </div>
        </div>

        <!-- Categories horizontal bar -->
        <div class="cat-slider-phone">
            <div class="cat-pill-phone ${state.selectedCoopCategory === 0 ? 'active' : ''}" onclick="filterStoreCategory(0)">Semua Produk</div>
            <div class="cat-pill-phone ${state.selectedCoopCategory === 1 ? 'active' : ''}" onclick="filterStoreCategory(1)">Sembako</div>
            <div class="cat-pill-phone ${state.selectedCoopCategory === 2 ? 'active' : ''}" onclick="filterStoreCategory(2)">Elektronik</div>
            <div class="cat-pill-phone ${state.selectedCoopCategory === 3 ? 'active' : ''}" onclick="filterStoreCategory(3)">UMKM</div>
            <div class="cat-pill-phone ${state.selectedCoopCategory === 4 ? 'active' : ''}" onclick="filterStoreCategory(4)">Pertanian</div>
        </div>

        <div class="phone-body">
            <div class="prod-grid-phone">
                ${storeProducts.map(p => `
                    <div class="phone-prod-card" onclick="openProductDetailPhone(${p.id})">
                        <div class="phone-prod-img" style="background-image: url('${p.foto}')">
                            <div class="phone-prod-rating">
                                <span class="material-symbols-outlined" style="font-size:0.6rem; font-variation-settings: 'FILL' 1;">star</span>
                                <span>${p.rating}</span>
                            </div>
                        </div>
                        <div class="phone-prod-details">
                            <div class="phone-prod-name">${p.nama_produk}</div>
                            <span class="phone-prod-price">Rp ${Number(p.harga).toLocaleString('id-ID')}</span>
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>
    `;
}

function filterStoreCategory(catId) {
    state.selectedCoopCategory = catId;
    renderPhoneScreen();
}

function openProductDetailPhone(id) {
    const prod = state.products.find(p => p.id == id);
    if (prod) {
        state.activeProductDetail = prod;
        state.currentPhoneView = 'product-detail';
        renderPhoneScreen();
    }
}

// 6. Phone Product Detail View
function renderPhoneProductDetail(container) {
    const p = state.activeProductDetail;
    container.innerHTML = `
        <div class="phone-header" style="display:flex; align-items:center; gap:8px;">
            <span class="material-symbols-outlined" style="cursor:pointer;" onclick="switchPhoneView('store')">arrow_back</span>
            <span style="font-weight:700; font-size:0.85rem;">Detail Produk</span>
        </div>

        <div class="phone-body" style="padding-bottom: 70px;">
            <div style="background-image: url('${p.foto}'); height: 220px; background-size: cover; background-position: center; border-bottom:1px solid #E2E8F0;"></div>
            <div style="padding:0.75rem;">
                <h2 style="font-size: 0.95rem; font-weight: 700; line-height: 1.4; color: #1E293B;">${p.nama_produk}</h2>
                <div style="font-size: 1.1rem; color: var(--primary); font-weight: 800; margin-top: 4px;">Rp ${Number(p.harga).toLocaleString('id-ID')}</div>
                <div style="font-size: 0.65rem; color: #64748B; margin-top: 4px; display:flex; align-items:center; gap:2px;">
                    <span class="material-symbols-outlined" style="font-size:0.8rem; color:#F59E0B; font-variation-settings: 'FILL' 1;">star</span>
                    <span>${p.rating} | Tersedia: ${p.stok}</span>
                </div>
                
                <div style="margin: 1rem 0; padding: 0.75rem; background:#F8FAFC; border-radius:10px; border:1px solid #E2E8F0; display:flex; align-items:center; gap:8px;">
                    <div style="width:36px; height:36px; border-radius:8px; background-image:url('${state.selectedCoop.logo}'); background-size:cover; background-position:center;"></div>
                    <div>
                        <div style="font-size:0.7rem; font-weight:800; color:#334155;">${state.selectedCoop.nama_koperasi}</div>
                        <div style="font-size:0.6rem; color:#94A3B8;">📍 ${state.selectedCoop.kabupaten}</div>
                    </div>
                </div>

                <h3 style="font-size:0.8rem; font-weight:700; color:#334155; margin-bottom:4px;">Deskripsi</h3>
                <p style="font-size:0.7rem; color:#64748B; line-height:1.5; white-space:pre-line;">${p.deskripsi || 'Tidak ada deskripsi produk.'}</p>
            </div>
        </div>

        <div style="position:absolute; bottom:0; left:0; right:0; background:white; padding:0.6rem 0.75rem; border-top:1px solid #E2E8F0; z-index:90;">
            <button class="btn btn-primary" onclick="addProductToCart(${p.id})" style="width:100%; border-radius:8px; padding:0.6rem;">TAMBAH KE KERANJANG</button>
        </div>
    `;
}

function addProductToCart(id) {
    const p = state.products.find(x => x.id == id);
    const exist = state.cart.find(item => item.product_id == id);
    
    if (exist) {
        exist.qty++;
    } else {
        state.cart.push({
            product_id: p.id,
            nama_produk: p.nama_produk,
            harga: p.harga,
            foto: p.foto,
            qty: 1
        });
    }

    logConsole(`Customer menambahkan barang "${p.nama_produk}" ke keranjang.`);
    state.currentPhoneView = 'cart';
    renderPhoneScreen();
}

// 7. Phone Cart View
function renderPhoneCart(container) {
    const totalItems = state.cart.reduce((s, i) => s + i.qty, 0);
    const subtotal = state.cart.reduce((s, i) => s + (i.harga * i.qty), 0);

    container.innerHTML = `
        <div class="phone-header" style="display:flex; align-items:center; gap:8px;">
            <span class="material-symbols-outlined" style="cursor:pointer;" onclick="switchPhoneView('store')">arrow_back</span>
            <span style="font-weight:700; font-size:0.85rem;">Keranjang Belanja</span>
        </div>

        <div class="phone-body" style="padding-bottom: 75px;">
            ${state.cart.length === 0 ? `
                <div style="text-align:center; padding:3rem; color:#94A3B8;">
                    <span class="material-symbols-outlined" style="font-size:3rem; margin-bottom:10px;">shopping_cart</span>
                    <p style="font-size:0.75rem;">Keranjang belanja Anda kosong.</p>
                </div>
            ` : state.cart.map(item => `
                <div class="cart-item-card">
                    <div class="cart-item-img" style="background-image: url('${item.foto}')"></div>
                    <div class="cart-item-info">
                        <div class="cart-item-title">${item.nama_produk}</div>
                        <div class="cart-item-price">Rp ${Number(item.harga).toLocaleString('id-ID')}</div>
                    </div>
                    <div class="cart-qty-row">
                        <div class="cart-qty-btn" onclick="updateCartQty(${item.product_id}, -1)">-</div>
                        <span style="font-size:0.75rem; font-weight:700;">${item.qty}</span>
                        <div class="cart-qty-btn" onclick="updateCartQty(${item.product_id}, 1)">+</div>
                    </div>
                </div>
            `).join('')}
        </div>

        ${state.cart.length > 0 ? `
            <div style="position:absolute; bottom:0; left:0; right:0; background:white; padding:0.75rem; border-top:1px solid #E2E8F0; z-index:90;">
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
                    <span style="font-size:0.7rem; color:#64748B;">Subtotal (${totalItems} barang)</span>
                    <span style="font-size:0.8rem; font-weight:800; color:var(--primary);">Rp ${subtotal.toLocaleString('id-ID')}</span>
                </div>
                <button class="btn btn-primary" onclick="switchPhoneView('checkout')" style="width:100%; border-radius:8px; padding:0.6rem;">CHECKOUT</button>
            </div>
        ` : ''}
    `;
}

function updateCartQty(prodId, diff) {
    const item = state.cart.find(x => x.product_id == prodId);
    if (item) {
        item.qty += diff;
        if (item.qty <= 0) {
            state.cart = state.cart.filter(x => x.product_id != prodId);
        }
    }
    renderPhoneScreen();
}

// 8. Phone Checkout View
function renderPhoneCheckout(container) {
    const subtotal = state.cart.reduce((s, i) => s + (i.harga * i.qty), 0);
    const shipping = 15000;
    const total = subtotal + shipping;

    container.innerHTML = `
        <div class="phone-header" style="display:flex; align-items:center; gap:8px;">
            <span class="material-symbols-outlined" style="cursor:pointer;" onclick="switchPhoneView('cart')">arrow_back</span>
            <span style="font-weight:700; font-size:0.85rem;">Checkout Pesanan</span>
        </div>

        <div class="phone-body" style="padding:0.75rem; padding-bottom:75px;">
            <div style="background:white; border-radius:10px; border:1px solid #E2E8F0; padding:0.75rem; margin-bottom:0.75rem;">
                <h4 style="font-size:0.7rem; font-weight:700; color:#334155; margin-bottom:6px; display:flex; align-items:center; gap:4px;">
                    <span class="material-symbols-outlined" style="font-size:0.95rem; color:var(--primary);">location_on</span> Alamat Pengiriman
                </h4>
                <textarea id="checkout-address" class="form-control" rows="2" style="background:#F8FAFC; color:#1E293B; font-size:0.7rem;">${state.shippingAddress}</textarea>
            </div>

            <div style="background:white; border-radius:10px; border:1px solid #E2E8F0; padding:0.75rem; margin-bottom:0.75rem;">
                <h4 style="font-size:0.7rem; font-weight:700; color:#334155; margin-bottom:6px;">Pilihan Ekspedisi</h4>
                <select id="checkout-courier" class="form-control" style="background:#F8FAFC; color:#1E293B; font-size:0.7rem;">
                    <option value="KopExpress" ${state.selectedCourier === 'KopExpress' ? 'selected' : ''}>KopExpress (Rp 15.000)</option>
                    <option value="POS Indonesia" ${state.selectedCourier === 'POS Indonesia' ? 'selected' : ''}>POS Indonesia (Rp 18.000)</option>
                    <option value="J&T Express" ${state.selectedCourier === 'J&T Express' ? 'selected' : ''}>J&T Express (Rp 20.000)</option>
                </select>
            </div>

            <div style="background:white; border-radius:10px; border:1px solid #E2E8F0; padding:0.75rem;">
                <h4 style="font-size:0.7rem; font-weight:700; color:#334155; margin-bottom:6px;">Rincian Harga</h4>
                <div style="display:flex; justify-content:space-between; font-size:0.65rem; color:#64748B; margin-bottom:4px;">
                    <span>Subtotal Barang</span>
                    <span>Rp ${subtotal.toLocaleString('id-ID')}</span>
                </div>
                <div style="display:flex; justify-content:space-between; font-size:0.65rem; color:#64748B; margin-bottom:6px;">
                    <span>Ongkos Kirim</span>
                    <span>Rp ${shipping.toLocaleString('id-ID')}</span>
                </div>
                <div style="display:flex; justify-content:space-between; font-size:0.75rem; font-weight:800; color:#1E293B; border-top:1px solid #F1F5F9; padding-top:6px;">
                    <span>Total Pembayaran</span>
                    <span>Rp ${total.toLocaleString('id-ID')}</span>
                </div>
            </div>
        </div>

        <div style="position:absolute; bottom:0; left:0; right:0; background:white; padding:0.75rem; border-top:1px solid #E2E8F0; z-index:90;">
            <button class="btn btn-primary" onclick="proceedToPayment()" style="width:100%; border-radius:8px; padding:0.6rem;">PILIH METODE PEMBAYARAN</button>
        </div>
    `;
}

function proceedToPayment() {
    state.shippingAddress = document.getElementById('checkout-address').value;
    state.selectedCourier = document.getElementById('checkout-courier').value;
    state.currentPhoneView = 'payment';
    renderPhoneScreen();
}

// 9. Phone Payment View
function renderPhonePayment(container) {
    const subtotal = state.cart.reduce((s, i) => s + (i.harga * i.qty), 0);
    const shipping = 15000;
    const total = subtotal + shipping;

    container.innerHTML = `
        <div class="phone-header" style="display:flex; align-items:center; gap:8px;">
            <span class="material-symbols-outlined" style="cursor:pointer;" onclick="switchPhoneView('checkout')">arrow_back</span>
            <span style="font-weight:700; font-size:0.85rem;">Pembayaran QRIS</span>
        </div>

        <div class="phone-body" style="padding-bottom: 75px;">
            <div class="qris-box">
                <h4 style="font-size:0.75rem; font-weight:700; color:#1E293B;">Scan QRIS Koperasi Digital</h4>
                <div class="qris-code"></div>
                <div style="font-size:0.65rem; color:#94A3B8;">Silakan scan QRIS untuk menyelesaikan pembayaran otomatis.</div>
            </div>

            <div style="padding:0 1rem; text-align:center;">
                <div style="font-size:0.65rem; color:#64748B;">Total Tagihan</div>
                <div style="font-size:1.1rem; font-weight:800; color:var(--primary); margin-top:2px;">Rp ${total.toLocaleString('id-ID')}</div>
            </div>
        </div>

        <div style="position:absolute; bottom:0; left:0; right:0; background:white; padding:0.75rem; border-top:1px solid #E2E8F0; z-index:90;">
            <button class="btn btn-primary" onclick="confirmPaymentAndCheckout()" style="width:100%; border-radius:8px; padding:0.6rem;">KONFIRMASI TELAH MEMBAYAR</button>
        </div>
    `;
}

async function confirmPaymentAndCheckout() {
    const subtotal = state.cart.reduce((s, i) => s + (i.harga * i.qty), 0);
    const shipping = 15000;
    const total = subtotal + shipping;

    const payload = {
        user_id: state.customerSession.id,
        koperasi_id: state.selectedCoop.id,
        items: JSON.stringify(state.cart.map(i => ({ product_id: i.product_id, qty: i.qty }))),
        shipping_courier: state.selectedCourier,
        shipping_address: state.shippingAddress,
        total_amount: total,
        shipping_cost: shipping
    };

    try {
        const response = await fetch('/api/orders', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `user_id=${payload.user_id}&koperasi_id=${payload.koperasi_id}&items=${encodeURIComponent(payload.items)}&shipping_courier=${encodeURIComponent(payload.shipping_courier)}&shipping_address=${encodeURIComponent(payload.shipping_address)}&total_amount=${payload.total_amount}&shipping_cost=${payload.shipping_cost}`
        });
        const res = await response.json();
        
        if (response.ok) {
            state.activeOrderTracking = {
                id: res.data.order_id,
                invoice: res.data.invoice,
                status: 'paid',
                total: total,
                kurir: state.selectedCourier,
                alamat: state.shippingAddress
            };
        }
    } catch (e) {
        // Local simulation insert
        const newId = state.orders.length + 1;
        const invoice = 'INV-' + dateString() + '-' + Math.random().toString(36).substring(3, 9).toUpperCase();
        const orderData = {
            id: newId,
            invoice: invoice,
            customer_id: state.customerSession.id,
            customer_name: state.customerSession.nama,
            koperasi_id: state.selectedCoop.id,
            total: total,
            status: 'paid',
            ongkir: shipping,
            kurir: state.selectedCourier,
            alamat: state.shippingAddress,
            created_at: new Date().toISOString().replace('T', ' ').substring(0, 19)
        };
        state.orders.push(orderData);
        state.activeOrderTracking = orderData;
    }

    logConsole(`Customer ${state.customerSession.nama} berhasil melakukan checkout pesanan.`);
    state.cart = []; // clear cart
    state.currentPhoneView = 'tracking';
    
    loadAllData();
}

function dateString() {
    const d = new Date();
    return d.getFullYear() + String(d.getMonth() + 1).padStart(2, '0') + String(d.getDate()).padStart(2, '0');
}

// 10. Phone Order Tracking View
function renderPhoneTracking(container) {
    const o = state.activeOrderTracking;
    const isPending = o.status === 'pending';
    const isPaid = ['paid', 'processing', 'shipped', 'completed'].includes(o.status);
    const isProcessing = ['processing', 'shipped', 'completed'].includes(o.status);
    const isShipped = ['shipped', 'completed'].includes(o.status);
    const isCompleted = o.status === 'completed';

    container.innerHTML = `
        <div class="phone-header" style="display:flex; align-items:center; gap:8px;">
            <span class="material-symbols-outlined" style="cursor:pointer;" onclick="setPhoneTab('history')">arrow_back</span>
            <span style="font-weight:700; font-size:0.85rem;">Pelacakan Pengiriman</span>
        </div>

        <div class="phone-body" style="padding:0.75rem;">
            <div style="background:white; border-radius:12px; border:1px solid #E2E8F0; padding:0.85rem; margin-bottom:0.75rem;">
                <div style="font-size:0.6rem; color:#94A3B8;">Nomor Invoice</div>
                <div style="font-size:0.85rem; font-weight:800; color:#1E293B;">${o.invoice}</div>
                <div style="font-size:0.65rem; color:#64748B; margin-top:4px;">Kurir: ${o.kurir}</div>
            </div>

            <div class="timeline-stepper">
                <div class="timeline-step ${isCompleted ? 'active' : ''}">
                    <div class="timeline-bullet"></div>
                    <div class="timeline-info">
                        <h4>Pesanan Selesai</h4>
                        <p>Barang telah diterima oleh customer.</p>
                    </div>
                </div>
                <div class="timeline-step ${isShipped ? 'active' : ''}">
                    <div class="timeline-bullet"></div>
                    <div class="timeline-info">
                        <h4>Dalam Pengiriman</h4>
                        <p>Barang sedang dibawa kurir. Resi: KOPEX123.</p>
                    </div>
                </div>
                <div class="timeline-step ${isProcessing ? 'active' : ''}">
                    <div class="timeline-bullet"></div>
                    <div class="timeline-info">
                        <h4>Sedang Diproses</h4>
                        <p>Seller sedang mempacking barang pesanan.</p>
                    </div>
                </div>
                <div class="timeline-step ${isPaid ? 'active' : ''}">
                    <div class="timeline-bullet"></div>
                    <div class="timeline-info">
                        <h4>Pembayaran Dikonfirmasi</h4>
                        <p>Pembayaran QRIS berhasil divalidasi.</p>
                    </div>
                </div>
                <div class="timeline-step ${isPending || isPaid ? 'active' : ''}">
                    <div class="timeline-bullet"></div>
                    <div class="timeline-info">
                        <h4>Pesanan Dibuat</h4>
                        <p>Checkout transaksi sukses dilakukan.</p>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// 11. Phone Purchase History View
function renderPhoneHistory(container) {
    const myOrders = state.orders.filter(o => o.customer_id == state.customerSession.id);

    container.innerHTML = `
        <div class="phone-header">
            <span style="font-weight:700; font-size:0.85rem;">Riwayat Belanja</span>
        </div>

        <div class="phone-body" style="padding-top: 8px;">
            ${myOrders.length === 0 ? `
                <div style="text-align:center; padding:3rem; color:#94A3B8;">
                    <span class="material-symbols-outlined" style="font-size:2.5rem; margin-bottom:8px;">assignment_late</span>
                    <p style="font-size:0.75rem;">Anda belum pernah berbelanja.</p>
                </div>
            ` : myOrders.map(o => `
                <div style="background:white; border-radius:10px; border:1px solid #E2E8F0; padding:0.75rem; margin:0.5rem 0.75rem; cursor:pointer;" onclick="openOrderTracking(${o.id})">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
                        <span style="font-size:0.65rem; font-weight:800; color:#334155;">${o.invoice}</span>
                        <span class="badge ${o.status === 'completed' ? 'approved' : 'lvl1'}" style="font-size:0.55rem; padding:1px 4px;">${o.status.toUpperCase()}</span>
                    </div>
                    <div style="font-size:0.65rem; color:#94A3B8;">Total Belanja: Rp ${Number(o.total).toLocaleString('id-ID')}</div>
                    <div style="font-size:0.65rem; color:#64748B; margin-top:4px; text-align:right;">Lacak Pengiriman →</div>
                </div>
            `).join('')}
        </div>
    `;
}

function openOrderTracking(id) {
    const o = state.orders.find(x => x.id == id);
    if (o) {
        state.activeOrderTracking = o;
        state.currentPhoneView = 'tracking';
        renderPhoneScreen();
    }
}

// 12. Phone AI Chatbot CS View
function renderPhoneChat(container) {
    container.innerHTML = `
        <div class="phone-header">
            <span style="font-weight:700; font-size:0.85rem;">KopMerahPutih AI CS</span>
        </div>

        <div id="phone-chat-body" style="flex:1; overflow-y:auto; padding:0.75rem; display:flex; flex-direction:column; gap:8px;">
            ${state.chatMessages.map(msg => `
                <div style="align-self:${msg.sender === 'AI' ? 'flex-start' : 'flex-end'}; background:${msg.sender === 'AI' ? '#E2E8F0' : 'var(--primary)'}; color:${msg.sender === 'AI' ? '#1E293B' : 'white'}; padding:8px 12px; border-radius:12px; font-size:0.7rem; max-width:80%; line-height:1.4; white-space:pre-line;">
                    ${msg.text}
                </div>
            `).join('')}
        </div>

        <div style="padding:6px; background:white; border-top:1px solid #E2E8F0; display:flex; gap:6px; z-index:90;">
            <input type="text" id="phone-chat-input" class="form-control" placeholder="Tanya tentang Koperasi..." style="font-size:0.7rem; border-radius:8px; padding:6px;" onkeyup="handleChatEnter(event)">
            <button class="btn btn-primary" onclick="sendChatMessage()" style="border-radius:8px; padding:0 12px; font-size:0.75rem;">Kirim</button>
        </div>
    `;
    setTimeout(() => {
        const body = document.getElementById('phone-chat-body');
        if (body) body.scrollTop = body.scrollHeight;
    }, 50);
}

function handleChatEnter(e) {
    if (e.key === 'Enter') sendChatMessage();
}

async function sendChatMessage() {
    const input = document.getElementById('phone-chat-input');
    const msg = input.value;
    if (!msg) return;

    state.chatMessages.push({ sender: 'User', text: msg });
    input.value = '';
    renderPhoneScreen();

    // Trigger REST AI CS
    try {
        const response = await fetch('/api/ai/chatbot', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `message=${encodeURIComponent(msg)}`
        });
        const res = await response.json();
        if (response.ok) {
            state.chatMessages.push({ sender: 'AI', text: res.reply });
        }
    } catch (e) {
        // Fallback
        state.chatMessages.push({ sender: 'AI', text: 'Koneksi AI assistant offline. Silakan coba sesaat lagi.' });
    }
    renderPhoneScreen();
}

// Navigation switcher from code
function setPhoneTab(tab) {
    state.activePhoneTab = tab;
    
    // Highlight phone navigation bottom bar tab
    document.querySelectorAll('.phone-bottom-nav .nav-tab').forEach(el => el.classList.remove('active'));
    const target = document.querySelector(`.phone-bottom-nav .nav-tab[data-tab="${tab}"]`);
    if (target) target.classList.add('active');

    if (tab === 'home') {
        state.currentPhoneView = 'home';
    } else if (tab === 'koperasi') {
        state.currentPhoneView = 'coop-select';
    } else if (tab === 'history') {
        state.currentPhoneView = 'history';
    } else if (tab === 'ai-cs') {
        state.currentPhoneView = 'chat';
    }
    renderPhoneScreen();
}

// Web Admin Authentication Logic
async function handleWebLogin() {
    const emailInput = document.getElementById('web-login-email');
    const passInput = document.getElementById('web-login-pass');
    const errAlert = document.getElementById('web-login-error');
    const loginBtn = document.getElementById('web-login-btn');

    if (!emailInput || !passInput) return;

    const email = emailInput.value.trim();
    const password = passInput.value;

    // Reset error
    if (errAlert) errAlert.classList.add('hidden');

    // Button loading state
    const originalBtnHTML = loginBtn.innerHTML;
    loginBtn.disabled = true;
    loginBtn.innerHTML = `
        <svg class="animate-spin -ml-1 mr-3 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        <span>MEMVERIFIKASI...</span>
    `;

    try {
        const response = await fetch('/api/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `email=${encodeURIComponent(email)}&password=${encodeURIComponent(password)}`
        });

        const res = await response.json();

        if (response.ok) {
            // Save to localStorage
            localStorage.setItem('web_token', res.token);
            localStorage.setItem('web_user', JSON.stringify(res.user));

            // Log activity
            logConsole(`User logged in: ${res.user.nama} (${res.user.email})`);

            // Apply session based on role
            closeWebLoginModal();
            if (res.user.role_id == 4) {
                applyCustomerSession(res.user);
            } else {
                applyWebSession(res.user);
            }
        } else {
            showWebLoginError(res.message || 'Email atau password salah.');
        }
    } catch (err) {
        logConsole('Koneksi backend API bermasalah. Menggunakan autentikasi offline.', 'error');
        // Offline Fallback for Development
        handleOfflineWebLogin(email, password);
    } finally {
        loginBtn.disabled = false;
        loginBtn.innerHTML = originalBtnHTML;
    }
}

function showWebLoginError(message) {
    const errAlert = document.getElementById('web-login-error');
    const errMsg = document.getElementById('web-login-error-msg');
    if (errAlert && errMsg) {
        errMsg.innerText = message;
        errAlert.classList.remove('hidden');
    }
}

// Web Authentication Form Switcher (Login vs Register)
function toggleWebAuthMode(mode) {
    const loginForm = document.getElementById('web-login-form');
    const registerForm = document.getElementById('web-register-form');
    const titleEl = document.getElementById('web-auth-modal-title');
    const subtitleEl = document.getElementById('web-auth-modal-subtitle');
    const badgeEl = document.getElementById('web-auth-modal-badge');
    const errLogin = document.getElementById('web-login-error');
    const errRegister = document.getElementById('web-register-error');

    if (errLogin) errLogin.classList.add('hidden');
    if (errRegister) errRegister.classList.add('hidden');

    if (mode === 'register') {
        if (loginForm) loginForm.classList.add('hidden');
        if (registerForm) registerForm.classList.remove('hidden');
        if (titleEl) titleEl.innerText = 'Daftar Akun Baru';
        if (subtitleEl) subtitleEl.innerText = 'Bergabung dengan Koperasi Digital Merah Putih';
        if (badgeEl) {
            badgeEl.innerText = 'Registration';
            badgeEl.className = 'text-[9px] bg-emerald-950/40 text-emerald-400 border border-emerald-800/30 px-2.5 py-0.5 rounded-full font-bold uppercase tracking-wider mt-1.5 inline-block';
        }

        // Reset register form inputs
        document.getElementById('web-register-name').value = '';
        document.getElementById('web-register-email').value = '';
        document.getElementById('web-register-phone').value = '';
        document.getElementById('web-register-pass').value = '';
        const roleSel = document.getElementById('web-register-role');
        if (roleSel) roleSel.value = '4';
        handleRegisterRoleChange('4');
    } else {
        if (loginForm) loginForm.classList.remove('hidden');
        if (registerForm) registerForm.classList.add('hidden');
        if (titleEl) titleEl.innerText = 'KopMerahPutih';
        if (subtitleEl) subtitleEl.innerText = 'Platform Koperasi Digital Merah Putih';
        if (badgeEl) {
            badgeEl.innerText = 'Web Authentication';
            badgeEl.className = 'text-[9px] bg-rose-950/40 text-primary border border-rose-800/30 px-2.5 py-0.5 rounded-full font-bold uppercase tracking-wider mt-1.5 inline-block';
        }
    }
}

// Handle change in account type (Consumer vs Seller)
function handleRegisterRoleChange(roleId) {
    const container = document.getElementById('web-register-coop-container');
    const select = document.getElementById('web-register-coop');
    if (!container || !select) return;

    if (roleId == '3') {
        container.classList.remove('hidden');
        select.innerHTML = '';
        state.cooperatives.forEach(c => {
            select.innerHTML += `<option value="${c.id}">${c.nama_koperasi}</option>`;
        });
    } else {
        container.classList.add('hidden');
        select.innerHTML = '';
    }
}

// Handle submit of Registration Form
async function handleWebRegister() {
    const name = document.getElementById('web-register-name').value.trim();
    const email = document.getElementById('web-register-email').value.trim();
    const phone = document.getElementById('web-register-phone').value.trim();
    const password = document.getElementById('web-register-pass').value;
    const roleId = document.getElementById('web-register-role').value;
    const koperasiId = roleId == '3' ? document.getElementById('web-register-coop').value : null;

    const errAlert = document.getElementById('web-register-error');
    const errMsg = document.getElementById('web-register-error-msg');
    const regBtn = document.getElementById('web-register-btn');

    if (errAlert) errAlert.classList.add('hidden');

    if (!name || !email || !phone || !password) {
        if (errMsg) errMsg.innerText = 'Harap isi semua kolom.';
        if (errAlert) errAlert.classList.remove('hidden');
        return;
    }

    if (password.length < 6) {
        if (errMsg) errMsg.innerText = 'Password minimal 6 karakter.';
        if (errAlert) errAlert.classList.remove('hidden');
        return;
    }

    // Button loading state
    const originalBtnHTML = regBtn.innerHTML;
    regBtn.disabled = true;
    regBtn.innerHTML = `
        <svg class="animate-spin -ml-1 mr-3 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        <span>MENDAFTARKAN...</span>
    `;

    const payload = `name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}&phone=${encodeURIComponent(phone)}&password=${encodeURIComponent(password)}&role_id=${roleId}&koperasi_id=${koperasiId || ''}`;

    try {
        const response = await fetch('/api/auth/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: payload
        });

        const res = await response.json();

        if (response.ok) {
            logConsole(`Registrasi berhasil untuk: ${name}. Mengalihkan ke login.`);
            const loginEmailInput = document.getElementById('web-login-email');
            const loginPassInput = document.getElementById('web-login-pass');
            if (loginEmailInput) loginEmailInput.value = email;
            if (loginPassInput) loginPassInput.value = password;
            toggleWebAuthMode('login');
            await handleWebLogin();
        } else {
            if (errMsg) errMsg.innerText = res.message || 'Registrasi gagal. Email mungkin sudah terdaftar.';
            if (errAlert) errAlert.classList.remove('hidden');
        }
    } catch (e) {
        logConsole('Koneksi backend API bermasalah. Menggunakan registrasi offline.', 'error');
        // Offline Fallback for Development Simulation
        const mockNewUserId = state.users.length + 1;
        const roleNameMap = {
            '1': 'Super Admin',
            '2': 'Admin',
            '3': 'User',
            '4': 'Customer'
        };
        const coopName = koperasiId ? (state.cooperatives.find(c => c.id == koperasiId)?.nama_koperasi || '-') : '-';
        const mockUser = {
            id: mockNewUserId,
            nama: name,
            email: email,
            password: password, // Store password to match offline login
            role_name: roleNameMap[roleId] || 'Customer',
            koperasi_name: coopName,
            status: 'active',
            role_id: parseInt(roleId),
            koperasi_id: koperasiId ? parseInt(koperasiId) : null
        };

        state.users.push(mockUser);
        logConsole(`Registrasi berhasil (Simulasi Offline): ${name}. Mengalihkan ke login.`);
        
        // Auto Login Mock
        const loginEmailInput = document.getElementById('web-login-email');
        const loginPassInput = document.getElementById('web-login-pass');
        if (loginEmailInput) loginEmailInput.value = email;
        if (loginPassInput) loginPassInput.value = password;
        toggleWebAuthMode('login');
        handleOfflineWebLogin(email, password);
    } finally {
        regBtn.disabled = false;
        regBtn.innerHTML = originalBtnHTML;
    }
}

// Offline fallback for development (mock login if backend is unreachable)
function handleOfflineWebLogin(emailInput, password) {
    let email = emailInput;
    if (emailInput.indexOf('@') === -1) {
        if (emailInput === 'superadmin') {
            email = 'superadmin@kopdigi.id';
        } else if (emailInput === 'dinas') {
            email = 'dinas@kopdigi.id';
        } else if (emailInput === 'admin') {
            email = 'admin.kopa@kopdigi.id';
        } else {
            email = emailInput + '@kopdigi.id';
        }
    }

    // Find mock user
    const mockUser = state.users.find(u => u.email === email && u.status === 'active');
    const isValidPass = mockUser && (password === 'password123' || (mockUser.password && password === mockUser.password));
    if (mockUser && isValidPass) {
        const roleIdMap = {
            'Super Admin': 1,
            'Admin': 2,
            'User': 3,
            'Customer': 4
        };
        const mockSessionUser = {
            id: mockUser.id,
            nama: mockUser.nama,
            email: mockUser.email,
            role_id: roleIdMap[mockUser.role_name] || 4,
            koperasi_id: mockUser.koperasi_id || null,
            status: 'active'
        };

        localStorage.setItem('web_token', 'mock_jwt_token_xyz123');
        localStorage.setItem('web_user', JSON.stringify(mockSessionUser));

        logConsole(`User logged in (Simulasi Offline): ${mockSessionUser.nama}`);
        
        closeWebLoginModal();
        if (mockSessionUser.role_id == 4) {
            applyCustomerSession(mockSessionUser);
        } else {
            applyWebSession(mockSessionUser);
        }
    } else {
        showWebLoginError('Email atau password salah (Kredensial simulasi salah).');
    }
}

// Apply Web Session State to UI
function applyWebSession(user) {
    // 1. Hide login modal, hide marketplace viewport, show main layout
    closeWebLoginModal();
    const marketViewport = document.getElementById('marketplace-viewport');
    const mainApp = document.getElementById('main-app-layout');
    if (marketViewport) marketViewport.classList.add('hidden');
    if (mainApp) mainApp.classList.remove('hidden');

    // 2. Map role_id to activeRole string
    let roleStr = 'superadmin';
    let roleDisplayName = 'Super Admin';
    if (user.role_id == 2) {
        roleStr = 'dinasadmin';
        roleDisplayName = 'Admin';
    } else if (user.role_id == 3) {
        roleStr = 'coopadmin';
        roleDisplayName = 'User';
    }

    state.activeRole = roleStr;
    state.adminSession = user;
    state.adminToken = localStorage.getItem('web_token');

    // Set coop context if coop admin
    if (user.role_id == 3 && user.koperasi_id) {
        state.coopId = user.koperasi_id;
    }

    // 3. Update Profile Card UI
    const profileName = document.getElementById('user-profile-name');
    const profileRole = document.getElementById('user-profile-role');
    const profileAvatar = document.getElementById('user-profile-avatar');
    const profileCoop = document.getElementById('user-profile-coop');

    if (profileName) profileName.innerText = user.nama;
    if (profileRole) profileRole.innerText = roleDisplayName;
    if (profileAvatar) profileAvatar.innerText = user.nama.charAt(0).toUpperCase();

    if (profileCoop) {
        if (user.role_id == 3 && state.cooperatives.length > 0) {
            const coop = state.cooperatives.find(c => c.id == state.coopId);
            if (coop) {
                profileCoop.innerText = coop.nama_koperasi;
                profileCoop.classList.remove('hidden');
            } else {
                profileCoop.classList.add('hidden');
            }
        } else {
            profileCoop.classList.add('hidden');
        }
    }

    // 4. Update sidebar menu navigation visibility
    document.querySelectorAll('.sidebar-menu-group').forEach(el => el.style.display = 'none');
    
    // Explicitly show active menu
    const targetMenu = document.getElementById(`menu-${roleStr}`);
    if (targetMenu) {
        targetMenu.style.display = 'block';
    }

    applyRolePermissions();

    // Update active switcher value (if it exists)
    const switcher = document.getElementById('role-switcher');
    if (switcher) {
        switcher.value = roleStr;
    }

    // 5. Select the default tab for this role
    let defaultTab = 'super-dashboard';
    if (roleStr === 'dinasadmin') defaultTab = 'dinas-dashboard';
    if (roleStr === 'coopadmin') defaultTab = 'coop-dashboard';

    state.activeTab = defaultTab;

    // Toggle active tab class in UI
    document.querySelectorAll('.menu-item').forEach(el => el.classList.remove('active'));
    const targetTabBtn = document.querySelector(`#menu-${roleStr} .menu-item[data-tab="${defaultTab}"]`);
    if (targetTabBtn) targetTabBtn.classList.add('active');

    // Context title update for Coop Admin
    if (roleStr === 'coopadmin' && state.cooperatives.length > 0) {
        const activeCoop = state.cooperatives.find(c => c.id == state.coopId);
        if (activeCoop) {
            const coopTitle = document.getElementById('c-store-title-dashboard');
            const coopBadge = document.getElementById('c-store-badge-dashboard');
            if (coopTitle) coopTitle.innerText = 'Dashboard ' + activeCoop.nama_koperasi;
            if (coopBadge) coopBadge.innerText = 'Koperasi ' + activeCoop.status;
        }
    }

    // 6. Render workspace panel contents
    renderWorkspace();
}

// Check and apply web admin session
function checkWebSession() {
    const token = localStorage.getItem('web_token');
    const userJson = localStorage.getItem('web_user');
    
    if (token && userJson) {
        try {
            const user = JSON.parse(userJson);
            if (user.role_id == 4) {
                applyCustomerSession(user);
            } else {
                applyWebSession(user);
            }
        } catch (e) {
            localStorage.removeItem('web_token');
            localStorage.removeItem('web_user');
            applyGuestSession();
        }
    } else {
        applyGuestSession();
    }
}

// Apply Guest Session to UI
function applyGuestSession() {
    closeWebLoginModal();
    const marketViewport = document.getElementById('marketplace-viewport');
    const mainApp = document.getElementById('main-app-layout');
    if (marketViewport) marketViewport.classList.remove('hidden');
    if (mainApp) mainApp.classList.add('hidden');

    const guestLoginBtn = document.getElementById('market-guest-login-btn');
    const custProfile = document.getElementById('market-customer-profile');
    if (guestLoginBtn) guestLoginBtn.classList.remove('hidden');
    if (custProfile) custProfile.classList.add('hidden');

    state.customerSession = null;
    state.adminSession = null;
    state.adminToken = null;
    renderMarketplace();
}

// Apply Customer Session to UI
function applyCustomerSession(user) {
    closeWebLoginModal();
    const marketViewport = document.getElementById('marketplace-viewport');
    const mainApp = document.getElementById('main-app-layout');
    if (marketViewport) marketViewport.classList.remove('hidden');
    if (mainApp) mainApp.classList.add('hidden');

    const guestLoginBtn = document.getElementById('market-guest-login-btn');
    const custProfile = document.getElementById('market-customer-profile');
    if (guestLoginBtn) guestLoginBtn.classList.add('hidden');
    if (custProfile) custProfile.classList.remove('hidden');

    const nameEl = document.getElementById('market-customer-name');
    const avatarEl = document.getElementById('market-customer-avatar');
    if (nameEl) nameEl.innerText = user.nama;
    if (avatarEl) {
        if (user.foto_profil) {
            avatarEl.innerHTML = `<img src="${resolveAssetPath(user.foto_profil)}" class="w-full h-full object-cover rounded-lg border border-slate-700/50">`;
        } else {
            avatarEl.innerText = user.nama.charAt(0).toUpperCase();
        }
    }

    state.customerSession = user;
    renderMarketplace();
}

// Log Out Web Admin
function handleWebLogout() {
    // Clear localStorage
    localStorage.removeItem('web_token');
    localStorage.removeItem('web_user');

    // Reset fields
    const emailInput = document.getElementById('web-login-email');
    const passInput = document.getElementById('web-login-pass');
    if (emailInput) emailInput.value = '';
    if (passInput) passInput.value = '';

    // Clear cart and state
    state.marketCart = [];
    state.customerSession = null;

    // Go to guest session
    applyGuestSession();

    logConsole('User logged out.');
}

// Show/Hide Web Password Visibility
function toggleWebPasswordVisibility() {
    const passInput = document.getElementById('web-login-pass');
    const toggleIcon = document.getElementById('web-password-toggle-icon');
    if (!passInput || !toggleIcon) return;

    if (passInput.type === 'password') {
        passInput.type = 'text';
        toggleIcon.innerText = 'visibility_off';
    } else {
        passInput.type = 'password';
        toggleIcon.innerText = 'visibility';
    }
}

// Open Edit User Modal
function openEditUserModal(id) {
    const modal = document.getElementById('edit-user-modal');
    if (!modal) return;

    let user = state.users.find(u => u.id == id);
    if (!user) {
        const mockUsers = [
            { id: 1, nama: 'Yusuf Fikri', email: 'superadmin@kopdigi.id', role_name: 'Super Admin', koperasi_name: 'Dinas Pusat', status: 'active', role_id: 1, koperasi_id: null },
            { id: 2, nama: 'Hendra Wijaya', email: 'dinas@kopdigi.id', role_name: 'Admin', koperasi_name: 'Dinas Gorontalo', status: 'active', role_id: 2, koperasi_id: null },
            { id: 3, nama: 'Admin KPRI Gorontalo', email: 'admin.kopa@kopdigi.id', role_name: 'User', koperasi_name: 'KPRI Gorontalo', status: 'active', role_id: 3, koperasi_id: 1 },
            { id: 7, nama: 'Budi Santoso', email: 'budi@gmail.com', role_name: 'Customer', koperasi_name: '-', status: 'active', role_id: 4, koperasi_id: null }
        ];
        user = mockUsers.find(u => u.id == id);
    }

    if (!user) return;

    document.getElementById('edit-user-id').value = user.id;
    document.getElementById('edit-user-nama').value = user.nama;
    document.getElementById('edit-user-email').value = user.email;
    document.getElementById('edit-user-role').value = user.role_id || (user.role_name === 'Super Admin' ? 1 : (user.role_name === 'Admin' ? 2 : (user.role_name === 'User' ? 3 : 4)));
    document.getElementById('edit-user-status').value = user.status;
    document.getElementById('edit-user-pass').value = '';

    const coopSelect = document.getElementById('edit-user-coop');
    if (coopSelect) {
        coopSelect.innerHTML = '<option value="">-</option>';
        state.cooperatives.forEach(c => {
            coopSelect.innerHTML += `<option value="${c.id}">${c.nama_koperasi}</option>`;
        });
        coopSelect.value = user.koperasi_id || '';
    }

    modal.classList.remove('hidden');
    modal.style.display = 'flex';
}

// Close Modal
function closeEditUserModal() {
    const modal = document.getElementById('edit-user-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
}

// Save Changes
async function saveEditedUser() {
    const id = document.getElementById('edit-user-id').value;
    const nama = document.getElementById('edit-user-nama').value;
    const email = document.getElementById('edit-user-email').value;
    const roleId = document.getElementById('edit-user-role').value;
    const status = document.getElementById('edit-user-status').value;
    const koperasiId = document.getElementById('edit-user-coop').value;
    const password = document.getElementById('edit-user-pass').value;

    const payload = `nama=${encodeURIComponent(nama)}&email=${encodeURIComponent(email)}&role_id=${roleId}&status=${status}&koperasi_id=${koperasiId}&password=${encodeURIComponent(password)}`;

    try {
        const response = await fetch(`/api/users/${id}/update`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: payload
        });

        const res = await response.json();
        if (response.ok) {
            logConsole(`Sukses memperbarui user: ${nama}`);
            await loadAllData();
            closeEditUserModal();
        } else {
            alert(res.message || 'Gagal menyimpan perubahan');
        }
    } catch (e) {
        logConsole('Koneksi API gagal. Menyimpan perubahan secara lokal (simulasi).', 'warning');
        
        let user = state.users.find(u => u.id == id);
        if (!user) {
            setupLocalMockData();
            user = state.users.find(u => u.id == id);
        }

        if (user) {
            user.nama = nama;
            user.email = email;
            user.role_id = parseInt(roleId);
            user.status = status;
            user.koperasi_id = koperasiId ? parseInt(koperasiId) : null;
            
            const rolesMap = { 1: 'Super Admin', 2: 'Admin', 3: 'User', 4: 'Customer' };
            user.role_name = rolesMap[roleId];

            if (user.koperasi_id) {
                const coop = state.cooperatives.find(c => c.id == user.koperasi_id);
                user.koperasi_name = coop ? coop.nama_koperasi : '-';
            } else {
                user.koperasi_name = '-';
            }
        }

        renderSuperUsersTable();
        closeEditUserModal();
    }
}

// Open Add Coop Modal
function openAddCoopModal() {
    const modal = document.getElementById('add-coop-modal');
    if (!modal) return;

    // Reset inputs
    document.getElementById('add-coop-kode').value = '';
    document.getElementById('add-coop-nama').value = '';
    document.getElementById('add-coop-alamat').value = '';
    document.getElementById('add-coop-logo').value = '';
    document.getElementById('add-coop-kabupaten').selectedIndex = 0;

    modal.classList.remove('hidden');
    modal.style.display = 'flex';
}

// Close Add Coop Modal
function closeAddCoopModal() {
    const modal = document.getElementById('add-coop-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
}

// Save New Cooperative
async function saveNewCoop() {
    const kode = document.getElementById('add-coop-kode').value.trim();
    const nama = document.getElementById('add-coop-nama').value.trim();
    const alamat = document.getElementById('add-coop-alamat').value.trim();
    const kabupaten = document.getElementById('add-coop-kabupaten').value;
    const provinsi = document.getElementById('add-coop-provinsi').value;
    const logo = document.getElementById('add-coop-logo').value.trim();

    const userSession = JSON.parse(localStorage.getItem('web_user') || '{}');
    const userId = userSession.id || 1;

    const payload = `kode_koperasi=${encodeURIComponent(kode)}&nama_koperasi=${encodeURIComponent(nama)}&alamat=${encodeURIComponent(alamat)}&kabupaten=${encodeURIComponent(kabupaten)}&provinsi=${encodeURIComponent(provinsi)}&logo=${encodeURIComponent(logo)}&user_id=${userId}`;

    try {
        const response = await fetch('/api/cooperatives', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: payload
        });

        const res = await response.json();
        if (response.ok) {
            logConsole(`Sukses mendaftarkan koperasi baru: ${nama}`);
            await loadAllData();
            closeAddCoopModal();
        } else {
            alert(res.message || 'Gagal menambahkan koperasi');
        }
    } catch (e) {
        logConsole('Koneksi API gagal. Menambahkan secara lokal (simulasi).', 'warning');
        
        const newCoopId = state.cooperatives.length + 1;
        const newCoop = {
            id: newCoopId,
            kode_koperasi: kode,
            nama_koperasi: nama,
            alamat: alamat,
            kabupaten: kabupaten,
            provinsi: provinsi,
            logo: logo || 'https://images.unsplash.com/photo-1543269865-cbf427effbad?w=150',
            status: 'pending',
            created_at: new Date().toISOString()
        };
        
        state.cooperatives.push(newCoop);
        renderSuperCoopsList();
        closeAddCoopModal();
    }
}

function populateRegionDropdowns() {
    const addSelect = document.getElementById('add-coop-kabupaten');
    const editSelect = document.getElementById('edit-coop-kabupaten');
    if (!addSelect || !editSelect) return;
    
    if (state.regions.length === 0) {
        const fallbackOptions = `
            <option value="Kota Gorontalo">Kota Gorontalo</option>
            <option value="Kabupaten Gorontalo">Kabupaten Gorontalo</option>
            <option value="Kabupaten Bone Bolango">Kabupaten Bone Bolango</option>
            <option value="Kabupaten Boalemo">Kabupaten Boalemo</option>
            <option value="Kabupaten Gorontalo Utara">Kabupaten Gorontalo Utara</option>
            <option value="Kabupaten Pohuwato">Kabupaten Pohuwato</option>
        `;
        addSelect.innerHTML = fallbackOptions;
        editSelect.innerHTML = fallbackOptions;
        return;
    }

    const optionsHTML = state.regions.map(r => `<option value="${r.nama_wilayah}">${r.nama_wilayah}</option>`).join('');
    addSelect.innerHTML = optionsHTML;
    editSelect.innerHTML = optionsHTML;
}

// Edit Koperasi Modal Handlers
function openEditCoopModal(id) {
    const coop = state.cooperatives.find(c => c.id == id);
    if (!coop) return;

    document.getElementById('edit-coop-id').value = coop.id;
    document.getElementById('edit-coop-kode').value = coop.kode_koperasi;
    document.getElementById('edit-coop-nama').value = coop.nama_koperasi;
    document.getElementById('edit-coop-alamat').value = coop.alamat;
    document.getElementById('edit-coop-kabupaten').value = coop.kabupaten;
    document.getElementById('edit-coop-logo').value = coop.logo || '';
    document.getElementById('edit-coop-status').value = coop.status;

    const modal = document.getElementById('edit-coop-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
    }
}

function closeEditCoopModal() {
    const modal = document.getElementById('edit-coop-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
}

async function saveEditCoop() {
    const id = document.getElementById('edit-coop-id').value;
    const kode = document.getElementById('edit-coop-kode').value.trim();
    const nama = document.getElementById('edit-coop-nama').value.trim();
    const alamat = document.getElementById('edit-coop-alamat').value.trim();
    const kabupaten = document.getElementById('edit-coop-kabupaten').value;
    const provinsi = document.getElementById('edit-coop-provinsi').value;
    const logo = document.getElementById('edit-coop-logo').value.trim();
    const status = document.getElementById('edit-coop-status').value;

    const userSession = JSON.parse(localStorage.getItem('web_user') || '{}');
    const userId = userSession.id || 1;

    const payload = `kode_koperasi=${encodeURIComponent(kode)}&nama_koperasi=${encodeURIComponent(nama)}&alamat=${encodeURIComponent(alamat)}&kabupaten=${encodeURIComponent(kabupaten)}&provinsi=${encodeURIComponent(provinsi)}&logo=${encodeURIComponent(logo)}&status=${encodeURIComponent(status)}&user_id=${userId}`;

    try {
        const response = await fetch(`/api/cooperatives/${id}/update`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: payload
        });

        const res = await response.json();
        if (response.ok) {
            logConsole(`Sukses memperbarui informasi koperasi: ${nama}`);
            await loadAllData();
            closeEditCoopModal();
        } else {
            alert(res.message || 'Gagal memperbarui koperasi');
        }
    } catch (e) {
        logConsole('Koneksi API gagal. Memperbarui secara lokal (simulasi).', 'warning');
        
        const coopIndex = state.cooperatives.findIndex(c => c.id == id);
        if (coopIndex !== -1) {
            state.cooperatives[coopIndex] = {
                ...state.cooperatives[coopIndex],
                kode_koperasi: kode,
                nama_koperasi: nama,
                alamat: alamat,
                kabupaten: kabupaten,
                provinsi: provinsi,
                logo: logo || state.cooperatives[coopIndex].logo,
                status: status
            };
            logConsole(`Profil Koperasi (simulasi) "${nama}" berhasil diperbarui.`);
            renderSuperCoopsList();
            renderSuperCoopsVerif();
            updateStatsDashboard();
            closeEditCoopModal();
        }
    }
}

async function deleteCooperative(id) {
    const coop = state.cooperatives.find(c => c.id == id);
    if (!coop) return;

    if (!confirm(`Apakah Anda yakin ingin menghapus Koperasi "${coop.nama_koperasi}"? Tindakan ini tidak dapat dibatalkan.`)) {
        return;
    }

    const userSession = JSON.parse(localStorage.getItem('web_user') || '{}');
    const userId = userSession.id || 1;

    try {
        const response = await fetch(`/api/cooperatives/${id}/delete`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `user_id=${userId}`
        });

        const res = await response.json();
        if (response.ok) {
            logConsole(`Koperasi "${coop.nama_koperasi}" berhasil dihapus.`);
            await loadAllData();
        } else {
            alert(res.message || 'Gagal menghapus koperasi');
        }
    } catch (e) {
        logConsole('Koneksi API gagal. Menghapus secara lokal (simulasi).', 'warning');
        state.cooperatives = state.cooperatives.filter(c => c.id != id);
        renderSuperCoopsList();
        renderSuperCoopsVerif();
        updateStatsDashboard();
    }
}

/* ----------------------------------------------------
 * WILAYAH KOPERASI CRUD HELPERS
 * ---------------------------------------------------- */

function renderSuperCoopsWilayah() {
    const tbody = document.getElementById('s-regions-list-table');
    if (!tbody) return;
    tbody.innerHTML = '';

    if (state.regions.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center py-4 text-slate-500">Belum ada data wilayah.</td></tr>';
        return;
    }

    state.regions.forEach(r => {
        const activeCount = state.cooperatives.filter(c => c.kabupaten === r.nama_wilayah && c.status === 'aktif').length;
        const totalCount = state.cooperatives.filter(c => c.kabupaten === r.nama_wilayah).length;

        tbody.innerHTML += `
            <tr class="border-b border-slate-800/40">
                <td class="py-3 px-4 text-slate-400 font-bold">${r.id}</td>
                <td class="py-3 px-4 text-slate-200 font-semibold">${r.nama_wilayah}</td>
                <td class="py-3 px-4 text-slate-400">${r.provinsi}</td>
                <td class="py-3 px-4 text-slate-400 text-xs">${r.deskripsi || '-'}</td>
                <td class="py-3 px-4">
                    <span class="px-2.5 py-1 bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 rounded-full text-xs font-semibold">
                        ${activeCount} Aktif (${totalCount} Total)
                    </span>
                </td>
                <td class="py-3 px-4">
                    <div class="flex gap-2">
                        <button class="px-2.5 py-1.5 bg-blue-600/90 hover:bg-blue-500 text-white rounded-xl text-[10px] font-bold transition flex items-center gap-1" onclick="openEditRegionModal(${r.id})">
                            <span class="material-symbols-outlined text-[12px]">edit</span>
                            <span>EDIT</span>
                        </button>
                        <button class="px-2.5 py-1.5 bg-rose-600/95 hover:bg-rose-500 text-white rounded-xl text-[10px] font-bold transition flex items-center gap-1" onclick="deleteRegion(${r.id})">
                            <span class="material-symbols-outlined text-[12px]">delete</span>
                            <span>HAPUS</span>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
}

function openAddRegionModal() {
    const modal = document.getElementById('add-region-modal');
    if (!modal) return;

    document.getElementById('add-region-nama').value = '';
    document.getElementById('add-region-deskripsi').value = '';
    
    modal.classList.remove('hidden');
    modal.style.display = 'flex';
}

function closeAddRegionModal() {
    const modal = document.getElementById('add-region-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
}

async function saveNewRegion() {
    const nama = document.getElementById('add-region-nama').value.trim();
    const provinsi = document.getElementById('add-region-provinsi').value;
    const deskripsi = document.getElementById('add-region-deskripsi').value.trim();

    const userSession = JSON.parse(localStorage.getItem('web_user') || '{}');
    const userId = userSession.id || 1;

    const payload = `nama_wilayah=${encodeURIComponent(nama)}&provinsi=${encodeURIComponent(provinsi)}&deskripsi=${encodeURIComponent(deskripsi)}&user_id=${userId}`;

    try {
        const response = await fetch('/api/regions', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: payload
        });

        const res = await response.json();
        if (response.ok) {
            logConsole(`Sukses menambahkan wilayah pengawasan baru: ${nama}`);
            await loadAllData();
            closeAddRegionModal();
        } else {
            alert(res.message || 'Gagal menambahkan wilayah');
        }
    } catch (e) {
        logConsole('Koneksi API gagal. Menambahkan wilayah secara lokal (simulasi).', 'warning');
        
        const newRegionId = state.regions.length > 0 ? Math.max(...state.regions.map(r => r.id)) + 1 : 1;
        const newRegion = {
            id: newRegionId,
            nama_wilayah: nama,
            provinsi: provinsi,
            deskripsi: deskripsi,
            created_at: new Date().toISOString()
        };

        state.regions.push(newRegion);
        renderSuperCoopsWilayah();
        populateRegionDropdowns();
        renderSuperDashboardRegions();
        closeAddRegionModal();
    }
}

function openEditRegionModal(id) {
    const region = state.regions.find(r => r.id == id);
    if (!region) return;

    document.getElementById('edit-region-id').value = region.id;
    document.getElementById('edit-region-nama').value = region.nama_wilayah;
    document.getElementById('edit-region-provinsi').value = region.provinsi;
    document.getElementById('edit-region-deskripsi').value = region.deskripsi || '';

    const modal = document.getElementById('edit-region-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
    }
}

function closeEditRegionModal() {
    const modal = document.getElementById('edit-region-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
}

async function saveEditRegion() {
    const id = document.getElementById('edit-region-id').value;
    const nama = document.getElementById('edit-region-nama').value.trim();
    const provinsi = document.getElementById('edit-region-provinsi').value;
    const deskripsi = document.getElementById('edit-region-deskripsi').value.trim();

    const userSession = JSON.parse(localStorage.getItem('web_user') || '{}');
    const userId = userSession.id || 1;

    const payload = `nama_wilayah=${encodeURIComponent(nama)}&provinsi=${encodeURIComponent(provinsi)}&deskripsi=${encodeURIComponent(deskripsi)}&user_id=${userId}`;

    try {
        const response = await fetch(`/api/regions/${id}/update`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: payload
        });

        const res = await response.json();
        if (response.ok) {
            logConsole(`Sukses memperbarui informasi wilayah: ${nama}`);
            await loadAllData();
            closeEditRegionModal();
        } else {
            alert(res.message || 'Gagal memperbarui wilayah');
        }
    } catch (e) {
        logConsole('Koneksi API gagal. Memperbarui secara lokal (simulasi).', 'warning');
        
        const regionIndex = state.regions.findIndex(r => r.id == id);
        if (regionIndex !== -1) {
            state.regions[regionIndex] = {
                ...state.regions[regionIndex],
                nama_wilayah: nama,
                provinsi: provinsi,
                deskripsi: deskripsi
            };
            logConsole(`Wilayah (simulasi) "${nama}" berhasil diperbarui.`);
            renderSuperCoopsWilayah();
            populateRegionDropdowns();
            renderSuperDashboardRegions();
            closeEditRegionModal();
        }
    }
}

async function deleteRegion(id) {
    const region = state.regions.find(r => r.id == id);
    if (!region) return;

    if (!confirm(`Apakah Anda yakin ingin menghapus Wilayah "${region.nama_wilayah}"?`)) {
        return;
    }

    const userSession = JSON.parse(localStorage.getItem('web_user') || '{}');
    const userId = userSession.id || 1;

    try {
        const response = await fetch(`/api/regions/${id}/delete`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `user_id=${userId}`
        });

        const res = await response.json();
        if (response.ok) {
            logConsole(`Wilayah "${region.nama_wilayah}" berhasil dihapus.`);
            await loadAllData();
        } else {
            alert(res.message || 'Gagal menghapus wilayah');
        }
    } catch (e) {
        logConsole('Koneksi API gagal. Menghapus secara lokal (simulasi).', 'warning');
        state.regions = state.regions.filter(r => r.id != id);
        renderSuperCoopsWilayah();
        populateRegionDropdowns();
        renderSuperDashboardRegions();
    }
}

/* ----------------------------------------------------
 * BUSINESS INTELLIGENCE (BI) REPORTS RENDERING
 * ---------------------------------------------------- */

let biRevenueChartInstance = null;
let biCategoryChartInstance = null;

async function renderSuperReports() {
    let data;

    try {
        const response = await fetch('/api/reports/bi?_t=' + new Date().getTime());
        if (!response.ok) throw new Error('BI API offline');
        const res = await response.json();
        data = res.data;
    } catch (e) {
        logConsole('Gagal memuat BI Report dari API. Menjalankan mesin kalkulasi BI lokal.', 'warning');
        data = calculateLocalBiReport();
    }

    // 1. Render BI Summary Cards
    const revEl = document.getElementById('bi-card-revenue');
    const ordEl = document.getElementById('bi-card-orders');
    const aovEl = document.getElementById('bi-card-aov');
    const prdEl = document.getElementById('bi-card-products');

    if (revEl) revEl.innerText = 'Rp ' + Number(data.cards.total_revenue).toLocaleString('id-ID');
    if (ordEl) ordEl.innerText = `${data.cards.total_orders} Transaksi`;
    if (aovEl) aovEl.innerText = 'Rp ' + Number(data.cards.average_order).toLocaleString('id-ID');
    if (prdEl) prdEl.innerText = `${data.cards.total_products} Produk`;

    // 2. Render Daily Trend Chart (Chart.js Line)
    const ctxRevenue = document.getElementById('bi-revenue-chart');
    if (ctxRevenue) {
        if (biRevenueChartInstance) {
            biRevenueChartInstance.destroy();
        }

        const labels = data.daily_trend.map(d => d.date);
        const revenues = data.daily_trend.map(d => parseFloat(d.revenue));

        const ctx2d = ctxRevenue.getContext('2d');
        const gradient = ctx2d.createLinearGradient(0, 0, 0, 200);
        gradient.addColorStop(0, 'rgba(225, 29, 72, 0.4)');
        gradient.addColorStop(1, 'rgba(225, 29, 72, 0)');

        biRevenueChartInstance = new Chart(ctxRevenue, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Pendapatan',
                    data: revenues,
                    borderColor: '#E11D48',
                    borderWidth: 2.5,
                    pointBackgroundColor: '#E11D48',
                    pointHoverRadius: 6,
                    fill: true,
                    backgroundColor: gradient,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { color: '#94A3B8', font: { size: 9, family: 'Outfit' } }
                    },
                    y: {
                        grid: { color: 'rgba(148, 163, 184, 0.08)' },
                        ticks: {
                            color: '#94A3B8',
                            font: { size: 9, family: 'Outfit' },
                            callback: function(value) {
                                if (value >= 1000000) return (value / 1000000).toFixed(1) + 'jt';
                                if (value >= 1000) return (value / 1000) + 'rb';
                                return value;
                            }
                        }
                    }
                }
            }
        });
    }

    // 3. Render Category Contribution Chart (Chart.js Doughnut)
    const ctxCategory = document.getElementById('bi-category-chart');
    if (ctxCategory) {
        if (biCategoryChartInstance) {
            biCategoryChartInstance.destroy();
        }

        const labels = data.category_sales.map(c => c.category);
        const sales = data.category_sales.map(c => parseFloat(c.sales));

        biCategoryChartInstance = new Chart(ctxCategory, {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: sales,
                    backgroundColor: [
                        '#E11D48', // Rose
                        '#3B82F6', // Blue
                        '#10B981', // Emerald
                        '#F59E0B', // Amber
                        '#8B5CF6'  // Purple
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right',
                        labels: {
                            color: '#94A3B8',
                            boxWidth: 10,
                            font: { size: 9, family: 'Outfit' }
                        }
                    }
                },
                cutout: '72%'
            }
        });
    }

    // 4. Render Top Selling Table
    const topTbody = document.getElementById('bi-top-selling-table');
    if (topTbody) {
        topTbody.innerHTML = '';
        data.top_products.forEach(p => {
            topTbody.innerHTML += `
                <tr class="border-b border-slate-800/40 hover:bg-white/5 transition">
                    <td class="py-3 px-1 flex items-center gap-2">
                        <img src="${p.foto || 'https://images.unsplash.com/photo-1586201375761-83865001e31c?w=150'}" class="w-7 h-7 rounded-lg object-cover">
                        <span class="font-semibold text-slate-200 truncate max-w-[120px]">${p.nama_produk}</span>
                    </td>
                    <td class="py-3 px-1 text-slate-400 truncate max-w-[120px]">${p.nama_koperasi}</td>
                    <td class="py-3 px-1 text-right font-bold text-slate-200">${p.qty_sold} ${p.satuan || 'unit'}</td>
                    <td class="py-3 px-1 text-right text-emerald-400 font-semibold">Rp ${Number(p.revenue).toLocaleString('id-ID')}</td>
                </tr>
            `;
        });
    }

    // 5. Render Low Stock Warnings Table
    const lowTbody = document.getElementById('bi-low-stock-table');
    if (lowTbody) {
        lowTbody.innerHTML = '';
        data.low_stock.forEach(p => {
            const isCritical = p.stok <= 5;
            const badgeClass = isCritical ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 'bg-amber-500/10 text-amber-400 border border-amber-500/20';
            const badgeText = isCritical ? 'KRITIS' : 'RESTOCK';

            lowTbody.innerHTML += `
                <tr class="border-b border-slate-800/40 hover:bg-white/5 transition">
                    <td class="py-3 px-1 font-semibold text-slate-200 truncate max-w-[140px]">${p.nama_produk}</td>
                    <td class="py-3 px-1 text-slate-400 truncate max-w-[120px]">${p.nama_koperasi}</td>
                    <td class="py-3 px-1 text-center font-bold ${isCritical ? 'text-red-400' : 'text-amber-400'}">${p.stok} ${p.satuan || 'unit'}</td>
                    <td class="py-3 px-1 text-center">
                        <span class="px-2 py-0.5 rounded-full text-[9px] font-bold ${badgeClass}">
                            ${badgeText}
                        </span>
                    </td>
                </tr>
            `;
        });
    }

    // 6. Render BI Insights
    const insightTextEl = document.getElementById('bi-analysis-text');
    if (insightTextEl) {
        insightTextEl.innerHTML = parseMarkdownBI(data.insights.analysis);
    }

    const recsListEl = document.getElementById('bi-recommendations-list');
    if (recsListEl) {
        recsListEl.innerHTML = '';
        data.insights.recommendations.forEach(r => {
            recsListEl.innerHTML += `
                <li class="flex items-start gap-2 text-xs text-slate-400 leading-relaxed">
                    <span class="text-amber-400 font-bold select-none">•</span>
                    <span>${parseMarkdownBI(r)}</span>
                </li>
            `;
        });
    }
}

function parseMarkdownBI(text) {
    if (!text) return '';
    return text.replace(/\*\*(.*?)\*\*/g, '<strong class="text-white font-semibold">$1</strong>');
}

function calculateLocalBiReport() {
    // Fallback logic
    const totalOrders = state.orders.length;
    let totalRevenue = 0;
    state.orders.forEach(o => {
        if (['paid', 'processing', 'shipped', 'completed'].includes(o.status.toLowerCase())) {
            totalRevenue += parseFloat(o.total);
        }
    });

    const averageOrder = totalOrders > 0 ? (totalRevenue / totalOrders) : 0;
    const totalProducts = state.products.filter(p => p.status === 'aktif').length;

    // Daily Trend
    const dailyTrend = [
        { date: '24 Mei', revenue: 1500000 },
        { date: '25 Mei', revenue: 2400000 },
        { date: '26 Mei', revenue: 1800000 },
        { date: '27 Mei', revenue: 3200000 },
        { date: '28 Mei', revenue: 4500000 },
        { date: '29 Mei', revenue: 5100000 },
        { date: '30 Mei', revenue: totalRevenue > 0 ? totalRevenue : 6200000 }
    ];

    // Category Sales
    const categorySales = [
        { category: 'Sembako', sales: totalRevenue > 0 ? totalRevenue * 0.55 : 5000000 },
        { category: 'Kerajinan', sales: totalRevenue > 0 ? totalRevenue * 0.25 : 3200000 },
        { category: 'Fashion', sales: totalRevenue > 0 ? totalRevenue * 0.12 : 1800000 },
        { category: 'Pertanian', sales: totalRevenue > 0 ? totalRevenue * 0.08 : 1200000 }
    ];

    // Top Selling
    const topProducts = [];
    const mockSold = [45, 32, 28, 15, 12];
    const mockRev = [3510000, 1088000, 2660000, 675000, 540000];
    const limit = Math.min(state.products.length, 5);
    for (let i = 0; i < limit; i++) {
        const prod = state.products[i];
        const coop = state.cooperatives.find(c => c.id == prod.koperasi_id) || { nama_koperasi: 'KopMerahPutih' };
        topProducts.push({
            nama_produk: prod.nama_produk,
            foto: prod.foto,
            nama_koperasi: coop.nama_koperasi,
            satuan: prod.satuan || 'unit',
            qty_sold: mockSold[i] || 10,
            revenue: mockRev[i] || prod.harga * 10
        });
    }

    // Low Stock
    const lowStock = [];
    const lowProducts = state.products.filter(p => p.stok <= 15);
    lowProducts.forEach(prod => {
        const coop = state.cooperatives.find(c => c.id == prod.koperasi_id) || { nama_koperasi: 'KopMerahPutih' };
        lowStock.push({
            nama_produk: prod.nama_produk,
            stok: prod.stok,
            satuan: prod.satuan || 'unit',
            nama_koperasi: coop.nama_koperasi
        });
    });
    
    if (lowStock.length === 0) {
        lowStock.push(
            { nama_produk: 'Beras Pandan Wangi 5kg', stok: 5, satuan: 'kg', nama_koperasi: 'KPRI Gorontalo' },
            { nama_produk: 'Kaos Merah Putih Digital', stok: 8, satuan: 'pcs', nama_koperasi: 'Koperasi Merah Putih Sejahtera' },
            { nama_produk: 'Tas Anyaman Bambu Limboto', stok: 3, satuan: 'pcs', nama_koperasi: 'Koperasi Merah Putih Sejahtera' }
        );
    }

    // Insights
    const insights = {
        market_leader_category: 'Sembako',
        top_cooperative: 'Koperasi Merah Putih Sejahtera',
        revenue_status: 'Meningkat 12.5% dibanding minggu lalu.',
        analysis: "Simulasi analisis BI mendeteksi kategori **Sembako** memiliki kontribusi omzet tertinggi secara nasional. Koperasi **Koperasi Merah Putih Sejahtera** dinilai sebagai unit usaha paling produktif secara volume pesanan. Terjadi tren penguatan penjualan ritel.",
        recommendations: [
            "Segera lakukan restock untuk produk-produk di tabel Stok Menipis agar kontinuitas penjualan terjaga.",
            "Terapkan diskon bundling pada kategori **Kerajinan** untuk menarik minat pasar yang lesu.",
            "Optimalkan stok pergudangan dan pengiriman ekspedisi pada hari Sabtu-Minggu karena data BI menunjukkan lonjakan transaksi tertinggi."
        ]
    };

    return {
        cards: {
            total_revenue: totalRevenue > 0 ? totalRevenue : 12300000,
            total_orders: totalOrders > 0 ? totalOrders : 52,
            average_order: averageOrder > 0 ? averageOrder : 236538,
            total_products: totalProducts > 0 ? totalProducts : 6
        },
        daily_trend: dailyTrend,
        category_sales: categorySales,
        top_products: topProducts,
        low_stock: lowStock,
        insights: insights
    };
}

let currentChatCoopId = null;
let currentChatProductId = null;
let productChatHistories = {};

async function openProductChatModal(coopId, productId) {
    currentChatCoopId = coopId;
    currentChatProductId = productId;

    const coop = state.cooperatives.find(c => c.id == coopId);
    const prod = state.products.find(p => p.id == productId);
    if (!prod) return;
    
    const coopName = coop ? coop.nama_koperasi : 'Koperasi';
    const coopLogo = coop ? coop.logo : 'https://images.unsplash.com/photo-1586201375761-83865001e31c?w=150';

    // Set header details
    const logoEl = document.getElementById('chat-seller-logo');
    const nameEl = document.getElementById('chat-seller-name');
    const prodEl = document.getElementById('chat-product-name');

    if (logoEl) logoEl.src = coopLogo;
    if (nameEl) nameEl.innerText = coopName;
    if (prodEl) prodEl.innerText = `Tanya tentang: ${prod.nama_produk}`;

    const chatKey = `${coopId}-${productId}`;
    // Always reset and reload from DB
    productChatHistories[chatKey] = [];

    // Show loading in container while fetching
    const containerPreload = document.getElementById('chat-messages-container');
    if (containerPreload) {
        containerPreload.innerHTML = `<div class="flex items-center justify-center py-10 text-slate-500 text-xs gap-2"><span class="material-symbols-outlined text-base animate-spin">progress_activity</span> Memuat percakapan...</div>`;
    }

    const modal = document.getElementById('product-chat-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
    }

    // Try to fetch from API
    try {
        const customerId = state.customerSession ? state.customerSession.id : '';
        const res = await fetch(`/api/messages/thread?product_id=${productId}&koperasi_id=${coopId}&customer_id=${customerId}`);
        const data = await res.json();
        if (data.status === 'success' && data.data && data.data.length > 0) {
            productChatHistories[chatKey] = data.data.map(m => ({
                sender: m.sender_role === 'customer' ? (state.customerSession && m.sender_id == state.customerSession.id ? 'user' : 'other') : 'seller',
                text: m.message,
                time: new Date(m.created_at).toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }),
                senderName: m.sender_name
            }));
        }
    } catch(e) {}

    // If still empty (no DB record yet), save a welcome message from seller to DB
    if (productChatHistories[chatKey].length === 0) {
        const welcomeMsg = `Halo! Terima kasih telah menghubungi kami. Ada yang bisa kami bantu mengenai produk ${prod.nama_produk}?`;
        // Save welcome to DB so it persists
        try {
            await fetch('/api/messages', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `product_id=${productId}&koperasi_id=${coopId}&sender_role=seller&sender_name=${encodeURIComponent(coopName)}&message=${encodeURIComponent(welcomeMsg)}&product_name=${encodeURIComponent(prod.nama_produk)}`
            });
            // Re-fetch after saving
            const res2 = await fetch(`/api/messages/thread?product_id=${productId}&koperasi_id=${coopId}&customer_id=${state.customerSession ? state.customerSession.id : ''}`);
            const data2 = await res2.json();
            if (data2.status === 'success' && data2.data && data2.data.length > 0) {
                productChatHistories[chatKey] = data2.data.map(m => ({
                    sender: m.sender_role === 'customer' ? (state.customerSession && m.sender_id == state.customerSession.id ? 'user' : 'other') : 'seller',
                    text: m.message,
                    time: new Date(m.created_at).toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }),
                    senderName: m.sender_name
                }));
            }
        } catch(e) {
            productChatHistories[chatKey] = [{
                sender: 'seller',
                text: welcomeMsg,
                time: new Date().toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }),
                senderName: coopName
            }];
        }
    }

    renderProductChatMessages();

    // Update badge
    if (state.customerSession) {
        setTimeout(() => checkCustomerUnreadBadge(), 200);
    }

    // Start polling for new seller replies every 10 seconds
    if (_chatPollInterval) clearInterval(_chatPollInterval);
    _chatPollInterval = setInterval(_pollChatForNewMessages, 10000);
}

let _chatPollInterval = null;

function closeProductChatModal() {
    const modal = document.getElementById('product-chat-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
    currentChatCoopId = null;
    currentChatProductId = null;
    if (_chatPollInterval) {
        clearInterval(_chatPollInterval);
        _chatPollInterval = null;
    }
}

async function _pollChatForNewMessages() {
    if (!currentChatCoopId || !currentChatProductId) return;
    const chatKey = `${currentChatCoopId}-${currentChatProductId}`;
    const prevCount = productChatHistories[chatKey] ? productChatHistories[chatKey].length : 0;
    try {
        const customerId = state.customerSession ? state.customerSession.id : '';
        const res = await fetch(`/api/messages/thread?product_id=${currentChatProductId}&koperasi_id=${currentChatCoopId}&customer_id=${customerId}`);
        const data = await res.json();
        if (data.status === 'success' && data.data && data.data.length > prevCount) {
            productChatHistories[chatKey] = data.data.map(m => ({
                sender: m.sender_role === 'customer' ? (state.customerSession && m.sender_id == state.customerSession.id ? 'user' : 'other') : 'seller',
                text: m.message,
                time: new Date(m.created_at).toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }),
                senderName: m.sender_name
            }));
            renderProductChatMessages();
            checkCustomerUnreadBadge();
        }
    } catch(e) {}
}

function renderProductChatMessages() {
    const container = document.getElementById('chat-messages-container');
    if (!container) return;

    const chatKey = `${currentChatCoopId}-${currentChatProductId}`;
    const messages = productChatHistories[chatKey] || [];

    container.innerHTML = messages.map(msg => {
        const isUser = msg.sender === 'user';
        const isOther = msg.sender === 'other';
        const bgClass = isUser ? 'bg-primary/20 text-white border border-primary/30 font-semibold' : 'bg-slate-900 border border-slate-800 text-slate-300';
        const alignmentClass = isUser ? 'items-end self-end' : 'items-start self-start';
        
        let formattedText = msg.text.replace(/\*\*(.*?)\*\*/g, '<strong class="text-white font-bold">$1</strong>');
        
        let senderNameLabel = '';
        if (isOther) {
            senderNameLabel = `<div class="text-[10px] text-slate-500 mb-0.5 px-1">${msg.senderName || 'Pembeli Lain'}</div>`;
        } else if (!isUser) {
            senderNameLabel = `<div class="text-[10px] text-slate-500 mb-0.5 px-1">Seller</div>`;
        }
        
        return `
            <div class="flex flex-col ${alignmentClass} gap-1 max-w-[85%]">
                ${senderNameLabel}
                <div class="p-3 rounded-2xl ${bgClass} leading-relaxed">
                    ${formattedText}
                </div>
                <span class="text-[9px] text-slate-500 px-1">${msg.time}</span>
            </div>
        `;
    }).join('');

    // Scroll to bottom
    setTimeout(() => {
        container.scrollTop = container.scrollHeight;
    }, 50);
}

async function sendProductChatMessage() {
    const input = document.getElementById('chat-message-input');
    if (!input || !input.value.trim() || !currentChatCoopId || !currentChatProductId) return;

    // Require login to chat
    if (!state.customerSession) {
        closeProductChatModal();
        openWebLoginModal();
        return;
    }

    const text = input.value.trim();
    input.value = '';

    const prod = state.products.find(p => p.id == currentChatProductId);
    const buyerName = state.customerSession.nama || 'Pembeli';
    const buyerId   = state.customerSession.id;

    const chatKey = `${currentChatCoopId}-${currentChatProductId}`;
    const time = new Date().toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' });

    // Optimistic UI: show message immediately
    if (!productChatHistories[chatKey]) productChatHistories[chatKey] = [];
    productChatHistories[chatKey].push({ sender: 'user', text, time, senderName: buyerName });
    renderProductChatMessages();

    // Save to DB
    try {
        await fetch('/api/messages', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `product_id=${currentChatProductId}&koperasi_id=${currentChatCoopId}&sender_id=${buyerId}&sender_name=${encodeURIComponent(buyerName)}&sender_role=customer&message=${encodeURIComponent(text)}&product_name=${encodeURIComponent(prod ? prod.nama_produk : 'Produk')}`
        });
    } catch(e) {}
}


function handleProductChatKeyup(event) {
    if (event.key === 'Enter') {
        sendProductChatMessage();
    }
}

// Global exposure for onClick handlers
window.openProductChatModal = openProductChatModal;
window.closeProductChatModal = closeProductChatModal;
window.sendProductChatMessage = sendProductChatMessage;
window.handleProductChatKeyup = handleProductChatKeyup;
window.renderSuperReports = renderSuperReports;
window.toggleCoopStatus = toggleCoopStatus;
window.updateOrderStatus = updateOrderStatus;
window.saveCoopProfile = saveCoopProfile;
window.askSellerAi = askSellerAi;
window.submitNewProduct = submitNewProduct;
window.handlePhoneLogin = handlePhoneLogin;
window.switchPhoneView = switchPhoneView;
window.handleWebLogin = handleWebLogin;
window.handleWebLogout = handleWebLogout;
window.toggleWebPasswordVisibility = toggleWebPasswordVisibility;
window.openEditUserModal = openEditUserModal;
window.closeEditUserModal = closeEditUserModal;
window.saveEditedUser = saveEditedUser;
window.openAddCoopModal = openAddCoopModal;
window.closeAddCoopModal = closeAddCoopModal;
window.saveNewCoop = saveNewCoop;
window.openEditCoopModal = openEditCoopModal;
window.closeEditCoopModal = closeEditCoopModal;
window.saveEditCoop = saveEditCoop;
window.deleteCooperative = deleteCooperative;
window.renderSuperCoopsWilayah = renderSuperCoopsWilayah;
window.openAddRegionModal = openAddRegionModal;
window.closeAddRegionModal = closeAddRegionModal;
window.saveNewRegion = saveNewRegion;
window.openEditRegionModal = openEditRegionModal;
window.closeEditRegionModal = closeEditRegionModal;
window.saveEditRegion = saveEditRegion;
window.deleteRegion = deleteRegion;
window.handlePhoneRegister = handlePhoneRegister;
window.filterCoopSearch = filterCoopSearch;
window.visitCoopStore = visitCoopStore;
window.filterStoreCategory = filterStoreCategory;
window.openProductDetailPhone = openProductDetailPhone;
window.addProductToCart = addProductToCart;
window.updateCartQty = updateCartQty;
window.proceedToPayment = proceedToPayment;
window.confirmPaymentAndCheckout = confirmPaymentAndCheckout;
window.openOrderTracking = openOrderTracking;
window.sendChatMessage = sendChatMessage;
window.handleChatEnter = handleChatEnter;
window.setPhoneTab = setPhoneTab;

window.togglePermission = togglePermission;
window.resetPermissionsToDefault = resetPermissionsToDefault;

window.goToMarketView = goToMarketView;
window.visitMarketCoopStore = visitMarketCoopStore;
window.visitMarketProductDetail = visitMarketProductDetail;
window.handleMarketSearch = handleMarketSearch;
window.openWebLoginModal = openWebLoginModal;
window.closeWebLoginModal = closeWebLoginModal;
window.checkoutMarketOrder = checkoutMarketOrder;
window.toggleWebAuthMode = toggleWebAuthMode;
window.handleRegisterRoleChange = handleRegisterRoleChange;
window.handleWebRegister = handleWebRegister;
window.addProductToMarketCart = addProductToMarketCart;
window.updateMarketCartQty = updateMarketCartQty;
window.removeFromMarketCart = removeFromMarketCart;
window.buyNowMarketProduct = buyNowMarketProduct;
window.checkoutCartCoop = checkoutCartCoop;
window.showMarketToast = showMarketToast;
window.saveCoopSettings = saveCoopSettings;
window.initCoopSettings = initCoopSettings;
window.openMarketPaymentModal = openMarketPaymentModal;
window.openMarketPaymentModalByOrderId = openMarketPaymentModalByOrderId;
window.processSimulatedPayment = processSimulatedPayment;
window.updateOrderStatusLocalAndRemote = updateOrderStatusLocalAndRemote;
window.getStatusBadge = getStatusBadge;

// DEFAULT PERMISSIONS CONFIGURATION
const DEFAULT_PERMISSIONS = {
    superadmin: {
        'super-dashboard': true,
        'super-coops-daftar': true,
        'super-coops-verif': true,
        'super-coops-wilayah': true,
        'super-products': true,
        'super-orders': true,
        'super-reports': true,
        'super-audit': true,
        'super-users': true,
        'super-permissions': true,
        'super-settings': true,
        'dinas-dashboard': false,
        'dinas-coops-daftar': false,
        'dinas-coops-verif': false,
        'dinas-products': false,
        'dinas-orders': false,
        'dinas-reports': false,
        'dinas-settings': false,
        'coop-dashboard': false,
        'coop-profile': false,
        'coop-categories': false,
        'coop-products-daftar': false,
        'coop-products-add': false,
        'coop-orders': false,
        'coop-shipping': false,
        'coop-customers': false,
        'coop-reports': false,
        'coop-settings': false,
    },
    dinasadmin: {
        'super-dashboard': false,
        'super-coops-daftar': false,
        'super-coops-verif': false,
        'super-coops-wilayah': false,
        'super-products': false,
        'super-orders': false,
        'super-reports': false,
        'super-audit': false,
        'super-users': false,
        'super-permissions': false,
        'super-settings': false,
        'dinas-dashboard': true,
        'dinas-coops-daftar': true,
        'dinas-coops-verif': true,
        'dinas-products': true,
        'dinas-orders': true,
        'dinas-reports': true,
        'dinas-settings': true,
        'coop-dashboard': false,
        'coop-profile': false,
        'coop-categories': false,
        'coop-products-daftar': false,
        'coop-products-add': false,
        'coop-orders': false,
        'coop-shipping': false,
        'coop-customers': false,
        'coop-reports': false,
        'coop-settings': false,
    },
    coopadmin: {
        'super-dashboard': false,
        'super-coops-daftar': false,
        'super-coops-verif': false,
        'super-coops-wilayah': false,
        'super-products': false,
        'super-orders': false,
        'super-reports': false,
        'super-audit': false,
        'super-users': false,
        'super-permissions': false,
        'super-settings': false,
        'dinas-dashboard': false,
        'dinas-coops-daftar': false,
        'dinas-coops-verif': false,
        'dinas-products': false,
        'dinas-orders': false,
        'dinas-reports': false,
        'dinas-settings': false,
        'coop-dashboard': true,
        'coop-profile': true,
        'coop-categories': true,
        'coop-products-daftar': true,
        'coop-products-add': true,
        'coop-orders': true,
        'coop-shipping': true,
        'coop-customers': true,
        'coop-reports': true,
        'coop-settings': true,
    },
    customer: {
        'super-dashboard': false,
        'super-coops-daftar': false,
        'super-coops-verif': false,
        'super-coops-wilayah': false,
        'super-products': false,
        'super-orders': false,
        'super-reports': false,
        'super-audit': false,
        'super-users': false,
        'super-permissions': false,
        'super-settings': false,
        'dinas-dashboard': false,
        'dinas-coops-daftar': false,
        'dinas-coops-verif': false,
        'dinas-products': false,
        'dinas-orders': false,
        'dinas-reports': false,
        'dinas-settings': false,
        'coop-dashboard': false,
        'coop-profile': false,
        'coop-categories': false,
        'coop-products-daftar': false,
        'coop-products-add': false,
        'coop-orders': false,
        'coop-shipping': false,
        'coop-customers': false,
        'coop-reports': false,
        'coop-settings': false,
    }
};

const menuMetadata = {
    // Super Admin Menus
    'super-dashboard': { name: 'Dashboard Nasional', group: 'Portal Nasional (Super Admin)' },
    'super-coops-daftar': { name: 'Daftar Koperasi Unit', group: 'Portal Nasional (Super Admin)' },
    'super-coops-verif': { name: 'Persetujuan Pendaftaran', group: 'Portal Nasional (Super Admin)' },
    'super-coops-wilayah': { name: 'Wilayah & Regional', group: 'Portal Nasional (Super Admin)' },
    'super-products': { name: 'Monitoring Produk', group: 'Portal Nasional (Super Admin)' },
    'super-orders': { name: 'Monitoring Transaksi', group: 'Portal Nasional (Super Admin)' },
    'super-reports': { name: 'Laporan Penjualan', group: 'Portal Nasional (Super Admin)' },
    'super-audit': { name: 'Sistem Audit Log', group: 'Portal Nasional (Super Admin)' },
    'super-users': { name: 'Manajemen User & Kredensial', group: 'Portal Nasional (Super Admin)' },
    'super-permissions': { name: 'Manajemen Hak Akses & Menu', group: 'Portal Nasional (Super Admin)' },
    'super-settings': { name: 'Pengaturan Sistem Global', group: 'Portal Nasional (Super Admin)' },

    // Dinas Admin Menus
    'dinas-dashboard': { name: 'Dashboard Pengawasan', group: 'Portal Dinas Koperasi (Admin)' },
    'dinas-coops-daftar': { name: 'Daftar Koperasi Binaan', group: 'Portal Dinas Koperasi (Admin)' },
    'dinas-coops-verif': { name: 'Legalitas & Approval', group: 'Portal Dinas Koperasi (Admin)' },
    'dinas-products': { name: 'Katalog Produk Gabungan', group: 'Portal Dinas Koperasi (Admin)' },
    'dinas-orders': { name: 'Laporan Transaksi Wilayah', group: 'Portal Dinas Koperasi (Admin)' },
    'dinas-reports': { name: 'Rekapitulasi SHU Regional', group: 'Portal Dinas Koperasi (Admin)' },
    'dinas-settings': { name: 'Konfigurasi Dinas Regional', group: 'Portal Dinas Koperasi (Admin)' },

    // Coop Admin Menus
    'coop-dashboard': { name: 'Dashboard Koperasi Unit', group: 'Portal Koperasi (User)' },
    'coop-profile': { name: 'Profil & Legalitas Koperasi', group: 'Portal Koperasi (User)' },
    'coop-categories': { name: 'Kategori Produk Toko', group: 'Portal Koperasi (User)' },
    'coop-products-daftar': { name: 'Daftar & Stok Produk', group: 'Portal Koperasi (User)' },
    'coop-products-add': { name: 'Tambah / Publikasi Produk', group: 'Portal Koperasi (User)' },
    'coop-orders': { name: 'Transaksi Penjualan Toko', group: 'Portal Koperasi (User)' },
    'coop-shipping': { name: 'Konfigurasi Kurir & Kiriman', group: 'Portal Koperasi (User)' },
    'coop-customers': { name: 'Daftar Pelanggan / Anggota', group: 'Portal Koperasi (User)' },
    'coop-reports': { name: 'Laporan SHU Anggota', group: 'Portal Koperasi (User)' },
    'coop-settings': { name: 'Pengaturan Toko Koperasi', group: 'Portal Koperasi (User)' },
};

function initPermissions() {
    const saved = localStorage.getItem('role_permissions');
    if (saved) {
        try {
            state.rolePermissions = JSON.parse(saved);
        } catch (e) {
            state.rolePermissions = JSON.parse(JSON.stringify(DEFAULT_PERMISSIONS));
        }
    } else {
        state.rolePermissions = JSON.parse(JSON.stringify(DEFAULT_PERMISSIONS));
    }
}

function applyRolePermissions() {
    const roles = ['superadmin', 'dinasadmin', 'coopadmin', 'customer'];
    
    roles.forEach(role => {
        const navContainer = document.getElementById(`menu-${role}`);
        if (!navContainer) return;

        Object.keys(menuMetadata).forEach(menuKey => {
            const menuEl = navContainer.querySelector(`.menu-item[data-tab="${menuKey}"]`);
            if (menuEl) {
                const isEnabled = state.rolePermissions[role]?.[menuKey] === true;
                if (isEnabled) {
                    menuEl.classList.remove('hidden');
                    menuEl.style.display = 'flex';
                } else {
                    menuEl.classList.add('hidden');
                    menuEl.style.display = 'none';
                }
            }
        });
    });

    // Check if current active tab is disabled
    const currentRole = state.activeRole;
    const currentTab = state.activeTab;
    const isCurrentTabEnabled = state.rolePermissions[currentRole]?.[currentTab] === true;

    if (!isCurrentTabEnabled) {
        const defaultTabs = {
            superadmin: 'super-dashboard',
            dinasadmin: 'dinas-dashboard',
            coopadmin: 'coop-dashboard',
            customer: 'home'
        };
        
        let newTab = defaultTabs[currentRole];
        if (state.rolePermissions[currentRole]?.[newTab] !== true) {
            newTab = Object.keys(menuMetadata).find(key => 
                key.startsWith(currentRole === 'superadmin' ? 'super-' : (currentRole === 'dinasadmin' ? 'dinas-' : 'coop-')) &&
                state.rolePermissions[currentRole]?.[key] === true
            );
        }
        
        if (newTab) {
            state.activeTab = newTab;
            document.querySelectorAll('.menu-item').forEach(el => el.classList.remove('active'));
            const targetTabBtn = document.querySelector(`#menu-${currentRole} .menu-item[data-tab="${newTab}"]`);
            if (targetTabBtn) targetTabBtn.classList.add('active');
            renderWorkspace();
        }
    }
}

function renderSuperPermissionsTable() {
    const tbody = document.getElementById('permissions-matrix-body');
    if (!tbody) return;
    tbody.innerHTML = '';

    const groups = {};
    Object.keys(menuMetadata).forEach(key => {
        const item = menuMetadata[key];
        if (!groups[item.group]) {
            groups[item.group] = [];
        }
        groups[item.group].push({ key, ...item });
    });

    Object.keys(groups).forEach(groupName => {
        tbody.innerHTML += `
            <tr class="bg-slate-800/30 font-bold">
                <td colspan="5" class="py-2.5 px-4 text-xs text-primary font-heading uppercase tracking-wider">${groupName}</td>
            </tr>
        `;

        groups[groupName].forEach(menu => {
            const superChecked = state.rolePermissions.superadmin[menu.key] ? 'checked' : '';
            const dinasChecked = state.rolePermissions.dinasadmin[menu.key] ? 'checked' : '';
            const coopChecked = state.rolePermissions.coopadmin[menu.key] ? 'checked' : '';
            const custChecked = state.rolePermissions.customer[menu.key] ? 'checked' : '';
            const isSelfLockoutSafety = menu.key === 'super-permissions';

            tbody.innerHTML += `
                <tr class="hover:bg-slate-800/10 border-b border-slate-800/40">
                    <td class="py-3 px-4 font-semibold text-slate-200">${menu.name}</td>
                    <td class="py-3 px-4 text-center">
                        <input type="checkbox" ${superChecked} ${isSelfLockoutSafety ? 'disabled' : ''} 
                            class="w-4 h-4 rounded border-slate-700 bg-slate-900 text-primary focus:ring-primary/45 transition cursor-pointer" 
                            onclick="togglePermission('superadmin', '${menu.key}', this.checked)">
                    </td>
                    <td class="py-3 px-4 text-center">
                        <input type="checkbox" ${dinasChecked} 
                            class="w-4 h-4 rounded border-slate-700 bg-slate-900 text-primary focus:ring-primary/45 transition cursor-pointer" 
                            onclick="togglePermission('dinasadmin', '${menu.key}', this.checked)">
                    </td>
                    <td class="py-3 px-4 text-center">
                        <input type="checkbox" ${coopChecked} 
                            class="w-4 h-4 rounded border-slate-700 bg-slate-900 text-primary focus:ring-primary/45 transition cursor-pointer" 
                            onclick="togglePermission('coopadmin', '${menu.key}', this.checked)">
                    </td>
                    <td class="py-3 px-4 text-center">
                        <input type="checkbox" ${custChecked} 
                            class="w-4 h-4 rounded border-slate-700 bg-slate-900 text-primary focus:ring-primary/45 transition cursor-pointer" 
                            onclick="togglePermission('customer', '${menu.key}', this.checked)">
                    </td>
                </tr>
            `;
        });
    });
}

function togglePermission(role, menuKey, checked) {
    if (!state.rolePermissions[role]) {
        state.rolePermissions[role] = {};
    }
    state.rolePermissions[role][menuKey] = checked;
    localStorage.setItem('role_permissions', JSON.stringify(state.rolePermissions));
    applyRolePermissions();
    logConsole(`Mengubah hak akses menu: ${menuMetadata[menuKey].name} untuk ${role.toUpperCase()} menjadi ${checked ? 'AKTIF' : 'NON-AKTIF'}`);
}

function resetPermissionsToDefault() {
    state.rolePermissions = JSON.parse(JSON.stringify(DEFAULT_PERMISSIONS));
    localStorage.setItem('role_permissions', JSON.stringify(state.rolePermissions));
    applyRolePermissions();
    renderSuperPermissionsTable();
    logConsole('Setelan hak akses dan visibilitas menu di-reset ke default pabrik.');
}

// ====================================================
// DESKTOP MARKETPLACE PORTAL RENDERERS & ACTIONS
// ====================================================

// Toast Notifications for Marketplace
function showMarketToast(message, type = 'success') {
    let container = document.getElementById('market-toast-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'market-toast-container';
        container.className = 'fixed top-6 right-6 z-[100] flex flex-col gap-3 max-w-sm w-full pointer-events-none';
        document.body.appendChild(container);
    }
    
    const toast = document.createElement('div');
    toast.className = 'pointer-events-auto bg-brandSurface/95 backdrop-blur-md border border-slate-700/80 p-4 rounded-2xl shadow-2xl flex items-center gap-3 transition-all duration-300 transform translate-x-12 opacity-0';
    
    const icon = type === 'success' ? 'check_circle' : 'info';
    const iconColor = type === 'success' ? 'text-emerald-400' : 'text-primary';
    
    toast.innerHTML = `
        <span class="material-symbols-outlined ${iconColor} text-lg shrink-0">${icon}</span>
        <div class="flex-1 text-xs font-semibold text-slate-100">${message}</div>
        <button class="text-slate-500 hover:text-white transition shrink-0" onclick="this.parentElement.remove()">
            <span class="material-symbols-outlined text-sm">close</span>
        </button>
    `;
    
    container.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.remove('translate-x-12', 'opacity-0');
        toast.classList.add('translate-x-0', 'opacity-100');
    }, 10);
    
    setTimeout(() => {
        toast.classList.remove('translate-x-0', 'opacity-100');
        toast.classList.add('translate-x-12', 'opacity-0');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, 3000);
}

// Add Product to Cart
function addProductToMarketCart(id) {
    const p = state.products.find(x => x.id == id);
    if (!p) return;
    
    const exist = state.marketCart.find(item => item.product_id == id);
    
    if (exist) {
        if (exist.qty >= p.stok) {
            showMarketToast(`Stok tidak mencukupi untuk menambah kuantitas "${p.nama_produk}".`, 'error');
            return;
        }
        exist.qty++;
    } else {
        state.marketCart.push({
            product_id: p.id,
            nama_produk: p.nama_produk,
            harga: p.harga,
            foto: p.foto,
            koperasi_id: p.koperasi_id,
            stok: p.stok,
            qty: 1
        });
    }

    logConsole(`Customer menambahkan barang "${p.nama_produk}" ke keranjang belanja desktop.`);
    showMarketToast(`"${p.nama_produk}" berhasil dimasukkan ke keranjang!`);
    
    const badge = document.getElementById('market-cart-badge');
    if (badge) {
        badge.innerText = state.marketCart.length;
    }
    
    if (state.marketView === 'cart') {
        renderMarketplace();
    }
}

// Update Cart Quantity
function updateMarketCartQty(id, newQty) {
    const item = state.marketCart.find(x => x.product_id == id);
    if (!item) return;
    
    const qty = parseInt(newQty);
    if (isNaN(qty) || qty < 1) {
        item.qty = 1;
    } else if (qty > item.stok) {
        item.qty = item.stok;
        showMarketToast(`Stok maksimal adalah ${item.stok} pcs.`, 'error');
    } else {
        item.qty = qty;
    }
    
    renderMarketplace();
}

// Remove item from Cart
function removeFromMarketCart(id) {
    const item = state.marketCart.find(x => x.product_id == id);
    if (!item) return;
    
    state.marketCart = state.marketCart.filter(x => x.product_id != id);
    logConsole(`Customer menghapus barang "${item.nama_produk}" dari keranjang belanja desktop.`);
    showMarketToast(`"${item.nama_produk}" dihapus dari keranjang.`, 'info');
    
    const badge = document.getElementById('market-cart-badge');
    if (badge) {
        badge.innerText = state.marketCart.length;
    }
    
    renderMarketplace();
}

// Checkout single product (Buy Now)
function buyNowMarketProduct(productId) {
    const p = state.products.find(x => x.id == productId);
    if (!p) return;
    
    state.checkoutCoopId = p.koperasi_id;
    state.checkoutItems = [{
        product_id: p.id,
        nama_produk: p.nama_produk,
        harga: p.harga,
        foto: p.foto,
        koperasi_id: p.koperasi_id,
        stok: p.stok,
        qty: 1
    }];
    
    goToMarketView('checkout');
}

// Checkout cooperative group items from Cart
function checkoutCartCoop(coopId) {
    const user = state.customerSession;
    if (!user) {
        openWebLoginModal();
        return;
    }
    
    const items = state.marketCart.filter(item => item.koperasi_id == coopId);
    if (items.length === 0) return;
    
    state.checkoutCoopId = coopId;
    state.checkoutItems = items;
    
    goToMarketView('checkout');
}

function goToMarketView(view) {
    if (typeof stopWebcamStream === 'function') {
        stopWebcamStream();
    }
    state.marketView = view;
    renderMarketplace();
}

function visitMarketCoopStore(coopId) {
    const coop = state.cooperatives.find(c => c.id == coopId);
    if (coop) {
        state.selectedMarketCoop = coop;
        state.marketView = 'coop-store';
        renderMarketplace();
    }
}

function visitMarketProductDetail(prodId) {
    const prod = state.products.find(p => p.id == prodId);
    if (prod) {
        state.selectedMarketProduct = prod;
        state.marketView = 'product-detail';
        renderMarketplace();
    }
}

function handleMarketSearch(e) {
    state.marketSearchQuery = e.target.value;
    if (state.marketView !== 'home' && state.marketView !== 'coop-store') {
        state.marketView = 'home';
    }
    renderMarketplace();
}

window.setMarketCategoryFilter = function(catId) {
    if (state.marketCategoryFilter === catId) {
        state.marketCategoryFilter = ''; // toggle off
    } else {
        state.marketCategoryFilter = catId;
    }
    if (state.marketView !== 'home' && state.marketView !== 'coop-store') {
        state.marketView = 'home';
    }
    renderMarketplace();
};

function openWebLoginModal() {
    const modal = document.getElementById('web-login-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
    }
}

function closeWebLoginModal() {
    const modal = document.getElementById('web-login-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
    const errAlert = document.getElementById('web-login-error');
    if (errAlert) errAlert.classList.add('hidden');
}

function renderMarketplace() {
    const container = document.getElementById('market-content-area');
    if (!container) return;

    const badge = document.getElementById('market-cart-badge');
    if (badge) {
        badge.innerText = state.marketCart.length;
    }

    if (state.customerSession) {
        checkCustomerUnreadBadge();
    }

    switch (state.marketView) {
        case 'home':
            renderMarketHome(container);
            break;
        case 'coop-store':
            renderMarketCoopStore(container);
            break;
        case 'product-detail':
            renderMarketProductDetail(container);
            break;
        case 'cart':
            renderMarketCart(container);
            break;
        case 'checkout':
            renderMarketCheckout(container);
            break;
        case 'orders':
            renderMarketOrders(container);
            break;
        case 'messages':
            renderMarketMessages(container);
            break;
        case 'profile':
            renderMarketProfile(container);
            break;
        default:
            renderMarketHome(container);
            break;
    }
}

function renderMarketHome(container) {
    const activeCoops = state.cooperatives.filter(c => c.status === 'aktif');
    const activeProducts = state.products.filter(p => p.status === 'aktif');
    
    let displayProducts = activeProducts;
    if (state.marketSearchQuery) {
        const query = state.marketSearchQuery.toLowerCase();
        displayProducts = displayProducts.filter(p => 
            p.nama_produk.toLowerCase().includes(query) || 
            (p.tags && p.tags.toLowerCase().includes(query))
        );
    }
    
    if (state.marketCategoryFilter) {
        displayProducts = displayProducts.filter(p => p.kategori_id == state.marketCategoryFilter);
    }

    container.innerHTML = `
        <!-- Banner Hero -->
        <div class="relative bg-gradient-to-r from-slate-900 via-rose-950/40 to-slate-900 border border-slate-800 rounded-3xl p-8 overflow-hidden shadow-2xl flex items-center min-h-[220px]">
            <div class="absolute inset-0 bg-[radial-gradient(circle_at_70%_120%,rgba(220,38,38,0.15),transparent_60%)]"></div>
            <div class="relative max-w-lg flex flex-col gap-2.5">
                <span class="text-xs bg-rose-950/40 text-primary border border-rose-800/30 px-3 py-1 rounded-full font-bold uppercase tracking-wider self-start">E-Commerce Koperasi</span>
                <h2 class="font-heading text-2xl md:text-3xl font-black text-white leading-tight">Koperasi Digital Merah Putih</h2>
                <p class="text-slate-400 text-xs md:text-sm">Platform E-Commerce kolaboratif Dinas Koperasi Provinsi Gorontalo. Belanja produk UMKM binaan sekaligus dukung pertumbuhan ekonomi lokal.</p>
            </div>
        </div>

        <!-- Section: Koperasi Terdaftar -->
        <div class="flex flex-col gap-4">
            <div class="flex justify-between items-center">
                <h3 class="font-heading text-base font-bold text-white flex items-center gap-2">
                    <span class="material-symbols-outlined text-primary">storefront</span>
                    <span>Koperasi Terdaftar</span>
                </h3>
            </div>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                ${activeCoops.map(c => `
                    <div onclick="visitMarketCoopStore(${c.id})" class="bg-slate-800/20 hover:bg-slate-800/40 border border-slate-700/30 hover:border-primary/40 rounded-2xl p-5 flex flex-col items-center text-center gap-3 cursor-pointer transition duration-200 shadow-md">
                        <img src="${c.logo}" class="w-12 h-12 rounded-xl object-cover shadow-md border border-slate-700/50">
                        <div>
                            <h4 class="font-heading font-bold text-white text-xs leading-snug line-clamp-2 h-8 flex items-center justify-center gap-1.5">
                                <span>${c.nama_koperasi}</span>
                                <span class="w-1.5 h-1.5 rounded-full bg-emerald-500 inline-block shrink-0" title="Seller Aktif"></span>
                            </h4>
                            <p class="text-[10px] text-slate-500 mt-1">📍 ${c.kabupaten}</p>
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>

        <!-- Section: Katalog Produk -->
        <div class="flex flex-col gap-4">
            <div class="flex flex-col md:flex-row justify-between md:items-center gap-4">
                <h3 class="font-heading text-base font-bold text-white flex items-center gap-2">
                    <span class="material-symbols-outlined text-primary">shopping_bag</span>
                    <span>${state.marketSearchQuery ? `Hasil Pencarian: "${state.marketSearchQuery}"` : 'Katalog Produk Unggulan'}</span>
                </h3>
                
                <!-- Category Filter Buttons -->
                <div class="flex gap-2 overflow-x-auto no-scrollbar pb-1">
                    <button onclick="setMarketCategoryFilter('')" class="shrink-0 px-4 py-1.5 rounded-full text-xs font-bold border transition ${state.marketCategoryFilter === '' ? 'bg-primary border-primary text-white' : 'bg-slate-800/50 border-slate-700 text-slate-400 hover:text-white hover:border-slate-500'}">Semua</button>
                    <button onclick="setMarketCategoryFilter('1')" class="shrink-0 px-4 py-1.5 rounded-full text-xs font-bold border transition ${state.marketCategoryFilter === '1' ? 'bg-primary border-primary text-white' : 'bg-slate-800/50 border-slate-700 text-slate-400 hover:text-white hover:border-slate-500'}">Bahan Pokok</button>
                    <button onclick="setMarketCategoryFilter('4')" class="shrink-0 px-4 py-1.5 rounded-full text-xs font-bold border transition ${state.marketCategoryFilter === '4' ? 'bg-primary border-primary text-white' : 'bg-slate-800/50 border-slate-700 text-slate-400 hover:text-white hover:border-slate-500'}">Hasil Pertanian</button>
                    <button onclick="setMarketCategoryFilter('3')" class="shrink-0 px-4 py-1.5 rounded-full text-xs font-bold border transition ${state.marketCategoryFilter === '3' ? 'bg-primary border-primary text-white' : 'bg-slate-800/50 border-slate-700 text-slate-400 hover:text-white hover:border-slate-500'}">UMKM</button>
                    <button onclick="setMarketCategoryFilter('5')" class="shrink-0 px-4 py-1.5 rounded-full text-xs font-bold border transition ${state.marketCategoryFilter === '5' ? 'bg-primary border-primary text-white' : 'bg-slate-800/50 border-slate-700 text-slate-400 hover:text-white hover:border-slate-500'}">Obat-obatan</button>
                </div>
            </div>
            
            ${displayProducts.length === 0 ? `
                <div class="text-center py-12 bg-slate-800/10 border border-slate-800 rounded-2xl">
                    <span class="material-symbols-outlined text-slate-600 text-4xl mb-2">search_off</span>
                    <p class="text-slate-500 text-xs font-semibold">Tidak ada produk yang cocok dengan pencarian Anda.</p>
                </div>
            ` : `
                <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                    ${displayProducts.map(p => {
                        const coop = state.cooperatives.find(c => c.id == p.koperasi_id);
                        return `
                            <div onclick="visitMarketProductDetail(${p.id})" class="group bg-slate-800/20 hover:bg-slate-800/40 border border-slate-700/30 hover:border-primary/30 rounded-2xl overflow-hidden flex flex-col cursor-pointer transition duration-200 shadow-md">
                                <div class="relative w-full aspect-square bg-slate-900">
                                    <img src="${p.foto}" class="w-full h-full object-cover">
                                    <span class="absolute top-2 left-2 text-[8px] bg-slate-900/80 text-slate-300 px-2 py-0.5 rounded-full font-bold uppercase border border-slate-700/50">${p.tags.split(',')[0]}</span>
                                    <button onclick="event.stopPropagation(); addProductToMarketCart(${p.id})" class="absolute bottom-2 right-2 bg-brandDark/85 hover:bg-primary text-slate-200 hover:text-white border border-slate-700 hover:border-primary w-7.5 h-7.5 rounded-lg flex items-center justify-center transition shadow-lg" title="Masukkan Keranjang">
                                        <span class="material-symbols-outlined text-base">add_shopping_cart</span>
                                    </button>
                                </div>
                                <div class="p-3.5 flex flex-col flex-1 gap-2">
                                    <h4 class="font-bold text-xs text-white line-clamp-2 leading-snug h-8">${p.nama_produk}</h4>
                                    <p class="text-[10px] text-slate-500 line-clamp-1 flex items-center gap-1">
                                        <span>Oleh: ${coop ? coop.nama_koperasi : 'Koperasi'}</span>
                                        ${coop && coop.status === 'aktif' ? `<span class="w-1.5 h-1.5 rounded-full bg-emerald-500 inline-block shrink-0" title="Seller Aktif"></span>` : ''}
                                    </p>
                                    <div class="mt-auto pt-2 flex flex-col gap-1">
                                        <div class="flex justify-between items-center">
                                            <span class="text-xs font-black text-white">Rp ${Number(p.harga).toLocaleString('id-ID')}</span>
                                            <span class="text-[10px] text-amber-400 font-bold flex items-center gap-0.5">
                                                <span class="material-symbols-outlined text-[10px]">star</span>
                                                <span>${p.rating}</span>
                                            </span>
                                        </div>
                                        <p class="text-[9px] text-slate-400">${p.stok} Tersedia</p>
                                    </div>
                                </div>
                            </div>
                        `;
                    }).join('')}
                </div>
            `}
        </div>
    `;
}

function renderMarketCoopStore(container) {
    const c = state.selectedMarketCoop;
    if (!c) return;

    let storeProducts = state.products.filter(p => p.koperasi_id == c.id && p.status === 'aktif');
    
    if (state.marketSearchQuery) {
        const query = state.marketSearchQuery.toLowerCase();
        storeProducts = storeProducts.filter(p => 
            p.nama_produk.toLowerCase().includes(query) || 
            (p.tags && p.tags.toLowerCase().includes(query))
        );
    }

    if (state.marketCategoryFilter) {
        storeProducts = storeProducts.filter(p => p.kategori_id == state.marketCategoryFilter);
    }

    container.innerHTML = `
        <div class="relative bg-gradient-to-r from-slate-900 to-slate-955 border border-slate-800 rounded-3xl p-6 shadow-xl flex flex-col md:flex-row items-center gap-6">
            <button onclick="goToMarketView('home')" class="absolute top-4 left-4 p-2 bg-slate-800 hover:bg-slate-700 border border-slate-700 text-white rounded-full transition flex items-center justify-center z-10">
                <span class="material-symbols-outlined text-sm">arrow_back</span>
            </button>
            
            <img src="${c.logo}" class="w-20 h-20 rounded-2xl object-cover border border-slate-700 shadow-lg mt-8 md:mt-0">
            
            <div class="flex-1 text-center md:text-left flex flex-col gap-2">
                <h2 class="font-heading text-xl font-extrabold text-white tracking-tight flex items-center justify-center md:justify-start gap-2">
                    <span>${c.nama_koperasi}</span>
                    ${c.status === 'aktif' ? `<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 inline-block animate-pulse shrink-0" title="Seller Aktif"></span>` : ''}
                </h2>
                <p class="text-slate-400 text-xs">📍 ${c.alamat} (${c.kabupaten}, ${c.provinsi})</p>
                <div class="flex gap-2 justify-center md:justify-start items-center">
                    <span class="text-[10px] bg-emerald-950/40 text-emerald-400 border border-emerald-800/30 px-2 py-0.5 rounded-full font-bold">Koperasi Terdaftar</span>
                    <span class="text-[10px] text-amber-400 font-bold flex items-center gap-0.5">
                        <span class="material-symbols-outlined text-[12px]">star</span>
                        <span>4.9 (Rating Koperasi)</span>
                    </span>
                </div>
            </div>
        </div>

        <div class="flex flex-col gap-4">
            <div class="flex flex-col md:flex-row justify-between md:items-center gap-4">
                <h3 class="font-heading text-base font-bold text-white flex items-center gap-2">
                    <span class="material-symbols-outlined text-primary">shopping_bag</span>
                    <span>${state.marketSearchQuery ? `Hasil Pencarian: "${state.marketSearchQuery}"` : 'Produk Koperasi'}</span>
                </h3>
                
                <!-- Category Filter Buttons -->
                <div class="flex gap-2 overflow-x-auto no-scrollbar pb-1">
                    <button onclick="setMarketCategoryFilter('')" class="shrink-0 px-4 py-1.5 rounded-full text-xs font-bold border transition ${state.marketCategoryFilter === '' ? 'bg-primary border-primary text-white' : 'bg-slate-800/50 border-slate-700 text-slate-400 hover:text-white hover:border-slate-500'}">Semua</button>
                    <button onclick="setMarketCategoryFilter('1')" class="shrink-0 px-4 py-1.5 rounded-full text-xs font-bold border transition ${state.marketCategoryFilter === '1' ? 'bg-primary border-primary text-white' : 'bg-slate-800/50 border-slate-700 text-slate-400 hover:text-white hover:border-slate-500'}">Bahan Pokok</button>
                    <button onclick="setMarketCategoryFilter('4')" class="shrink-0 px-4 py-1.5 rounded-full text-xs font-bold border transition ${state.marketCategoryFilter === '4' ? 'bg-primary border-primary text-white' : 'bg-slate-800/50 border-slate-700 text-slate-400 hover:text-white hover:border-slate-500'}">Hasil Pertanian</button>
                    <button onclick="setMarketCategoryFilter('3')" class="shrink-0 px-4 py-1.5 rounded-full text-xs font-bold border transition ${state.marketCategoryFilter === '3' ? 'bg-primary border-primary text-white' : 'bg-slate-800/50 border-slate-700 text-slate-400 hover:text-white hover:border-slate-500'}">UMKM</button>
                    <button onclick="setMarketCategoryFilter('5')" class="shrink-0 px-4 py-1.5 rounded-full text-xs font-bold border transition ${state.marketCategoryFilter === '5' ? 'bg-primary border-primary text-white' : 'bg-slate-800/50 border-slate-700 text-slate-400 hover:text-white hover:border-slate-500'}">Obat-obatan</button>
                </div>
            </div>

            ${storeProducts.length === 0 ? `
                <div class="text-center py-12 bg-slate-800/10 border border-slate-800 rounded-2xl">
                    <p class="text-slate-500 text-xs font-semibold">Koperasi ini belum memiliki produk yang terdaftar.</p>
                </div>
            ` : `
                <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                    ${storeProducts.map(p => `
                        <div onclick="visitMarketProductDetail(${p.id})" class="bg-slate-800/20 hover:bg-slate-800/40 border border-slate-700/30 hover:border-primary/30 rounded-2xl overflow-hidden flex flex-col cursor-pointer transition duration-200 shadow-md">
                            <div class="relative w-full aspect-square bg-slate-900">
                                <img src="${p.foto}" class="w-full h-full object-cover">
                                <button onclick="event.stopPropagation(); addProductToMarketCart(${p.id})" class="absolute bottom-2 right-2 bg-brandDark/85 hover:bg-primary text-slate-200 hover:text-white border border-slate-700 hover:border-primary w-7.5 h-7.5 rounded-lg flex items-center justify-center transition shadow-lg" title="Masukkan Keranjang">
                                    <span class="material-symbols-outlined text-base">add_shopping_cart</span>
                                </button>
                            </div>
                            <div class="p-3.5 flex flex-col flex-1 gap-2">
                                <h4 class="font-bold text-xs text-white line-clamp-2 leading-snug h-8">${p.nama_produk}</h4>
                                <div class="mt-auto pt-2 flex flex-col gap-1">
                                    <div class="flex justify-between items-center">
                                        <span class="text-xs font-black text-white">Rp ${Number(p.harga).toLocaleString('id-ID')}</span>
                                        <span class="text-[10px] text-amber-400 font-bold flex items-center gap-0.5">
                                            <span class="material-symbols-outlined text-[10px]">star</span>
                                            <span>${p.rating}</span>
                                        </span>
                                    </div>
                                    <p class="text-[9px] text-slate-400">${p.stok} Tersedia</p>
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            `}
        </div>
    `;
}

function renderMarketProductDetail(container) {
    const p = state.selectedMarketProduct;
    if (!p) return;

    const coop = state.cooperatives.find(c => c.id == p.koperasi_id);
    const isLoggedIn = state.customerSession !== null;

    container.innerHTML = `
        <div class="relative flex flex-col lg:flex-row gap-8 bg-slate-800/20 border border-slate-700/30 rounded-3xl p-6 lg:p-8 shadow-xl">
            <button onclick="goToMarketView('home')" class="absolute top-4 left-4 p-2 bg-slate-800 hover:bg-slate-700 border border-slate-700 text-white rounded-full transition flex items-center justify-center z-10">
                <span class="material-symbols-outlined text-sm">arrow_back</span>
            </button>

            <div class="w-full lg:w-1/2 aspect-square lg:h-[400px] bg-slate-900 rounded-2xl overflow-hidden border border-slate-700 flex items-center justify-center shrink-0">
                <img src="${p.foto}" class="w-full h-full object-cover">
            </div>

            <div class="flex-1 flex flex-col gap-5 justify-between">
                <div class="flex flex-col gap-3">
                    <span class="text-[10px] bg-primary/20 text-primary border border-primary/30 px-3 py-1 rounded-full font-bold uppercase tracking-wider self-start">${p.tags.split(',')[0]}</span>
                    <h2 class="font-heading text-xl lg:text-2xl font-black text-white tracking-tight">${p.nama_produk}</h2>
                    
                    <div class="flex gap-4 items-center text-xs text-slate-400">
                        <span class="text-amber-400 font-bold flex items-center gap-0.5 cursor-pointer hover:text-amber-300 transition hover:scale-105" onclick="showProductReviews(${p.id})" title="Lihat ulasan pengguna">
                            <span class="material-symbols-outlined text-[14px]">star</span>
                            <span class="underline decoration-amber-400/30 underline-offset-2">${p.rating} / 5.0 (Rating)</span>
                        </span>
                        <div class="h-3 w-[1px] bg-slate-800"></div>
                        <span>Tersedia: <strong class="text-white">${p.stok}</strong></span>
                    </div>

                    <div class="py-2.5 border-y border-slate-800 flex items-center gap-3 flex-wrap">
                        <span class="text-[10px] text-slate-500 font-semibold uppercase tracking-wider">Koperasi Penjual:</span>
                        <div class="flex items-center gap-2">
                            <span onclick="visitMarketCoopStore(${coop ? coop.id : p.koperasi_id})" class="text-xs text-primary hover:text-rose-400 font-bold cursor-pointer transition underline">${coop ? coop.nama_koperasi : 'Koperasi'}</span>
                            ${coop && coop.status === 'aktif' ? `<span class="w-2 h-2 rounded-full bg-emerald-500 inline-block animate-pulse shrink-0" title="Seller Aktif"></span>` : ''}
                            <button onclick="openProductChatModal(${coop ? coop.id : p.koperasi_id}, ${p.id})" class="ml-2 py-1 px-2.5 bg-slate-800 hover:bg-primary border border-slate-700/80 hover:border-primary text-slate-300 hover:text-white rounded-lg transition flex items-center gap-1 text-[10px] font-bold shadow" title="Tanya Penjual tentang produk ini">
                                <span class="material-symbols-outlined text-xs">chat</span>
                                <span>Tanya Seller</span>
                            </button>
                        </div>
                    </div>

                    <div class="bg-slate-900/60 p-4 rounded-2xl border border-slate-800/80 flex flex-col gap-1 mt-2">
                        <span class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Harga Belanja</span>
                        <span class="text-2xl font-black text-white">Rp ${Number(p.harga).toLocaleString('id-ID')}</span>
                    </div>

                    <div class="flex flex-col gap-2 mt-2">
                        <h4 class="text-xs font-bold text-white uppercase tracking-wider">Deskripsi</h4>
                        <p class="text-slate-400 text-xs leading-relaxed">${p.deskripsi}</p>
                    </div>
                </div>

                <div class="border-t border-slate-800 pt-4 flex flex-col gap-4 mt-6">
                    ${isLoggedIn ? `
                        <div class="flex flex-col gap-1.5">
                            <h4 class="text-xs font-bold text-white flex items-center gap-1">
                                <span class="material-symbols-outlined text-sm">local_shipping</span>
                                <span>Pilihan Pembelian</span>
                            </h4>
                            <p class="text-slate-400 text-[10px]">Anda login sebagai <strong class="text-white">${state.customerSession.nama}</strong>. Silakan tambahkan ke keranjang belanja atau langsung lakukan checkout.</p>
                        </div>
                        <div class="flex gap-4">
                            <button onclick="addProductToMarketCart(${p.id})" class="flex-1 bg-slate-800 hover:bg-slate-700 text-white border border-slate-700 font-bold text-xs uppercase tracking-wider px-4 py-3.5 rounded-xl transition flex items-center justify-center gap-1.5">
                                <span class="material-symbols-outlined text-base">add_shopping_cart</span>
                                <span>Masukkan Keranjang</span>
                            </button>
                            <button onclick="buyNowMarketProduct(${p.id})" class="flex-1 bg-gradient-to-r from-primary to-secondary hover:from-primary/95 hover:to-secondary/95 text-white font-bold text-xs uppercase tracking-wider px-4 py-3.5 rounded-xl shadow-lg transition flex items-center justify-center gap-1.5">
                                <span class="material-symbols-outlined text-base">shopping_cart_checkout</span>
                                <span>Beli Sekarang</span>
                            </button>
                        </div>
                    ` : `
                        <div class="flex flex-col gap-1.5">
                            <h4 class="text-xs font-bold text-slate-400 flex items-center gap-1">
                                <span class="material-symbols-outlined text-sm">info</span>
                                <span>Pilihan Pembelian</span>
                            </h4>
                            <p class="text-slate-500 text-[10px]">Anda dapat menambahkan produk ke keranjang belanja, tetapi wajib masuk/login ke sistem terlebih dahulu untuk melakukan transaksi checkout.</p>
                        </div>
                        <div class="flex gap-4">
                            <button onclick="addProductToMarketCart(${p.id})" class="flex-1 bg-slate-800 hover:bg-slate-700 text-white border border-slate-700 font-bold text-xs uppercase tracking-wider px-4 py-3.5 rounded-xl transition flex items-center justify-center gap-1.5">
                                <span class="material-symbols-outlined text-base">add_shopping_cart</span>
                                <span>Masukkan Keranjang</span>
                            </button>
                            <button onclick="openWebLoginModal()" class="flex-1 bg-gradient-to-r from-primary to-secondary hover:from-primary/95 hover:to-secondary/95 text-white font-bold text-xs uppercase tracking-wider px-4 py-3.5 rounded-xl shadow-lg transition flex items-center justify-center gap-1.5">
                                <span class="material-symbols-outlined text-base">login</span>
                                <span>Beli Sekarang</span>
                            </button>
                        </div>
                    `}
                </div>
            </div>
        </div>
    `;
}

// Premium Desktop Cart view renderer
function renderMarketCart(container) {
    if (state.marketCart.length === 0) {
        container.innerHTML = `
            <div class="max-w-md mx-auto text-center py-16 px-4 bg-slate-800/10 border border-slate-800/80 rounded-3xl shadow-xl flex flex-col items-center gap-5">
                <div class="w-16 h-16 rounded-2xl bg-slate-900/60 flex items-center justify-center text-slate-600 border border-slate-800">
                    <span class="material-symbols-outlined text-3xl">shopping_cart</span>
                </div>
                <div>
                    <h3 class="font-heading text-lg font-bold text-white">Keranjang Belanja Kosong</h3>
                    <p class="text-slate-400 text-xs mt-1 max-w-xs mx-auto">Anda belum menambahkan produk apa pun ke keranjang belanja Anda.</p>
                </div>
                <button onclick="goToMarketView('home')" class="bg-gradient-to-r from-primary to-secondary hover:from-primary/95 hover:to-secondary/95 text-white font-bold text-xs uppercase tracking-wider px-5 py-3 rounded-xl shadow-lg transition flex items-center justify-center gap-1.5">
                    <span class="material-symbols-outlined text-sm font-bold">shopping_bag</span>
                    <span>Mulai Belanja</span>
                </button>
            </div>
        `;
        return;
    }

    // Group items by cooperative
    const cartGroups = {};
    state.marketCart.forEach(item => {
        if (!cartGroups[item.koperasi_id]) {
            cartGroups[item.koperasi_id] = [];
        }
        cartGroups[item.koperasi_id].push(item);
    });

    let groupsHtml = '';
    
    Object.keys(cartGroups).forEach(coopId => {
        const coop = state.cooperatives.find(c => c.id == coopId);
        const coopItems = cartGroups[coopId];
        const groupSubtotal = coopItems.reduce((sum, item) => sum + (item.harga * item.qty), 0);
        
        groupsHtml += `
            <!-- Cooperative Group Card -->
            <div class="bg-slate-800/20 border border-slate-700/30 rounded-3xl p-6 shadow-xl flex flex-col gap-5">
                <!-- Group Header -->
                <div class="flex items-center justify-between border-b border-slate-800/80 pb-4">
                    <div class="flex items-center gap-3 cursor-pointer" onclick="visitMarketCoopStore(${coopId})">
                        <img src="${coop ? coop.logo : 'https://images.unsplash.com/photo-1543269865-cbf427effbad?w=150'}" class="w-8 h-8 rounded-lg object-cover border border-slate-700/50 shadow-sm">
                        <div>
                            <h4 class="font-heading text-xs font-bold text-white hover:text-primary transition flex items-center gap-1">
                                <span>${coop ? coop.nama_koperasi : 'Koperasi'}</span>
                                <span class="material-symbols-outlined text-[12px] text-slate-500">arrow_forward</span>
                            </h4>
                            <p class="text-[9px] text-slate-500">📍 ${coop ? coop.kabupaten : 'Gorontalo'}</p>
                        </div>
                    </div>
                    <span class="text-[9px] bg-emerald-950/40 text-emerald-400 border border-emerald-800/30 px-2 py-0.5 rounded-full font-bold uppercase">Toko Terverifikasi</span>
                </div>
                
                <!-- Group Items List -->
                <div class="divide-y divide-slate-800/50">
                    ${coopItems.map(item => `
                        <div class="py-4 first:pt-0 last:pb-0 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                            <div class="flex items-center gap-4 cursor-pointer" onclick="visitMarketProductDetail(${item.product_id})">
                                <img src="${item.foto}" class="w-14 h-14 rounded-xl object-cover border border-slate-700/50 shadow-md shrink-0">
                                <div>
                                    <h5 class="text-xs font-bold text-white hover:text-primary transition line-clamp-1">${item.nama_produk}</h5>
                                    <p class="text-[10px] text-slate-400 font-black mt-1">Rp ${Number(item.harga).toLocaleString('id-ID')}</p>
                                    <p class="text-[9px] text-slate-500 mt-0.5">Stok tersedia: ${item.stok} pcs</p>
                                </div>
                            </div>
                            
                            <div class="flex items-center justify-between sm:justify-end gap-6 w-full sm:w-auto">
                                <!-- Quantity controls -->
                                <div class="flex items-center bg-slate-900 border border-slate-800 rounded-xl p-1 shrink-0">
                                    <button onclick="updateMarketCartQty(${item.product_id}, ${item.qty - 1})" class="w-7 h-7 flex items-center justify-center text-slate-400 hover:text-white rounded-lg hover:bg-slate-800 transition">
                                        <span class="material-symbols-outlined text-sm font-bold">remove</span>
                                    </button>
                                    <input type="number" value="${item.qty}" min="1" max="${item.stok}" 
                                        onchange="updateMarketCartQty(${item.product_id}, this.value)" 
                                        class="w-10 bg-transparent border-none text-center text-xs font-bold text-white focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none">
                                    <button onclick="updateMarketCartQty(${item.product_id}, ${item.qty + 1})" class="w-7 h-7 flex items-center justify-center text-slate-400 hover:text-white rounded-lg hover:bg-slate-800 transition">
                                        <span class="material-symbols-outlined text-sm font-bold">add</span>
                                    </button>
                                </div>
                                
                                <!-- Subtotal & Delete -->
                                <div class="text-right flex items-center gap-4 shrink-0">
                                    <div>
                                        <p class="text-[9px] text-slate-500">Subtotal</p>
                                        <p class="text-xs font-black text-white">Rp ${Number(item.harga * item.qty).toLocaleString('id-ID')}</p>
                                    </div>
                                    <button onclick="removeFromMarketCart(${item.product_id})" class="text-slate-500 hover:text-rose-400 p-2 rounded-xl hover:bg-rose-950/20 transition" title="Hapus Barang">
                                        <span class="material-symbols-outlined text-base">delete</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
                
                <!-- Group Footer & Checkout -->
                <div class="border-t border-slate-800/80 pt-4 mt-2 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                    <div>
                        <span class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Subtotal Koperasi</span>
                        <h4 class="text-base font-black text-white mt-0.5">Rp ${groupSubtotal.toLocaleString('id-ID')}</h4>
                    </div>
                    <button onclick="checkoutCartCoop(${coopId})" class="w-full sm:w-auto bg-gradient-to-r from-primary to-secondary hover:from-primary/95 hover:to-secondary/95 text-white font-bold text-xs uppercase tracking-wider px-6 py-3.5 rounded-xl shadow-lg transition flex items-center justify-center gap-1.5">
                        <span class="material-symbols-outlined text-base">shopping_cart_checkout</span>
                        <span>Checkout dari Koperasi Ini</span>
                    </button>
                </div>
            </div>
        `;
    });

    container.innerHTML = `
        <div class="flex flex-col gap-6 max-w-4xl mx-auto w-full">
            <div class="flex justify-between items-center border-b border-slate-800/60 pb-4">
                <h3 class="font-heading text-lg font-bold text-white flex items-center gap-2">
                    <span class="material-symbols-outlined text-primary">shopping_cart</span>
                    <span>Keranjang Belanja Anda</span>
                </h3>
                <button onclick="goToMarketView('home')" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white rounded-xl text-xs font-bold transition flex items-center gap-1.5">
                    <span class="material-symbols-outlined text-sm">arrow_back</span>
                    <span>Lanjut Belanja</span>
                </button>
            </div>
            
            <div class="flex flex-col gap-6">
                ${groupsHtml}
            </div>
        </div>
    `;
}

function renderMarketCheckout(container) {
    const items = state.checkoutItems;
    const coopId = state.checkoutCoopId;
    
    if (!items || items.length === 0 || !coopId) {
        goToMarketView(state.marketCart.length > 0 ? 'cart' : 'home');
        return;
    }

    const coop = state.cooperatives.find(c => c.id == coopId);
    const user = state.customerSession;
    if (!user) {
        openWebLoginModal();
        return;
    }

    if (!state.shippingAddress) {
        state.shippingAddress = 'Jl. Jenderal Sudirman No. 24, Limboto, Gorontalo';
    }

    const subtotal = items.reduce((sum, item) => sum + (item.harga * item.qty), 0);
    const initialOngkir = 15000;
    const initialTotal = subtotal + initialOngkir;

    const enabledMethods = (coop && coop.payment_methods ? coop.payment_methods : 'qris,transfer_bank,bri,bni,mandiri,bsi').split(',');
    
    let paymentOptionsHtml = `
        <option value="saldo">Saldo Anggota Digital - Rp 500.000 (Aktif)</option>
        <option value="cod">Cash on Delivery (COD)</option>
    `;
    
    enabledMethods.forEach(method => {
        const m = method.trim().toLowerCase();
        if (m === 'qris') {
            paymentOptionsHtml += `<option value="qris">QRIS Koperasi Digital</option>`;
        } else if (m === 'transfer_bank') {
            paymentOptionsHtml += `<option value="transfer_bank">Transfer Bank Manual</option>`;
        } else if (m === 'bri') {
            paymentOptionsHtml += `<option value="bri">Bank BRI (BRIVA)</option>`;
        } else if (m === 'bni') {
            paymentOptionsHtml += `<option value="bni">Bank BNI VA</option>`;
        } else if (m === 'mandiri') {
            paymentOptionsHtml += `<option value="mandiri">Bank Mandiri VA</option>`;
        } else if (m === 'bsi') {
            paymentOptionsHtml += `<option value="bsi">Bank BSI VA</option>`;
        }
    });

    container.innerHTML = `
        <div class="max-w-2xl mx-auto flex flex-col gap-6 bg-slate-800/20 border border-slate-700/30 rounded-3xl p-6 lg:p-8 shadow-xl relative">
            <button onclick="goToMarketView('${state.marketCart.length > 0 ? 'cart' : 'home'}')" class="absolute top-4 left-4 p-2 bg-slate-800 hover:bg-slate-700 border border-slate-700 text-white rounded-full transition flex items-center justify-center">
                <span class="material-symbols-outlined text-sm">arrow_back</span>
            </button>

            <div class="text-center mb-2">
                <h2 class="font-heading text-xl font-extrabold text-white tracking-tight">Checkout Pemesanan</h2>
                <p class="text-slate-400 text-xs mt-1">Konfirmasi pesanan barang, pengiriman, dan selesaikan pembayaran.</p>
            </div>

            <!-- Checkout Items List -->
            <div class="space-y-3 bg-slate-900/60 border border-slate-850 p-4 rounded-2xl max-h-[220px] overflow-y-auto no-scrollbar">
                ${items.map(item => `
                    <div class="flex items-center gap-4 border-b border-slate-800/40 last:border-b-0 pb-3 last:pb-0">
                        <img src="${item.foto}" class="w-12 h-12 rounded-xl object-cover border border-slate-700/50">
                        <div class="flex-1">
                            <h4 class="text-xs font-bold text-white line-clamp-1">${item.nama_produk}</h4>
                            <p class="text-[9px] text-slate-500 mt-0.5">Qty: ${item.qty} pcs</p>
                            <p class="text-xs font-black text-slate-400 mt-1">Rp ${Number(item.harga).toLocaleString('id-ID')} / pcs</p>
                        </div>
                        <div class="text-right">
                            <span class="text-xs font-black text-white">Rp ${Number(item.harga * item.qty).toLocaleString('id-ID')}</span>
                        </div>
                    </div>
                `).join('')}
            </div>

            <div class="space-y-4">
                <div>
                    <label class="block text-slate-400 text-xs font-semibold mb-2 flex items-center gap-1">
                        <span class="material-symbols-outlined text-sm">home_pin</span>
                        <span>Alamat Pengiriman</span>
                    </label>
                    <textarea id="market-checkout-address" required class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary h-20 resize-none">${state.shippingAddress}</textarea>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-slate-400 text-xs font-semibold mb-2 flex items-center gap-1">
                            <span class="material-symbols-outlined text-sm">local_shipping</span>
                            <span>Pilih Jasa Pengiriman</span>
                        </label>
                        <select id="market-checkout-courier" class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary">
                            <option value="KopExpress" ${state.selectedCourier === 'KopExpress' ? 'selected' : ''}>KopExpress (Koperasi Instant) - Rp 15.000</option>
                            <option value="POS Indonesia" ${state.selectedCourier === 'POS Indonesia' ? 'selected' : ''}>POS Indonesia (Ekspedisi) - Rp 12.000</option>
                            <option value="JNE Express" ${state.selectedCourier === 'JNE Express' ? 'selected' : ''}>JNE Express (Reguler) - Rp 18.000</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-slate-400 text-xs font-semibold mb-2 flex items-center gap-1">
                            <span class="material-symbols-outlined text-sm">account_balance_wallet</span>
                            <span>Metode Pembayaran</span>
                        </label>
                        <select id="market-checkout-payment" class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary">
                            ${paymentOptionsHtml}
                        </select>
                    </div>
                </div>
            </div>

            <div class="border-t border-slate-800 pt-4 space-y-2 text-xs">
                <div class="flex justify-between text-slate-400">
                    <span>Harga Barang (${items.reduce((sum, item) => sum + item.qty, 0)} pcs):</span>
                    <span>Rp ${subtotal.toLocaleString('id-ID')}</span>
                </div>
                <div class="flex justify-between text-slate-400">
                    <span>Ongkos Kirim:</span>
                    <span id="market-checkout-ongkir-display">Rp 15.000</span>
                </div>
                <div class="flex justify-between text-white font-black text-sm pt-2 border-t border-slate-800">
                    <span>Total Pembayaran:</span>
                    <span id="market-checkout-total-display">Rp ${initialTotal.toLocaleString('id-ID')}</span>
                </div>
            </div>

            <button onclick="checkoutMarketOrder()" class="w-full bg-gradient-to-r from-primary to-secondary hover:from-primary/95 hover:to-secondary/95 text-white font-bold text-xs uppercase tracking-wider px-6 py-3.5 rounded-xl shadow-lg transition flex items-center justify-center gap-1.5">
                <span class="material-symbols-outlined text-base">payments</span>
                <span>Konfirmasi & Bayar</span>
            </button>
        </div>
    `;

    const courierSelect = document.getElementById('market-checkout-courier');
    if (courierSelect) {
        courierSelect.addEventListener('change', (e) => {
            const val = e.target.value;
            let ongkir = 15000;
            if (val === 'POS Indonesia') ongkir = 12000;
            if (val === 'JNE Express') ongkir = 18000;
            
            document.getElementById('market-checkout-ongkir-display').innerText = `Rp ${ongkir.toLocaleString('id-ID')}`;
            document.getElementById('market-checkout-total-display').innerText = `Rp ${(subtotal + ongkir).toLocaleString('id-ID')}`;
        });
    }
}

async function checkoutMarketOrder() {
    const items = state.checkoutItems;
    const coopId = state.checkoutCoopId;
    const coop = state.cooperatives.find(c => c.id == coopId);
    const user = state.customerSession;
    if (!user || !items || items.length === 0 || !coop) return;

    const address = document.getElementById('market-checkout-address').value;
    const courier = document.getElementById('market-checkout-courier').value;
    const payment = document.getElementById('market-checkout-payment').value;

    let ongkir = 15000;
    if (courier === 'POS Indonesia') ongkir = 12000;
    if (courier === 'JNE Express') ongkir = 18000;
    
    const subtotal = items.reduce((sum, item) => sum + (item.harga * item.qty), 0);
    const total = subtotal + ongkir;

    const invoice = 'INV-' + new Date().getFullYear() + String(new Date().getMonth() + 1).padStart(2, '0') + String(new Date().getDate()).padStart(2, '0') + '-' + Math.random().toString(36).substring(2, 8).toUpperCase();
    const itemsJson = JSON.stringify(items.map(i => ({ product_id: i.product_id, qty: i.qty })));

    try {
        const response = await fetch('/api/orders', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `user_id=${user.id}&koperasi_id=${coop.id}&items=${encodeURIComponent(itemsJson)}&shipping_courier=${encodeURIComponent(courier)}&shipping_address=${encodeURIComponent(address)}&total_amount=${total}&shipping_cost=${ongkir}&payment_method=${encodeURIComponent(payment)}`
        });
        
        const res = await response.json();
        if (response.ok) {
            logConsole(`Sukses memesan produk! Invoice: ${invoice}`);
            
            // Clear checked out items from cart
            const checkedOutIds = items.map(i => i.product_id);
            state.marketCart = state.marketCart.filter(item => !checkedOutIds.includes(item.product_id));
            
            await loadAllData(); 
            goToMarketView('orders');

            const createdOrder = state.orders.find(o => o.id == res.data.order_id) || {
                id: res.data.order_id,
                invoice: res.data.invoice || invoice,
                total: res.data.total || total,
                payment_method: payment,
                status: 'PENDING_PAYMENT'
            };
            openMarketPaymentModal(createdOrder);
        } else {
            throw new Error(res.message || 'API order error');
        }
    } catch (e) {
        logConsole('Koneksi API gagal. Membuat transaksi belanja secara lokal (simulasi).', 'warning');
        
        const newOrderId = state.orders.length + 1;
        const newOrder = {
            id: newOrderId,
            invoice: invoice,
            customer_id: user.id,
            customer_name: user.nama,
            koperasi_id: coop.id,
            total: total,
            status: 'PENDING_PAYMENT',
            payment_method: payment,
            ongkir: ongkir,
            kurir: courier,
            alamat: address,
            created_at: new Date().toISOString().replace('T', ' ').substring(0, 19)
        };
        
        state.orders.unshift(newOrder);
        
        // Clear checked out items from cart
        const checkedOutIds = items.map(i => i.product_id);
        state.marketCart = state.marketCart.filter(item => !checkedOutIds.includes(item.product_id));
        
        goToMarketView('orders');
        openMarketPaymentModal(newOrder);
    }
}

function renderMarketOrders(container) {
    const user = state.customerSession;
    if (!user) {
        goToMarketView('home');
        return;
    }

    const myOrders = state.orders.filter(o => o.customer_id == user.id);

    container.innerHTML = `
        <div class="flex flex-col gap-6 max-w-4xl mx-auto">
            <div class="flex justify-between items-center border-b border-slate-800 pb-4">
                <h3 class="font-heading text-lg font-bold text-white flex items-center gap-2">
                    <span class="material-symbols-outlined text-primary">receipt_long</span>
                    <span>Riwayat Pesanan & Transaksi Belanja</span>
                </h3>
                <button onclick="goToMarketView('home')" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white rounded-xl text-xs font-bold transition">Kembali Belanja</button>
            </div>

            ${myOrders.length === 0 ? `
                <div class="text-center py-12 bg-slate-800/10 border border-slate-800 rounded-2xl">
                    <span class="material-symbols-outlined text-slate-600 text-4xl mb-2">receipt</span>
                    <p class="text-slate-500 text-xs font-semibold">Anda belum memiliki riwayat transaksi belanja.</p>
                </div>
            ` : `
                <div class="space-y-4">
                    ${myOrders.map(o => {
                        const coop = state.cooperatives.find(c => c.id == o.koperasi_id);
                        
                        let buyerActionsHtml = '';
                        if (o.status === 'PENDING_PAYMENT') {
                            buyerActionsHtml = `
                                <div class="flex gap-3 justify-end mt-2 pt-3 border-t border-slate-800/40">
                                    <button onclick="updateOrderStatus(${o.id}, 'CANCELLED_BY_CUSTOMER')" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white rounded-xl text-[10px] font-bold uppercase tracking-wider transition">Batalkan Pesanan</button>
                                    <button onclick="openMarketPaymentModalByOrderId(${o.id})" class="px-4 py-2 bg-gradient-to-r from-primary to-secondary text-white rounded-xl text-[10px] font-bold uppercase tracking-wider transition shadow-lg shadow-primary/20 flex items-center gap-1.5">
                                        <span class="material-symbols-outlined text-xs">payments</span>
                                        <span>Bayar Sekarang</span>
                                    </button>
                                </div>
                            `;
                        } else if (o.status === 'DELIVERED') {
                            buyerActionsHtml = `
                                <div class="flex gap-3 justify-end mt-2 pt-3 border-t border-slate-800/40">
                                    <button onclick="updateOrderStatus(${o.id}, 'RETURN_REQUEST')" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white rounded-xl text-[10px] font-bold uppercase tracking-wider transition">Ajukan Retur</button>
                                    <button onclick="updateOrderStatus(${o.id}, 'COMPLETED')" class="px-4 py-2 bg-gradient-to-r from-emerald-500 to-teal-600 text-white rounded-xl text-[10px] font-bold uppercase tracking-wider transition shadow-lg shadow-emerald-500/20 flex items-center gap-1.5">
                                        <span class="material-symbols-outlined text-xs">check_circle</span>
                                        <span>Pesanan Selesai</span>
                                    </button>
                                </div>
                            `;
                        } else if (o.status === 'COMPLETED') {
                            buyerActionsHtml = `
                                <div class="flex gap-3 justify-end mt-2 pt-3 border-t border-slate-800/40">
                                    <button onclick="openReviewModal(${o.id}, ${o.koperasi_id})" class="px-4 py-2 bg-gradient-to-r from-amber-500 to-orange-500 text-white rounded-xl text-[10px] font-bold uppercase tracking-wider transition shadow-lg shadow-amber-500/20 flex items-center gap-1.5 hover:from-amber-400 hover:to-orange-400">
                                        <span class="material-symbols-outlined text-xs">star</span>
                                        <span>Berikan Ulasan</span>
                                    </button>
                                </div>
                            `;
                        } else if (o.status === 'RETURN_REQUEST') {
                            buyerActionsHtml = `
                                <div class="flex justify-end mt-2 pt-3 border-t border-slate-800/40 text-[10px] text-slate-400 italic font-semibold">
                                    Menunggu persetujuan retur oleh koperasi penjual...
                                </div>
                            `;
                        } else if (o.status === 'RETURN_APPROVED') {
                            buyerActionsHtml = `
                                <div class="flex justify-end mt-2 pt-3 border-t border-slate-800/40 text-[10px] text-emerald-400 font-bold uppercase tracking-wider">
                                    Retur disetujui, menunggu pengembalian dana...
                                </div>
                            `;
                        } else if (o.status === 'REFUNDED') {
                            buyerActionsHtml = `
                                <div class="flex justify-end mt-2 pt-3 border-t border-slate-800/40 text-[10px] text-slate-500 font-bold uppercase tracking-wider">
                                    Dana telah dikembalikan ke saldo anggota.
                                </div>
                            `;
                        }

                        return `
                            <div class="bg-slate-800/20 border border-slate-700/30 rounded-2xl p-5 flex flex-col gap-4 shadow-md">
                                <div class="flex flex-wrap justify-between items-center gap-2 border-b border-slate-800/60 pb-3">
                                    <div class="flex items-center gap-3">
                                        <span class="text-xs font-mono font-bold text-white">${o.invoice}</span>
                                        <span class="text-[10px] text-slate-500">${o.created_at || 'Baru'}</span>
                                    </div>
                                    ${getStatusBadge(o.status)}
                                </div>
                                <div class="flex items-center gap-4">
                                    <div class="w-10 h-10 rounded-xl bg-slate-900 flex items-center justify-center text-primary text-xl font-black">KM</div>
                                    <div class="flex-1 text-xs">
                                        <div class="flex justify-between items-center">
                                            <span class="text-slate-400">Penyedia Koperasi:</span>
                                            <strong class="text-white">${coop ? coop.nama_koperasi : 'Koperasi'}</strong>
                                        </div>
                                        <div class="flex justify-between items-center mt-1">
                                            <span class="text-slate-400">Metode Pembayaran:</span>
                                            <strong class="text-white uppercase">${o.payment_method || 'saldo'}</strong>
                                        </div>
                                        <div class="flex justify-between items-center mt-1">
                                            <span class="text-slate-400">Jasa Pengiriman / Kurir:</span>
                                            <strong class="text-white">${o.kurir || '-'}</strong>
                                        </div>
                                        <div class="flex justify-between items-center mt-1">
                                            <span class="text-slate-400">Alamat Pengiriman:</span>
                                            <span class="text-white line-clamp-1 max-w-[200px] md:max-w-none text-right font-medium">${o.alamat}</span>
                                        </div>
                                        <div class="flex justify-between items-center mt-2 pt-2 border-t border-slate-850 text-sm">
                                            <span class="text-slate-400 font-semibold">Total Transaksi:</span>
                                            <strong class="text-white font-black text-sm">Rp ${Number(o.total).toLocaleString('id-ID')}</strong>
                                        </div>
                                    </div>
                                </div>
                                ${buyerActionsHtml}
                            </div>
                        `;
                    }).join('')}
                </div>
            `}
        </div>
    `;
}

// ----------------------------------------------------
// EXTENDED ORDER LIFECYCLE HELPERS & payment CONFIG
// ----------------------------------------------------

// Render Color Status Badge dynamically
function getStatusBadge(status) {
    let text = status;
    let colorClass = 'bg-slate-800 text-slate-200 border-slate-700'; // Default fallback
    
    switch (status) {
        case 'PENDING_PAYMENT':
            text = 'Menunggu Pembayaran';
            colorClass = 'bg-yellow-950/40 text-yellow-400 border-yellow-800/30';
            break;
        case 'PAYMENT_VERIFIED':
            text = 'Pembayaran Berhasil';
            colorClass = 'bg-blue-950/40 text-blue-400 border-blue-800/30';
            break;
        case 'WAITING_PROCESS':
            text = 'Pesanan Sedang Diproses';
            colorClass = 'bg-indigo-950/40 text-indigo-400 border-indigo-800/30';
            break;
        case 'VERIFIKASI_KOPERASI':
            text = 'Terverifikasi Koperasi';
            colorClass = 'bg-violet-950/40 text-violet-400 border-violet-800/30';
            break;
        case 'PACKING':
            text = 'Barang Sedang Dikemas';
            colorClass = 'bg-fuchsia-950/40 text-fuchsia-400 border-fuchsia-800/30';
            break;
        case 'READY_TO_SHIP':
            text = 'Siap Dikirim';
            colorClass = 'bg-cyan-950/40 text-cyan-400 border-cyan-800/30';
            break;
        case 'SHIPPED':
            text = 'Barang Telah Dikirim';
            colorClass = 'bg-sky-950/40 text-sky-400 border-sky-800/30';
            break;
        case 'IN_TRANSIT':
            text = 'Dalam Pengiriman';
            colorClass = 'bg-orange-950/40 text-orange-400 border-orange-800/30';
            break;
        case 'ARRIVED_DESTINATION':
            text = 'Tiba di Kota Tujuan';
            colorClass = 'bg-teal-950/40 text-teal-400 border-teal-800/30';
            break;
        case 'OUT_FOR_DELIVERY':
            text = 'Sedang Diantar';
            colorClass = 'bg-emerald-950/40 text-emerald-400 border-emerald-800/30';
            break;
        case 'DELIVERED':
            text = 'Barang Diterima';
            colorClass = 'bg-green-950/40 text-green-400 border-green-800/30';
            break;
        case 'COMPLETED':
            text = 'Pesanan Selesai';
            colorClass = 'bg-green-900/60 text-green-300 border-green-700/40';
            break;
        case 'CANCELLED_BY_CUSTOMER':
            text = 'Dibatalkan Pembeli';
            colorClass = 'bg-rose-950/40 text-rose-400 border-rose-800/30';
            break;
        case 'REJECTED_BY_SELLER':
            text = 'Ditolak Koperasi';
            colorClass = 'bg-red-950/40 text-red-400 border-red-800/30';
            break;
        case 'PAYMENT_FAILED':
            text = 'Pembayaran Gagal';
            colorClass = 'bg-red-950/40 text-red-400 border-red-800/30';
            break;
        case 'RETURN_REQUEST':
            text = 'Pengajuan Retur';
            colorClass = 'bg-slate-800 text-slate-400 border-slate-700';
            break;
        case 'RETURN_APPROVED':
            text = 'Retur Disetujui';
            colorClass = 'bg-slate-700 text-slate-300 border-slate-650';
            break;
        case 'REFUNDED':
            text = 'Dana Dikembalikan';
            colorClass = 'bg-slate-900 text-slate-500 border-slate-800';
            break;
        // Backward compatibility fallbacks
        case 'pending':
            text = 'Menunggu Pembayaran';
            colorClass = 'bg-yellow-950/40 text-yellow-400 border-yellow-800/30';
            break;
        case 'paid':
            text = 'Pembayaran Berhasil';
            colorClass = 'bg-blue-950/40 text-blue-400 border-blue-800/30';
            break;
        case 'processing':
            text = 'Pesanan Sedang Diproses';
            colorClass = 'bg-indigo-950/40 text-indigo-400 border-indigo-800/30';
            break;
        case 'shipped':
            text = 'Barang Telah Dikirim';
            colorClass = 'bg-sky-950/40 text-sky-400 border-sky-800/30';
            break;
        case 'completed':
            text = 'Pesanan Selesai';
            colorClass = 'bg-green-900/60 text-green-300 border-green-700/40';
            break;
        case 'cancelled':
            text = 'Dibatalkan';
            colorClass = 'bg-rose-950/40 text-rose-400 border-rose-800/30';
            break;
    }
    
    return `<span class="px-2.5 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider border ${colorClass}">${text}</span>`;
}

// Initialize settings checkboxes when tab is rendered
function initCoopSettings() {
    const coop = state.cooperatives.find(c => c.id == state.coopId);
    if (!coop) return;

    const enabled = (coop.payment_methods || 'qris,transfer_bank,bri,bni,mandiri,bsi').split(',');
    
    document.getElementById('pay-qris').checked = enabled.includes('qris');
    document.getElementById('pay-transfer').checked = enabled.includes('transfer_bank');
    document.getElementById('pay-bri').checked = enabled.includes('bri');
    document.getElementById('pay-bni').checked = enabled.includes('bni');
    document.getElementById('pay-mandiri').checked = enabled.includes('mandiri');
    document.getElementById('pay-bsi').checked = enabled.includes('bsi');
}

// Save active payment options in settings panel
async function saveCoopSettings() {
    const hours = document.getElementById('coop-settings-hours').value;
    const packing = document.getElementById('coop-settings-packing').value;
    
    const paymentMethods = [];
    if (document.getElementById('pay-qris').checked) paymentMethods.push('qris');
    if (document.getElementById('pay-transfer').checked) paymentMethods.push('transfer_bank');
    if (document.getElementById('pay-bri').checked) paymentMethods.push('bri');
    if (document.getElementById('pay-bni').checked) paymentMethods.push('bni');
    if (document.getElementById('pay-mandiri').checked) paymentMethods.push('mandiri');
    if (document.getElementById('pay-bsi').checked) paymentMethods.push('bsi');
    
    const paymentMethodsStr = paymentMethods.join(',');
    const id = state.coopId;
    
    try {
        const response = await fetch(`/api/cooperatives/${id}/update`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `payment_methods=${encodeURIComponent(paymentMethodsStr)}&user_id=${state.coopAdminId}`
        });
        
        if (response.ok) {
            const coop = state.cooperatives.find(c => c.id == id);
            if (coop) {
                coop.payment_methods = paymentMethodsStr;
            }
            logConsole('Pengaturan toko dan metode pembayaran berhasil disimpan.');
            showMarketToast('Pengaturan pembayaran berhasil disimpan!');
            loadAllData();
        } else {
            logConsole('Gagal menyimpan pengaturan toko.', 'error');
        }
    } catch (e) {
        logConsole('Gagal menghubungi API. Menyimpan secara lokal (simulasi).', 'warning');
        const coop = state.cooperatives.find(c => c.id == id);
        if (coop) {
            coop.payment_methods = paymentMethodsStr;
        }
        showMarketToast('Pengaturan pembayaran berhasil disimpan (Lokal)!');
    }
}

// Open Payment Gateway Sheet Modal for Customer
function openMarketPaymentModal(order) {
    let modal = document.getElementById('market-payment-modal');
    if (modal) modal.remove();

    modal = document.createElement('div');
    modal.id = 'market-payment-modal';
    modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/85 backdrop-blur-sm p-4';
    
    let paymentContentHtml = '';
    const method = (order.payment_method || 'saldo').toLowerCase();
    
    if (method === 'qris') {
        paymentContentHtml = `
            <div class="flex flex-col items-center gap-4 text-center">
                <div class="bg-white p-3 rounded-2xl shadow-inner border border-slate-200">
                    <div class="w-44 h-44 bg-[radial-gradient(#1e293b_1px,transparent_1px)] bg-[size:10px_10px] flex items-center justify-center relative">
                        <div class="absolute inset-4 bg-slate-900 flex items-center justify-center rounded-xl border-4 border-white">
                            <span class="text-white font-extrabold font-heading text-lg tracking-tight">QRIS KP</span>
                        </div>
                    </div>
                </div>
                <div class="text-[10px] text-slate-400">Pindai kode QR di atas menggunakan aplikasi e-wallet Anda untuk menyelesaikan pembayaran.</div>
            </div>
        `;
    } else if (method === 'saldo') {
        paymentContentHtml = `
            <div class="bg-slate-900/80 border border-slate-800/60 p-5 rounded-2xl flex flex-col gap-3">
                <div class="flex justify-between items-center text-xs">
                    <span class="text-slate-400">Saldo Anggota Anda:</span>
                    <strong class="text-white">Rp 500.000</strong>
                </div>
                <div class="flex justify-between items-center text-xs border-t border-slate-800/40 pt-2.5">
                    <span class="text-slate-400">Total Tagihan:</span>
                    <strong class="text-primary font-black">Rp ${Number(order.total).toLocaleString('id-ID')}</strong>
                </div>
                <div class="text-[10px] text-emerald-400 font-medium mt-1 flex items-center gap-1.5">
                    <span class="material-symbols-outlined text-sm">lock</span>
                    <span>Transaksi ini diamankan menggunakan enkripsi PIN saldo.</span>
                </div>
            </div>
        `;
    } else if (['bri', 'bni', 'mandiri', 'bsi', 'transfer_bank'].includes(method)) {
        let bankLabel = 'Bank Transfer';
        let vaNumber = '8801' + String(order.id).padStart(4, '0') + Math.random().toString().substring(2, 10);
        if (method === 'bri') bankLabel = 'BRI Virtual Account (BRIVA)';
        if (method === 'bni') bankLabel = 'BNI Virtual Account';
        if (method === 'mandiri') bankLabel = 'Mandiri VA Bill Payment';
        if (method === 'bsi') bankLabel = 'BSI Virtual Account';
        
        paymentContentHtml = `
            <div class="bg-slate-900/80 border border-slate-800/60 p-5 rounded-2xl flex flex-col gap-3">
                <div class="flex flex-col gap-1">
                    <span class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">${bankLabel}</span>
                    <div class="flex items-center justify-between mt-1">
                        <strong class="text-base text-white font-mono tracking-wider" id="va-number-text">${vaNumber}</strong>
                        <button onclick="navigator.clipboard.writeText('${vaNumber}'); showMarketToast('Nomor VA disalin!')" class="text-xs text-primary hover:underline font-bold">Salin</button>
                    </div>
                </div>
                <div class="flex justify-between items-center text-xs border-t border-slate-800/40 pt-3">
                    <span class="text-slate-400">Nama Rekening:</span>
                    <strong class="text-white">Koperasi Digital Merah Putih</strong>
                </div>
                <div class="flex justify-between items-center text-xs">
                    <span class="text-slate-400">Jumlah Transfer:</span>
                    <strong class="text-white">Rp ${Number(order.total).toLocaleString('id-ID')}</strong>
                </div>
            </div>
        `;
    } else {
        paymentContentHtml = `
            <div class="bg-slate-900/80 border border-slate-800/60 p-5 rounded-2xl flex flex-col gap-2.5 text-center text-xs text-slate-400">
                <span class="material-symbols-outlined text-3xl text-slate-600">local_shipping</span>
                <div>Metode pembayaran Cash on Delivery (COD). Selesaikan pembayaran secara tunai saat kurir menyerahkan barang.</div>
            </div>
        `;
    }

    modal.innerHTML = `
        <div class="w-full max-w-md bg-brandSurface border border-slate-800 rounded-3xl p-6 shadow-2xl relative overflow-hidden flex flex-col gap-5">
            <div class="absolute top-0 left-0 right-0 h-[3px] bg-gradient-to-r from-primary to-secondary"></div>
            
            <div class="flex justify-between items-center">
                <h3 class="font-heading text-base font-extrabold text-white">Proses Pembayaran</h3>
                <button onclick="document.getElementById('market-payment-modal').remove()" class="text-slate-400 hover:text-white transition">
                    <span class="material-symbols-outlined text-lg">close</span>
                </button>
            </div>
            
            <div class="flex justify-between items-center bg-slate-900/60 border border-slate-850 p-3.5 rounded-2xl text-xs">
                <div>
                    <div class="text-[9px] text-slate-500 font-bold uppercase tracking-wider">Invoice</div>
                    <strong class="text-white font-mono">${order.invoice}</strong>
                </div>
                <div class="text-right">
                    <div class="text-[9px] text-slate-500 font-bold uppercase tracking-wider">Total Pembayaran</div>
                    <strong class="text-primary font-black text-sm">Rp ${Number(order.total).toLocaleString('id-ID')}</strong>
                </div>
            </div>
            
            ${paymentContentHtml}
            
            <div class="flex gap-3 mt-2">
                <button onclick="document.getElementById('market-payment-modal').remove()" class="flex-1 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white font-bold text-xs uppercase tracking-wider py-3 rounded-xl transition">
                    Kembali
                </button>
                <button id="btn-confirm-payment" onclick="processSimulatedPayment(${order.id})" class="flex-1 bg-gradient-to-r from-primary to-secondary hover:from-primary/95 hover:to-secondary/95 text-white font-bold text-xs uppercase tracking-wider py-3 rounded-xl transition shadow-lg shadow-primary/20 flex items-center justify-center gap-1.5">
                    <span class="material-symbols-outlined text-sm">check_circle</span>
                    <span>Konfirmasi Bayar</span>
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
}

function openMarketPaymentModalByOrderId(orderId) {
    const order = state.orders.find(o => o.id == orderId);
    if (order) {
        openMarketPaymentModal(order);
    }
}

async function processSimulatedPayment(orderId) {
    const btn = document.getElementById('btn-confirm-payment');
    if (btn) {
        btn.disabled = true;
        btn.innerHTML = `<span class="material-symbols-outlined text-sm animate-spin">sync</span> <span>Memproses...</span>`;
    }
    
    try {
        await updateOrderStatusLocalAndRemote(orderId, 'PAYMENT_VERIFIED');
        
        const modal = document.getElementById('market-payment-modal');
        if (modal) {
            modal.innerHTML = `
                <div class="w-full max-w-sm bg-brandSurface border border-slate-800 rounded-3xl p-8 shadow-2xl flex flex-col items-center justify-center gap-5 text-center relative overflow-hidden">
                    <div class="absolute top-0 left-0 right-0 h-[3px] bg-emerald-500"></div>
                    <div class="w-16 h-16 rounded-full bg-emerald-950/40 border border-emerald-800 text-emerald-400 flex items-center justify-center shadow-lg shadow-emerald-500/10">
                        <span class="material-symbols-outlined text-3xl font-bold">done</span>
                    </div>
                    <div>
                        <h4 class="font-heading text-base font-extrabold text-white">Pembayaran Berhasil!</h4>
                        <p class="text-slate-400 text-xs mt-1">Sistem mendeteksi transfer payment gateway aman.</p>
                    </div>
                    <div class="text-[9px] bg-slate-900 border border-slate-850 px-3 py-1 rounded-full text-slate-500 font-mono">Status: PAYMENT_VERIFIED</div>
                </div>
            `;
        }
        
        setTimeout(async () => {
            await updateOrderStatusLocalAndRemote(orderId, 'WAITING_PROCESS');
            showMarketToast('Pembayaran selesai, menunggu diproses oleh koperasi.');
            
            const modalEl = document.getElementById('market-payment-modal');
            if (modalEl) modalEl.remove();
            
            goToMarketView('orders');
        }, 1500);
        
    } catch (e) {
        showMarketToast('Koneksi terganggu. Gagal memproses simulasi.', 'error');
        if (btn) {
            btn.disabled = false;
            btn.innerHTML = `<span class="material-symbols-outlined text-sm">check_circle</span> <span>Konfirmasi Bayar</span>`;
        }
    }
}

async function updateOrderStatusLocalAndRemote(id, newStatus) {
    try {
        await fetch(`/api/orders/${id}/status`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `status=${newStatus}&user_id=${state.coopAdminId}`
        });
    } catch (e) {}

    const order = state.orders.find(o => o.id == id);
    if (order) {
        order.status = newStatus;
        logConsole(`Status pesanan "${order.invoice}" diperbarui menjadi ${newStatus}`);
    }
    await loadAllData();
}

// ----------------------------------------------------
// USER PROFILE MANAGEMENT & WEBCAM SIMULATOR
// ----------------------------------------------------

let activeWebcamStream = null;
let profilePhotoBase64 = null;
let qrisImageBase64 = null;
let selfieImageBase64 = null;

function resolveAssetPath(path) {
    if (!path) return '';
    if (path.startsWith('data:') || path.startsWith('http') || path.startsWith('blob:')) {
        return path;
    }
    const pathname = window.location.pathname;
    let base = '/';
    if (pathname.includes('/public')) {
        base = pathname.substring(0, pathname.indexOf('/public') + 7) + '/';
    } else if (pathname.includes('/index.php')) {
        base = pathname.substring(0, pathname.indexOf('/index.php')) + '/';
    }
    return base + path;
}

function renderMarketProfile(container) {
    const user = state.customerSession;
    if (!user) {
        goToMarketView('home');
        return;
    }

    profilePhotoBase64 = user.foto_profil || null;
    qrisImageBase64 = user.qris_path || null;
    selfieImageBase64 = null;

    const verificationStatus = user.verification_status || 'UNVERIFIED';
    let statusText = 'Belum Terverifikasi';
    let statusBadgeClass = 'bg-slate-800 text-slate-400 border-slate-700';

    if (verificationStatus === 'VERIFIED') {
        statusText = 'Terverifikasi (Akun Resmi)';
        statusBadgeClass = 'bg-emerald-950/40 text-emerald-400 border-emerald-800/30';
    } else if (verificationStatus === 'PENDING') {
        statusText = 'Menunggu Verifikasi Admin';
        statusBadgeClass = 'bg-yellow-950/40 text-yellow-400 border-yellow-800/30';
    }

    const currentProfilePic = profilePhotoBase64 ? resolveAssetPath(profilePhotoBase64) : 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=150';
    const currentQrisPic = qrisImageBase64 ? resolveAssetPath(qrisImageBase64) : '';

    container.innerHTML = `
        <div class="max-w-4xl mx-auto flex flex-col gap-6 relative">
            <div class="flex justify-between items-center border-b border-slate-800 pb-4">
                <h3 class="font-heading text-lg font-bold text-white flex items-center gap-2">
                    <span class="material-symbols-outlined text-primary">manage_accounts</span>
                    <span>Pengaturan Profil Anggota</span>
                </h3>
                <button onclick="goToMarketView('home')" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white rounded-xl text-xs font-bold transition">Kembali Belanja</button>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
                
                <!-- Left Column: Summary & Webcam -->
                <div class="flex flex-col gap-5 bg-slate-800/20 border border-slate-700/30 rounded-3xl p-6 lg:p-7 shadow-xl backdrop-blur-sm text-center">
                    <div class="relative w-32 h-32 mx-auto rounded-full overflow-hidden border-2 border-primary/50 group bg-slate-900 flex items-center justify-center">
                        <img id="profile-preview-pic" src="${currentProfilePic}" class="w-full h-full object-cover">
                        <div class="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 flex flex-col items-center justify-center gap-1 transition cursor-pointer text-white text-[10px] font-bold" onclick="document.getElementById('profile-file-input').click()">
                            <span class="material-symbols-outlined text-base">photo_camera</span>
                            <span>Unggah Foto</span>
                        </div>
                    </div>
                    <input type="file" id="profile-file-input" class="hidden" accept="image/*" onchange="handleProfilePhotoUpload(event)">

                    <div>
                        <h4 class="text-white text-sm font-bold">${user.nama}</h4>
                        <p class="text-slate-400 text-[10px] mt-0.5">${user.email}</p>
                    </div>

                    <div class="flex justify-center">
                        <span class="px-3 py-1 text-[9px] font-bold uppercase tracking-wider rounded-full border ${statusBadgeClass}">
                            ${statusText}
                        </span>
                    </div>

                    <div class="border-t border-slate-800/80 pt-4 text-left flex flex-col gap-2">
                        <label class="block text-slate-400 text-xs font-semibold mb-1">Ambil Foto via Kamera</label>
                        <div id="camera-container" class="relative w-full h-44 rounded-2xl overflow-hidden bg-slate-900 border border-slate-800 flex flex-col items-center justify-center gap-2 text-slate-500">
                            <span class="material-symbols-outlined text-3xl">videocam_off</span>
                            <span class="text-[9px]">Kamera tidak aktif</span>
                        </div>
                        <div class="flex gap-2">
                            <button id="btn-toggle-camera" onclick="startWebcamStream()" class="flex-1 bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white font-bold text-[9px] uppercase py-2 rounded-lg transition flex items-center justify-center gap-1">
                                <span class="material-symbols-outlined text-xs">videocam</span>
                                <span>Aktifkan</span>
                            </button>
                            <button id="btn-snapshot-camera" onclick="takeWebcamSnapshot()" disabled class="flex-1 bg-gradient-to-r from-primary to-secondary hover:from-primary/95 hover:to-secondary/95 text-white font-bold text-[9px] uppercase py-2 rounded-lg transition disabled:opacity-50 flex items-center justify-center gap-1">
                                <span class="material-symbols-outlined text-xs">photo_camera</span>
                                <span>Ambil Foto</span>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Right Column: Settings -->
                <div class="lg:col-span-2 flex flex-col gap-5">
                    
                    <!-- Section: Personal Info -->
                    <div class="bg-slate-800/20 border border-slate-700/30 rounded-3xl p-6 lg:p-7 shadow-xl backdrop-blur-sm flex flex-col gap-4">
                        <h4 class="font-heading text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1.5 pb-2 border-b border-slate-800">
                            <span class="material-symbols-outlined text-primary text-sm">person</span>
                            <span>Informasi Pribadi & Alamat Utama</span>
                        </h4>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-slate-400 text-xs font-semibold mb-2">Nama Lengkap</label>
                                <input id="profile-name" type="text" class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary" value="${user.nama}">
                            </div>
                            <div>
                                <label class="block text-slate-400 text-xs font-semibold mb-2">Email</label>
                                <input id="profile-email" type="email" class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary" value="${user.email}">
                            </div>
                            <div>
                                <label class="block text-slate-400 text-xs font-semibold mb-2">Nomor Telepon</label>
                                <input id="profile-phone" type="text" class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary" value="${user.phone || ''}">
                            </div>
                            <div>
                                <label class="block text-slate-400 text-xs font-semibold mb-2">NIK (Nomor Induk Kependudukan)</label>
                                <input id="profile-nik" type="text" maxlength="16" class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary" placeholder="Masukkan 16 digit NIK" value="${user.nik || ''}">
                            </div>
                        </div>

                        <div>
                            <label class="block text-slate-400 text-xs font-semibold mb-2 flex items-center gap-1">
                                <span class="material-symbols-outlined text-sm">home_pin</span>
                                <span>Alamat Pengiriman Utama (Tujuan Paket)</span>
                            </label>
                            <textarea id="profile-address" class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary h-20 resize-none" placeholder="Tuliskan alamat lengkap pengiriman paket anda">${user.alamat_utama || ''}</textarea>
                        </div>
                    </div>

                    <!-- Section: Payments -->
                    <div class="bg-slate-800/20 border border-slate-700/30 rounded-3xl p-6 lg:p-7 shadow-xl backdrop-blur-sm flex flex-col gap-4">
                        <h4 class="font-heading text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1.5 pb-2 border-b border-slate-800">
                            <span class="material-symbols-outlined text-primary text-sm">account_balance</span>
                            <span>Data Rekening & QRIS Pribadi (Refund / Withdraw)</span>
                        </h4>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-slate-400 text-xs font-semibold mb-2">Pilih Bank</label>
                                <select id="profile-bank-name" class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary">
                                    <option value="">-- Pilih Bank --</option>
                                    <option value="BRI" ${user.bank_name === 'BRI' ? 'selected' : ''}>Bank BRI</option>
                                    <option value="BNI" ${user.bank_name === 'BNI' ? 'selected' : ''}>Bank BNI</option>
                                    <option value="Mandiri" ${user.bank_name === 'Mandiri' ? 'selected' : ''}>Bank Mandiri</option>
                                    <option value="BSI" ${user.bank_name === 'BSI' ? 'selected' : ''}>Bank BSI</option>
                                    <option value="BCA" ${user.bank_name === 'BCA' ? 'selected' : ''}>Bank BCA</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-slate-400 text-xs font-semibold mb-2">Nomor Rekening</label>
                                <input id="profile-rekening" type="text" class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary" placeholder="Contoh: 12400012345" value="${user.no_rekening || ''}">
                            </div>
                        </div>

                        <div>
                            <label class="block text-slate-400 text-xs font-semibold mb-2">QRIS Pribadi</label>
                            <div class="flex flex-col md:flex-row gap-4 items-center">
                                <div class="w-24 h-24 rounded-xl border border-slate-850 bg-slate-900 flex items-center justify-center overflow-hidden">
                                    <img id="qris-preview-pic" src="${currentQrisPic || 'https://images.unsplash.com/photo-1546868871-7041f2a55e12?w=100'}" class="w-full h-full object-cover ${currentQrisPic ? '' : 'opacity-20'}">
                                </div>
                                <div class="flex-1 flex flex-col gap-2 w-full">
                                    <input type="file" id="qris-file-input" class="hidden" accept="image/*" onchange="handleQrisPhotoUpload(event)">
                                    <button type="button" onclick="document.getElementById('qris-file-input').click()" class="bg-slate-900 hover:bg-slate-800 text-slate-200 border border-slate-700/70 font-bold text-xs px-4 py-2.5 rounded-xl transition w-full md:w-auto">
                                        Pilih Berkas QRIS
                                    </button>
                                    <p class="text-slate-500 text-[10px]">Format .png atau .jpg maksimal 2MB.</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Section: Security -->
                    <div class="bg-slate-800/20 border border-slate-700/30 rounded-3xl p-6 lg:p-7 shadow-xl backdrop-blur-sm flex flex-col gap-4">
                        <h4 class="font-heading text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1.5 pb-2 border-b border-slate-800">
                            <span class="material-symbols-outlined text-primary text-sm">lock</span>
                            <span>Ubah Kata Sandi</span>
                        </h4>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-slate-400 text-xs font-semibold mb-2">Kata Sandi Baru</label>
                                <input id="profile-new-pass" type="password" class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary" placeholder="Kosongkan jika tidak diubah">
                            </div>
                            <div>
                                <label class="block text-slate-400 text-xs font-semibold mb-2">Konfirmasi Kata Sandi</label>
                                <input id="profile-confirm-pass" type="password" class="w-full bg-slate-900 border border-slate-700/60 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-primary" placeholder="Kosongkan jika tidak diubah">
                            </div>
                        </div>
                    </div>

                    <!-- Section: Account Owner Identity Verification -->
                    <div class="bg-slate-800/20 border border-slate-700/30 rounded-3xl p-6 lg:p-7 shadow-xl backdrop-blur-sm flex flex-col gap-4">
                        <h4 class="font-heading text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1.5 pb-2 border-b border-slate-800">
                            <span class="material-symbols-outlined text-primary text-sm">verified_user</span>
                            <span>Konfirmasi Pemilik Akun</span>
                        </h4>

                        <div class="flex flex-col gap-3">
                            <p class="text-slate-400 text-[10px]">Unggah foto KTP atau foto selfie memegang identitas Anda untuk mengonfirmasi kepemilikan akun.</p>
                            
                            <div class="flex flex-col md:flex-row gap-4 items-center mt-1">
                                <div class="w-32 h-20 rounded-xl border border-slate-850 bg-slate-900 flex items-center justify-center overflow-hidden" id="selfie-preview-box">
                                    <span class="material-symbols-outlined text-3xl text-slate-700" id="selfie-placeholder-icon">badge</span>
                                </div>
                                <div class="flex-1 flex flex-col gap-2 w-full">
                                    <input type="file" id="selfie-file-input" class="hidden" accept="image/*" onchange="handleSelfiePhotoUpload(event)">
                                    <div class="flex gap-2">
                                        <button type="button" onclick="document.getElementById('selfie-file-input').click()" class="bg-slate-900 hover:bg-slate-800 text-slate-200 border border-slate-700/70 font-bold text-xs px-4 py-2.5 rounded-xl transition">
                                            Pilih Berkas KTP / Selfie
                                        </button>
                                        ${verificationStatus === 'UNVERIFIED' ? `
                                            <button type="button" onclick="requestIdentityVerification()" class="bg-emerald-900/60 hover:bg-emerald-850/80 text-emerald-400 border border-emerald-800/30 font-bold text-xs px-4 py-2.5 rounded-xl transition">
                                                Ajukan Verifikasi
                                            </button>
                                        ` : ''}
                                    </div>
                                    <p class="text-slate-500 text-[10px]">Format berkas .png atau .jpg maksimal 2MB.</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="flex gap-3 mt-2 justify-end">
                        <button onclick="goToMarketView('home')" class="bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white font-bold text-xs uppercase tracking-wider px-6 py-3.5 rounded-xl transition">
                            Batal
                        </button>
                        <button onclick="updateMarketProfile()" class="bg-gradient-to-r from-primary to-secondary hover:from-primary/95 hover:to-secondary/95 text-white font-bold text-xs uppercase tracking-wider px-7 py-3.5 rounded-xl shadow-lg transition flex items-center gap-1.5">
                            <span class="material-symbols-outlined text-sm">save</span>
                            <span>Simpan Perubahan</span>
                        </button>
                    </div>

                </div>

            </div>
        </div>
    `;
}

function startWebcamStream() {
    const container = document.getElementById('camera-container');
    if (!container) return;

    container.innerHTML = `
        <video id="webcam-feed" autoplay playsinline class="w-full h-full object-cover"></video>
        <canvas id="webcam-canvas" class="hidden"></canvas>
    `;

    const video = document.getElementById('webcam-feed');
    const toggleBtn = document.getElementById('btn-toggle-camera');
    const snapBtn = document.getElementById('btn-snapshot-camera');

    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: { width: 320, height: 240 } })
            .then(stream => {
                activeWebcamStream = stream;
                video.srcObject = stream;
                
                if (toggleBtn) {
                    toggleBtn.innerHTML = `<span class="material-symbols-outlined text-xs">videocam_off</span> <span>Matikan</span>`;
                    toggleBtn.setAttribute('onclick', 'stopWebcamStream()');
                }
                if (snapBtn) snapBtn.disabled = false;
                logConsole('Webcam diaktifkan untuk pengambilan foto profil.');
            })
            .catch(err => {
                logConsole('Gagal mengakses kamera. Menggunakan simulasi kamera.', 'warning');
                showWebcamSimulation();
            });
    } else {
        logConsole('Kamera tidak didukung browser ini. Menggunakan simulasi.', 'warning');
        showWebcamSimulation();
    }
}

function showWebcamSimulation() {
    const container = document.getElementById('camera-container');
    if (!container) return;

    container.innerHTML = `
        <div class="absolute inset-0 bg-slate-950 flex flex-col items-center justify-center gap-2 p-4 text-center">
            <div class="w-12 h-12 rounded-full border border-slate-700/60 flex items-center justify-center text-primary bg-primary/10 animate-pulse">
                <span class="material-symbols-outlined text-lg">videocam</span>
            </div>
            <p class="text-[10px] text-slate-400 font-bold">SIMULATOR KAMERA</p>
            <p class="text-[9px] text-slate-500 max-w-[200px]">Izin kamera diblokir atau tidak tersedia. Gunakan jepret simulasi di bawah.</p>
            <button onclick="captureSimulatedCamera()" class="mt-1 bg-primary hover:bg-primary/95 text-white font-bold text-[9px] px-3 py-1.5 rounded-lg transition uppercase tracking-wider flex items-center gap-1 justify-center">
                <span class="material-symbols-outlined text-xs">photo_camera</span>
                <span>Jepret Foto Simulasi</span>
            </button>
        </div>
    `;

    const toggleBtn = document.getElementById('btn-toggle-camera');
    if (toggleBtn) {
        toggleBtn.innerHTML = `<span class="material-symbols-outlined text-xs">videocam_off</span> <span>Matikan</span>`;
        toggleBtn.setAttribute('onclick', 'stopWebcamStream()');
    }
    const snapBtn = document.getElementById('btn-snapshot-camera');
    if (snapBtn) snapBtn.disabled = true;
}

function captureSimulatedCamera() {
    const avatars = [
        'https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=150',
        'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150',
        'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=150',
        'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=150'
    ];
    const chosen = avatars[Math.floor(Math.random() * avatars.length)];
    profilePhotoBase64 = chosen;

    const imgEl = document.getElementById('profile-preview-pic');
    if (imgEl) imgEl.src = chosen;

    showMarketToast('Simulasi capture berhasil!');
    logConsole('Simulasi foto profil kamera berhasil diambil.');
}

function stopWebcamStream() {
    if (activeWebcamStream) {
        activeWebcamStream.getTracks().forEach(track => track.stop());
        activeWebcamStream = null;
    }

    const container = document.getElementById('camera-container');
    if (container) {
        container.innerHTML = `
            <span class="material-symbols-outlined text-3xl">videocam_off</span>
            <span class="text-[9px]">Kamera tidak aktif</span>
        `;
    }

    const toggleBtn = document.getElementById('btn-toggle-camera');
    if (toggleBtn) {
        toggleBtn.innerHTML = `<span class="material-symbols-outlined text-xs">videocam</span> <span>Aktifkan</span>`;
        toggleBtn.setAttribute('onclick', 'startWebcamStream()');
    }

    const snapBtn = document.getElementById('btn-snapshot-camera');
    if (snapBtn) snapBtn.disabled = true;
    logConsole('Webcam dimatikan.');
}

function takeWebcamSnapshot() {
    const video = document.getElementById('webcam-feed');
    const canvas = document.createElement('canvas');
    if (!video) return;

    canvas.width = video.videoWidth || 320;
    canvas.height = video.videoHeight || 240;
    
    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    
    const base64 = canvas.toDataURL('image/png');
    profilePhotoBase64 = base64;

    const imgEl = document.getElementById('profile-preview-pic');
    if (imgEl) imgEl.src = base64;

    showMarketToast('Foto profil berhasil dijepret!');
    logConsole('Foto profil webcam berhasil ditangkap.');
    stopWebcamStream();
}

function handleProfilePhotoUpload(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function(e) {
        profilePhotoBase64 = e.target.result;
        const imgEl = document.getElementById('profile-preview-pic');
        if (imgEl) imgEl.src = e.target.result;
        showMarketToast('Pratinjau foto profil terpasang.');
    };
    reader.readAsDataURL(file);
}

function handleQrisPhotoUpload(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function(e) {
        qrisImageBase64 = e.target.result;
        const imgEl = document.getElementById('qris-preview-pic');
        if (imgEl) {
            imgEl.src = e.target.result;
            imgEl.classList.remove('opacity-20');
        }
        showMarketToast('Pratinjau QRIS berhasil dimuat.');
    };
    reader.readAsDataURL(file);
}

function handleSelfiePhotoUpload(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function(e) {
        selfieImageBase64 = e.target.result;
        const previewBox = document.getElementById('selfie-preview-box');
        if (previewBox) {
            previewBox.innerHTML = `<img src="${e.target.result}" class="w-full h-full object-cover">`;
        }
        showMarketToast('Foto identitas terpilih.');
    };
    reader.readAsDataURL(file);
}

function requestIdentityVerification() {
    if (!selfieImageBase64) {
        showMarketToast('Pilih atau unggah berkas KTP / Selfie terlebih dahulu!', 'error');
        return;
    }
    const user = state.customerSession;
    if (user) {
        user.verification_status = 'PENDING';
    }
    showMarketToast('Pengajuan verifikasi berhasil dikirim!');
    logConsole('Pengajuan verifikasi identitas (Selfie/KTP) dikirim.');
    
    const container = document.getElementById('market-content-area');
    if (container) renderMarketProfile(container);
}

async function updateMarketProfile() {
    const user = state.customerSession;
    if (!user) return;

    const nama = document.getElementById('profile-name').value.trim();
    const email = document.getElementById('profile-email').value.trim();
    const phone = document.getElementById('profile-phone').value.trim();
    const nik = document.getElementById('profile-nik').value.trim();
    const alamat_utama = document.getElementById('profile-address').value.trim();
    const bank_name = document.getElementById('profile-bank-name').value;
    const no_rekening = document.getElementById('profile-rekening').value.trim();
    const password = document.getElementById('profile-new-pass').value;
    const confirm_pass = document.getElementById('profile-confirm-pass').value;

    if (!nama || !email) {
        showMarketToast('Nama dan Email wajib diisi!', 'error');
        return;
    }

    if (password) {
        if (password.length < 6) {
            showMarketToast('Kata sandi minimal harus 6 karakter!', 'error');
            return;
        }
        if (password !== confirm_pass) {
            showMarketToast('Konfirmasi kata sandi tidak cocok!', 'error');
            return;
        }
    }

    if (nik && (nik.length !== 16 || isNaN(nik))) {
        showMarketToast('NIK harus berupa 16 digit angka!', 'error');
        return;
    }

    let bodyData = `nama=${encodeURIComponent(nama)}` +
                   `&email=${encodeURIComponent(email)}` +
                   `&phone=${encodeURIComponent(phone)}` +
                   `&nik=${encodeURIComponent(nik)}` +
                   `&alamat_utama=${encodeURIComponent(alamat_utama)}` +
                   `&bank_name=${encodeURIComponent(bank_name)}` +
                   `&no_rekening=${encodeURIComponent(no_rekening)}` +
                   `&verification_status=${user.verification_status || 'UNVERIFIED'}`;

    if (password) {
        bodyData += `&password=${encodeURIComponent(password)}`;
    }
    if (profilePhotoBase64 && profilePhotoBase64.startsWith('data:image')) {
        bodyData += `&foto_profil=${encodeURIComponent(profilePhotoBase64)}`;
    }
    if (qrisImageBase64 && qrisImageBase64.startsWith('data:image')) {
        bodyData += `&qris_path=${encodeURIComponent(qrisImageBase64)}`;
    }

    const token = localStorage.getItem('web_token');

    try {
        const response = await fetch('/api/auth/profile/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Bearer ${token}`
            },
            body: bodyData
        });

        const res = await response.json();
        if (response.ok) {
            state.customerSession = res.user;
            localStorage.setItem('web_user', JSON.stringify(res.user));
            
            const nameEl = document.getElementById('market-customer-name');
            if (nameEl) nameEl.innerText = res.user.nama;
            const avatarEl = document.getElementById('market-customer-avatar');
            if (avatarEl) {
                if (res.user.foto_profil) {
                    avatarEl.innerHTML = `<img src="${resolveAssetPath(res.user.foto_profil)}" class="w-full h-full object-cover rounded-lg border border-slate-700/50">`;
                } else {
                    avatarEl.innerText = res.user.nama.charAt(0).toUpperCase();
                }
            }

            showMarketToast('Profil berhasil disimpan!');
            logConsole(`Profil pengguna "${res.user.nama}" berhasil diperbarui.`);
            goToMarketView('home');
        } else {
            showMarketToast(res.message || 'Gagal memperbarui profil.', 'error');
        }
    } catch (e) {
        logConsole('Koneksi API gagal. Mengupdate profil secara lokal (simulasi).', 'warning');
        
        user.nama = nama;
        user.email = email;
        user.phone = phone;
        user.nik = nik;
        user.alamat_utama = alamat_utama;
        user.bank_name = bank_name;
        user.no_rekening = no_rekening;
        if (profilePhotoBase64) user.foto_profil = profilePhotoBase64;
        if (qrisImageBase64) user.qris_path = qrisImageBase64;

        localStorage.setItem('web_user', JSON.stringify(user));

        const nameEl = document.getElementById('market-customer-name');
        if (nameEl) nameEl.innerText = user.nama;
        const avatarEl = document.getElementById('market-customer-avatar');
        if (avatarEl) {
            if (user.foto_profil) {
                avatarEl.innerHTML = `<img src="${resolveAssetPath(user.foto_profil)}" class="w-full h-full object-cover rounded-lg border border-slate-700/50">`;
            } else {
                avatarEl.innerText = user.nama.charAt(0).toUpperCase();
            }
        }

        showMarketToast('Profil disimpan secara lokal (Simulasi)!');
        goToMarketView('home');
    }
}

// Window scope exports
window.resolveAssetPath = resolveAssetPath;
window.renderMarketProfile = renderMarketProfile;
window.updateMarketProfile = updateMarketProfile;
window.startWebcamStream = startWebcamStream;
window.stopWebcamStream = stopWebcamStream;
window.takeWebcamSnapshot = takeWebcamSnapshot;
window.handleProfilePhotoUpload = handleProfilePhotoUpload;
window.handleQrisPhotoUpload = handleQrisPhotoUpload;
window.handleSelfiePhotoUpload = handleSelfiePhotoUpload;
window.requestIdentityVerification = requestIdentityVerification;
window.captureSimulatedCamera = captureSimulatedCamera;

function renderSuperUsersVerifTable() {
    const tbody = document.getElementById('s-users-verif-table');
    if (!tbody) return;
    tbody.innerHTML = '';
    
    const customersList = (Array.isArray(state.users) && state.users.length) ? state.users.filter(u => u.role_id == 4 || u.role_name === 'Customer') : [
        { id: 7, nama: 'Budi Santoso', email: 'budi@gmail.com', role_name: 'Customer', status: 'active', role_id: 4, nik: '3201234567890123', alamat_utama: 'Jl. Merdeka No. 45, Gorontalo', verification_status: 'PENDING', foto_profil: '', qris_path: '' }
    ];

    if (customersList.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" class="py-8 text-center text-slate-500 text-xs">Tidak ada data konsumen/anggota terdaftar.</td>
            </tr>
        `;
        return;
    }

    customersList.forEach(u => {
        let verifBadge = '';
        const vStatus = u.verification_status || 'UNVERIFIED';
        if (vStatus === 'VERIFIED') {
            verifBadge = '<span class="px-2 py-0.5 bg-emerald-950/40 text-emerald-400 border border-emerald-800/30 rounded-full text-[10px] font-bold">TERVERIFIKASI</span>';
        } else if (vStatus === 'PENDING') {
            verifBadge = '<span class="px-2 py-0.5 bg-yellow-950/40 text-yellow-400 border border-yellow-800/30 rounded-full text-[10px] font-bold animate-pulse">PENDING REVIEW</span>';
        } else {
            verifBadge = '<span class="px-2 py-0.5 bg-slate-800 text-slate-400 border border-slate-700/60 rounded-full text-[10px] font-bold">BELUM VERIFIKASI</span>';
        }

        const profilePic = u.foto_profil ? resolveAssetPath(u.foto_profil) : 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=60';
        
        tbody.innerHTML += `
            <tr class="hover:bg-slate-800/10">
                <td class="py-3 px-4">
                    <img src="${profilePic}" class="w-8 h-8 rounded-full object-cover border border-slate-700/50">
                </td>
                <td class="py-3 px-4">
                    <div class="font-bold text-white">${u.nama}</div>
                    <div class="text-[10px] text-slate-500">${u.email}</div>
                </td>
                <td class="py-3 px-4 text-slate-300 font-mono text-xs">${u.nik || '-'}</td>
                <td class="py-3 px-4 text-slate-400 max-w-[200px] truncate" title="${u.alamat_utama || ''}">${u.alamat_utama || '-'}</td>
                <td class="py-3 px-4 text-center">${verifBadge}</td>
                <td class="py-3 px-4 text-center">
                    <button onclick="viewIdentityDocument(${u.id})" class="mx-auto px-2.5 py-1 bg-slate-900/60 hover:bg-slate-800 border border-slate-750 rounded-lg text-[10px] font-bold text-slate-300 hover:text-white transition flex items-center justify-center gap-1">
                        <span class="material-symbols-outlined text-[12px]">badge</span>
                        <span>Lihat Dokumen</span>
                    </button>
                </td>
                <td class="py-3 px-4">
                    <div class="flex items-center justify-center gap-1.5">
                        ${vStatus !== 'VERIFIED' ? `
                            <button onclick="verifyCustomerAccount(${u.id}, 'VERIFIED')" class="px-2 py-1 bg-emerald-950/40 hover:bg-emerald-900/60 text-emerald-400 border border-emerald-800/30 rounded-lg text-[10px] font-bold transition flex items-center gap-0.5">
                                <span class="material-symbols-outlined text-xs">check</span>
                                <span>Setuju</span>
                            </button>
                        ` : ''}
                        ${vStatus !== 'UNVERIFIED' ? `
                            <button onclick="verifyCustomerAccount(${u.id}, 'UNVERIFIED')" class="px-2 py-1 bg-rose-950/40 hover:bg-rose-900/60 text-rose-400 border border-rose-800/30 rounded-lg text-[10px] font-bold transition flex items-center gap-0.5">
                                <span class="material-symbols-outlined text-xs">close</span>
                                <span>Tolak</span>
                            </button>
                        ` : ''}
                    </div>
                </td>
            </tr>
        `;
    });
}

function viewIdentityDocument(userId) {
    const u = state.users.find(x => x.id == userId);
    if (!u) return;

    let modal = document.getElementById('identity-preview-modal');
    if (modal) modal.remove();

    modal = document.createElement('div');
    modal.id = 'identity-preview-modal';
    modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/85 backdrop-blur-sm p-4';

    const profilePic = u.foto_profil ? resolveAssetPath(u.foto_profil) : 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=150';
    const selfiePic = u.foto_profil ? resolveAssetPath(u.foto_profil) : 'https://images.unsplash.com/photo-1540569014015-19a7be504e3a?w=400';

    modal.innerHTML = `
        <div class="w-full max-w-2xl bg-brandSurface border border-slate-800 rounded-3xl p-6 shadow-2xl relative overflow-hidden flex flex-col gap-5">
            <div class="absolute top-0 left-0 right-0 h-[3px] bg-gradient-to-r from-primary to-secondary"></div>
            
            <div class="flex justify-between items-center">
                <h3 class="font-heading text-base font-extrabold text-white flex items-center gap-1.5">
                    <span class="material-symbols-outlined text-primary text-lg">verified_user</span>
                    <span>Verifikasi Identitas Anggota</span>
                </h3>
                <button onclick="document.getElementById('identity-preview-modal').remove()" class="text-slate-400 hover:text-white transition">
                    <span class="material-symbols-outlined text-lg">close</span>
                </button>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-5 items-start">
                
                <div class="bg-slate-900/60 border border-slate-850 p-5 rounded-2xl flex flex-col gap-3.5 text-xs text-slate-300">
                    <div class="flex items-center gap-3">
                        <img src="${profilePic}" class="w-12 h-12 rounded-full object-cover border border-slate-700/50">
                        <div>
                            <h4 class="font-bold text-white text-sm">${u.nama}</h4>
                            <p class="text-[10px] text-slate-500">${u.email}</p>
                        </div>
                    </div>
                    
                    <div class="border-t border-slate-800 pt-3 flex flex-col gap-1.5">
                        <div>
                            <span class="text-[9px] text-slate-500 font-bold uppercase tracking-wider">NIK (No. KTP)</span>
                            <div class="text-white font-mono font-bold text-sm tracking-wider mt-0.5">${u.nik || 'Tidak diisi'}</div>
                        </div>
                        <div class="mt-1">
                            <span class="text-[9px] text-slate-500 font-bold uppercase tracking-wider">Alamat Pengiriman Utama</span>
                            <div class="text-slate-300 mt-0.5 leading-relaxed">${u.alamat_utama || 'Tidak diisi'}</div>
                        </div>
                        <div class="mt-1">
                            <span class="text-[9px] text-slate-500 font-bold uppercase tracking-wider">Informasi Bank</span>
                            <div class="text-slate-300 mt-0.5 font-bold flex items-center gap-1">
                                <span class="material-symbols-outlined text-sm text-slate-400">account_balance</span>
                                <span>${u.bank_name || '-'} (No: ${u.no_rekening || '-'})</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="flex flex-col gap-2">
                    <span class="text-[9px] text-slate-500 font-bold uppercase tracking-wider">Dokumen KTP / Selfie Pemilik</span>
                    <div class="w-full h-44 rounded-2xl overflow-hidden bg-slate-900 border border-slate-800 flex items-center justify-center relative group">
                        <img src="${selfiePic}" class="w-full h-full object-cover">
                        <div class="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 flex items-center justify-center transition cursor-pointer text-white text-[10px] font-bold" onclick="window.open('${selfiePic}', '_blank')">
                            <span class="material-symbols-outlined text-base mr-1">open_in_new</span>
                            <span>Perbesar Gambar</span>
                        </div>
                    </div>
                </div>

            </div>

            <div class="flex justify-end gap-3 mt-1.5">
                <button onclick="document.getElementById('identity-preview-modal').remove()" class="bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white font-bold text-xs uppercase tracking-wider px-5 py-2.5 rounded-xl transition">
                    Tutup
                </button>
                ${u.verification_status !== 'VERIFIED' ? `
                    <button onclick="document.getElementById('identity-preview-modal').remove(); verifyCustomerAccount(${u.id}, 'VERIFIED')" class="bg-emerald-900 hover:bg-emerald-850 text-emerald-400 border border-emerald-800/40 font-bold text-xs uppercase tracking-wider px-5 py-2.5 rounded-xl transition flex items-center gap-1 shadow-lg shadow-emerald-950/20">
                        <span class="material-symbols-outlined text-sm font-bold">check</span>
                        <span>Setujui Verifikasi</span>
                    </button>
                ` : `
                    <button onclick="document.getElementById('identity-preview-modal').remove(); verifyCustomerAccount(${u.id}, 'UNVERIFIED')" class="bg-rose-900 hover:bg-rose-850 text-rose-400 border border-rose-800/40 font-bold text-xs uppercase tracking-wider px-5 py-2.5 rounded-xl transition flex items-center gap-1 shadow-lg shadow-rose-950/20">
                        <span class="material-symbols-outlined text-sm font-bold">close</span>
                        <span>Batalkan Verifikasi</span>
                    </button>
                `}
            </div>
        </div>
    `;

    document.body.appendChild(modal);
}

async function verifyCustomerAccount(userId, newStatus) {
    try {
        const response = await fetch(`/api/users/${userId}/verify`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `verification_status=${newStatus}`
        });

        const res = await response.json();
        if (response.ok) {
            showMarketToast('Status verifikasi anggota berhasil diperbarui!');
            logConsole(`Status verifikasi user ID ${userId} diperbarui menjadi ${newStatus}.`);
        } else {
            showMarketToast(res.message || 'Gagal mengubah status verifikasi.', 'error');
        }
    } catch (e) {
        logConsole('Koneksi API terganggu. Mengubah verifikasi secara lokal (simulasi).', 'warning');
        showMarketToast('Status verifikasi disimpan secara lokal (Simulasi)!');
    }

    const user = state.users.find(u => u.id == userId);
    if (user) {
        user.verification_status = newStatus;
    }
    
    renderSuperUsersVerifTable();
    if (state.customerSession && state.customerSession.id == userId) {
        state.customerSession.verification_status = newStatus;
        const container = document.getElementById('market-content-area');
        if (state.marketView === 'profile' && container) {
            renderMarketProfile(container);
        }
    }
}

window.renderSuperUsersVerifTable = renderSuperUsersVerifTable;
window.viewIdentityDocument = viewIdentityDocument;
window.verifyCustomerAccount = verifyCustomerAccount;


/* ============================================================
 * SELLER - PRODUCT CRUD (Edit & Delete)
 * ============================================================ */

window.openEditProductModal = function(productId) {
    const p = state.products.find(x => x.id == productId);
    if (!p) return;
    document.getElementById('edit-prod-id').value    = p.id;
    document.getElementById('edit-prod-name').value  = p.nama_produk;
    document.getElementById('edit-prod-price').value = p.harga;
    document.getElementById('edit-prod-satuan').value = p.satuan || 'unit';
    document.getElementById('edit-prod-stock').value = p.stok;
    document.getElementById('edit-prod-cat').value   = p.kategori_id;
    document.getElementById('edit-prod-foto').value  = p.foto || '';
    document.getElementById('edit-prod-tags').value  = p.tags || '';
    document.getElementById('edit-prod-status').value = p.status || 'aktif';
    document.getElementById('edit-prod-desc').value  = p.deskripsi || '';

    // Reset preview
    const previewContainer = document.getElementById('edit-prod-preview');
    if (previewContainer) previewContainer.classList.add('hidden');

    const modal = document.getElementById('edit-product-modal');
    modal.classList.remove('hidden');
    modal.classList.add('flex');
};

window.closeEditProductModal = function() {
    const modal = document.getElementById('edit-product-modal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
};

window.saveEditProduct = async function() {
    const id     = document.getElementById('edit-prod-id').value;
    const name   = document.getElementById('edit-prod-name').value;
    const price  = document.getElementById('edit-prod-price').value;
    const satuan = document.getElementById('edit-prod-satuan').value;
    const stock  = document.getElementById('edit-prod-stock').value;
    const cat    = document.getElementById('edit-prod-cat').value;
    const foto   = document.getElementById('edit-prod-foto').value;
    const tags   = document.getElementById('edit-prod-tags').value;
    const status = document.getElementById('edit-prod-status').value;
    const desc   = document.getElementById('edit-prod-desc').value;

    try {
        const res = await fetch(`/api/products/${id}/update`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `name=${encodeURIComponent(name)}&price=${price}&satuan=${encodeURIComponent(satuan)}&stock=${stock}&category_id=${cat}&image=${encodeURIComponent(foto)}&tags=${encodeURIComponent(tags)}&status=${status}&description=${encodeURIComponent(desc)}`
        });
        
        const data = await res.json();
        if (data.status !== 'success') {
            alert('Gagal menyimpan produk: ' + (data.message || 'Error tidak diketahui'));
            return;
        }
    } catch(e) {
        alert('Terjadi kesalahan jaringan saat menyimpan produk.');
        return;
    }

    // Update local state
    const p = state.products.find(x => x.id == id);
    if (p) {
        p.nama_produk = name;
        p.harga       = parseFloat(price);
        p.satuan      = satuan;
        p.stok        = parseInt(stock);
        p.kategori_id = parseInt(cat);
        p.foto        = foto;
        p.tags        = tags;
        p.status      = status;
        p.deskripsi   = desc;
    }

    closeEditProductModal();
    renderCoopProductsDaftar();
    logConsole(`Produk "${name}" berhasil diperbarui.`);
};

window.deleteCoopProduct = async function(productId, productName) {
    if (!confirm(`Hapus produk "${productName}" dari katalog? Tindakan ini tidak dapat dibatalkan.`)) return;
    try {
        await fetch(`/api/products/${productId}/delete`, { method: 'POST' });
    } catch(e) {}

    // Remove from local state
    state.products = state.products.filter(p => p.id != productId);
    renderCoopProductsDaftar();
    logConsole(`Produk "${productName}" berhasil dihapus dari katalog.`);
};

window.switchTab = function(tab) {
    state.activeTab = tab;
    renderWorkspace();
};


/* ============================================================
 * SELLER INBOX - PESAN MASUK (Messaging System)
 * ============================================================ */

async function renderSellerInbox() {
    await loadSellerMessages();
    renderMessageThreadList(state.messages);
    checkUnreadBadge();
}

async function loadSellerMessages() {
    try {
        const res = await fetch(`/api/messages?koperasi_id=${state.coopId}`);
        const data = await res.json();
        if (data.status === 'success') {
            state.messages = data.data;
        }
    } catch(e) {
        // Use local state if API unavailable
    }
}

function renderMessageThreadList(threads) {
    const container = document.getElementById('msg-thread-list');
    if (!container) return;

    if (!threads || !threads.length) {
        container.innerHTML = `
            <div class="flex flex-col items-center justify-center py-14 text-center px-4">
                <span class="material-symbols-outlined text-4xl text-slate-600 mb-3">forum</span>
                <p class="text-slate-500 text-xs font-semibold">Belum ada pesan masuk</p>
                <p class="text-slate-600 text-[10px] mt-1">Pesan dari pembeli terkait produk Anda akan tampil di sini</p>
            </div>`;
        return;
    }

    container.innerHTML = threads.map(t => {
        const unread = t.unread_count > 0
            ? `<span class="bg-rose-500 text-white text-[9px] font-extrabold px-1.5 py-0.5 rounded-full">${t.unread_count}</span>`
            : '';
        const lastMsg = t.last_message ? t.last_message.substring(0, 50) + (t.last_message.length > 50 ? '...' : '') : '';
        const timeStr = t.last_time ? new Date(t.last_time).toLocaleString('id-ID', {hour:'2-digit', minute:'2-digit', day:'numeric', month:'short'}) : '';
        const isActive = state.activeMessageThread && state.activeMessageThread.product_id == t.product_id ? 'bg-primary/10 border-l-2 border-primary' : '';
        return `
            <div onclick="openMessageThread(${t.product_id}, '${(t.product_name||'Produk').replace(/'/g, "\\'")}')" 
                 class="flex items-center gap-3 px-4 py-3.5 cursor-pointer hover:bg-slate-700/30 transition ${isActive}">
                <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-primary/30 to-secondary/30 flex items-center justify-center shrink-0">
                    <span class="material-symbols-outlined text-primary text-base">inventory_2</span>
                </div>
                <div class="flex-1 min-w-0">
                    <div class="flex items-center justify-between gap-2">
                        <span class="text-xs font-bold text-white truncate">${t.product_name || 'Produk'}</span>
                        ${unread}
                    </div>
                    <div class="text-slate-500 text-[10px] truncate">${lastMsg}</div>
                    <div class="text-slate-600 text-[10px] mt-0.5">${timeStr}</div>
                </div>
            </div>`;
    }).join('');
}

window.openMessageThread = async function(productId, productName) {
    state.activeMessageThread = { product_id: productId, product_name: productName };

    // Highlight selected thread
    renderMessageThreadList(state.messages);

    // Update header
    const prodEl  = document.getElementById('msg-conv-product');
    const buyerEl = document.getElementById('msg-conv-buyer');
    const statusEl = document.getElementById('msg-conv-status');
    const inputArea = document.getElementById('seller-msg-input-area');

    if (prodEl) prodEl.textContent = `Produk: ${productName}`;
    if (buyerEl) {
        const thread = state.messages.find(t => t.product_id == productId);
        const msgCount = thread ? thread.messages.length : 0;
        buyerEl.textContent = `${msgCount} pesan dalam diskusi ini`;
    }
    if (statusEl) statusEl.classList.remove('hidden');
    if (inputArea) inputArea.classList.remove('hidden');

    // Fetch thread messages
    const container = document.getElementById('seller-msg-container');
    if (container) container.innerHTML = `<div class="text-center py-6 text-slate-500 text-xs">Memuat pesan...</div>`;

    try {
        const res = await fetch(`/api/messages/thread?product_id=${productId}&koperasi_id=${state.coopId}`);
        const data = await res.json();
        if (data.status === 'success') {
            renderConversation(data.data);
            // Update unread count in local state
            const thread = state.messages.find(t => t.product_id == productId);
            if (thread) thread.unread_count = 0;
            checkUnreadBadge();
            renderMessageThreadList(state.messages);
        }
    } catch(e) {
        // Fallback: show local messages if any
        const thread = state.messages.find(t => t.product_id == productId);
        if (thread && thread.messages) {
            renderConversation(thread.messages);
        }
    }
};

function renderConversation(messages) {
    const container = document.getElementById('seller-msg-container');
    if (!container) return;
    if (!messages || !messages.length) {
        container.innerHTML = `
            <div class="flex flex-col items-center justify-center py-10 text-center">
                <span class="material-symbols-outlined text-3xl text-slate-600 mb-2">chat_bubble</span>
                <p class="text-slate-600 text-xs">Belum ada pesan dalam diskusi ini.</p>
            </div>`;
        return;
    }
    container.innerHTML = messages.map(msg => {
        const isSeller = msg.sender_role === 'seller';
        const alignClass = isSeller ? 'items-end' : 'items-start';
        const bubbleClass = isSeller
            ? 'bg-gradient-to-r from-primary to-secondary text-white rounded-bl-xl rounded-tl-xl rounded-tr-xl'
            : 'bg-slate-700/60 text-slate-200 rounded-br-xl rounded-tr-xl rounded-tl-xl';
        const timeStr = msg.created_at ? new Date(msg.created_at).toLocaleString('id-ID', {hour:'2-digit', minute:'2-digit', day:'numeric', month:'short'}) : '';
        return `
            <div class="flex flex-col ${alignClass} gap-0.5">
                <div class="text-[10px] text-slate-500 px-1">${isSeller ? 'Anda (Koperasi)' : msg.sender_name || 'Pembeli'}</div>
                <div class="px-3 py-2 max-w-[80%] text-xs leading-relaxed ${bubbleClass}">${msg.message}</div>
                <div class="text-[9px] text-slate-600 px-1">${timeStr}</div>
            </div>`;
    }).join('');
    container.scrollTop = container.scrollHeight;
}

window.sendSellerReply = async function() {
    const input = document.getElementById('seller-reply-input');
    if (!input || !input.value.trim()) return;
    if (!state.activeMessageThread) return;

    const message = input.value.trim();
    const coop = state.cooperatives.find(c => c.id == state.coopId);
    const senderName = coop ? coop.nama_koperasi : 'Koperasi';

    // Optimistic UI
    const localMsg = {
        product_id:   state.activeMessageThread.product_id,
        koperasi_id:  state.coopId,
        sender_role:  'seller',
        sender_name:  senderName,
        message:      message,
        product_name: state.activeMessageThread.product_name,
        created_at:   new Date().toISOString()
    };

    // Append to current thread
    const thread = state.messages.find(t => t.product_id == state.activeMessageThread.product_id);
    if (thread) {
        if (!thread.messages) thread.messages = [];
        thread.messages.push(localMsg);
        thread.last_message = message;
        thread.last_time = localMsg.created_at;
    }

    renderConversation(thread ? thread.messages : [localMsg]);
    input.value = '';

    // Send to API
    try {
        await fetch('/api/messages', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `product_id=${state.activeMessageThread.product_id}&koperasi_id=${state.coopId}&sender_id=${state.coopAdminId}&sender_name=${encodeURIComponent(senderName)}&sender_role=seller&message=${encodeURIComponent(message)}&product_name=${encodeURIComponent(state.activeMessageThread.product_name)}`
        });
    } catch(e) {}
};

window.handleSellerMsgKeyup = function(e) {
    if (e.key === 'Enter') sendSellerReply();
};

window.filterMessageThreads = function() {
    const q = (document.getElementById('msg-search') || {value: ''}).value.toLowerCase();
    const filtered = q ? state.messages.filter(t => (t.product_name || '').toLowerCase().includes(q)) : state.messages;
    renderMessageThreadList(filtered);
};

async function checkUnreadBadge() {
    if (!state.coopId) return;
    try {
        const res = await fetch(`/api/messages/unread-count?koperasi_id=${state.coopId}`);
        const data = await res.json();
        const badge = document.getElementById('seller-unread-badge');
        if (badge) {
            if (data.count > 0) {
                badge.textContent = data.count;
                badge.classList.remove('hidden');
            } else {
                badge.classList.add('hidden');
            }
        }
    } catch(e) {
        // Compute from local state
        const totalUnread = state.messages.reduce((s, t) => s + (t.unread_count || 0), 0);
        const badge = document.getElementById('seller-unread-badge');
        if (badge) {
            if (totalUnread > 0) {
                badge.textContent = totalUnread;
                badge.classList.remove('hidden');
            } else {
                badge.classList.add('hidden');
            }
        }
    }
}

async function checkCustomerUnreadBadge() {
    if (!state.customerSession) return;
    try {
        const res = await fetch(`/api/messages/customer-unread-count?customer_id=${state.customerSession.id}`);
        const data = await res.json();
        const badge = document.getElementById('market-msg-badge');
        if (badge) {
            if (data.count > 0) {
                badge.textContent = data.count;
                badge.classList.remove('hidden');
            } else {
                badge.classList.add('hidden');
            }
        }
    } catch(e) {}
}

// Also check unread badge when coop admin logs in
const _origRenderWorkspace = typeof renderWorkspace === 'function' ? renderWorkspace : null;
// Poll unread every 60 seconds
setInterval(() => {
    if (state.activeRole === 'coopadmin' && state.coopId) {
        checkUnreadBadge();
    }
    if (state.customerSession) {
        checkCustomerUnreadBadge();
    }
}, 60000);

async function renderMarketMessages(container) {
    if (!state.customerSession) {
        container.innerHTML = `
            <div class="max-w-md mx-auto text-center py-16 px-4 bg-slate-800/10 border border-slate-800/80 rounded-3xl shadow-xl flex flex-col items-center gap-5">
                <div class="w-16 h-16 rounded-2xl bg-slate-900/60 flex items-center justify-center text-slate-600 border border-slate-800">
                    <span class="material-symbols-outlined text-3xl">lock</span>
                </div>
                <div>
                    <h3 class="font-heading text-lg font-bold text-white">Silakan Login</h3>
                    <p class="text-slate-400 text-xs mt-1 max-w-xs mx-auto">Anda harus masuk ke akun Anda untuk melihat pesan.</p>
                </div>
                <button onclick="openWebLoginModal()" class="bg-gradient-to-r from-primary to-secondary hover:from-primary/95 hover:to-secondary/95 text-white font-bold text-xs uppercase tracking-wider px-5 py-3 rounded-xl shadow-lg transition flex items-center justify-center gap-1.5">
                    <span class="material-symbols-outlined text-sm font-bold">login</span>
                    <span>Masuk / Daftar</span>
                </button>
            </div>
        `;
        return;
    }

    container.innerHTML = `<div class="text-center py-10 text-slate-400 text-xs">Memuat pesan Anda...</div>`;
    
    try {
        const res = await fetch(`/api/messages/customer?customer_id=${state.customerSession.id}`);
        const data = await res.json();
        
        // unreadByKey will store unread_count per chatKey for rendering
        state._customerUnreadByKey = {};

        if (data.status === 'success') {
            Object.keys(data.data).forEach(pid => {
                const thread = data.data[pid];
                const msgs = thread.messages || thread; // backwards compat
                if (msgs.length > 0) {
                    const coopId = msgs[0].koperasi_id;
                    const chatKey = `${coopId}-${pid}`;
                    productChatHistories[chatKey] = msgs.map(m => ({
                        sender: m.sender_role === 'customer' ? (state.customerSession && m.sender_id == state.customerSession.id ? 'user' : 'other') : 'seller',
                        text: m.message,
                        time: new Date(m.created_at).toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }),
                        senderName: m.sender_name
                    }));
                    state._customerUnreadByKey[chatKey] = thread.unread_count || 0;
                }
            });
        }
    } catch(e) {}

    if (Object.keys(productChatHistories).length === 0) {
        container.innerHTML = `
            <div class="max-w-md mx-auto text-center py-16 px-4 bg-slate-800/10 border border-slate-800/80 rounded-3xl shadow-xl flex flex-col items-center gap-5">
                <div class="w-16 h-16 rounded-2xl bg-slate-900/60 flex items-center justify-center text-slate-600 border border-slate-800">
                    <span class="material-symbols-outlined text-3xl">chat_bubble_outline</span>
                </div>
                <div>
                    <h3 class="font-heading text-lg font-bold text-white">Belum Ada Pesan</h3>
                    <p class="text-slate-400 text-xs mt-1 max-w-xs mx-auto">Anda belum pernah memulai diskusi produk dengan penjual mana pun.</p>
                </div>
                <button onclick="goToMarketView('home')" class="bg-gradient-to-r from-primary to-secondary hover:from-primary/95 hover:to-secondary/95 text-white font-bold text-xs uppercase tracking-wider px-5 py-3 rounded-xl shadow-lg transition flex items-center justify-center gap-1.5">
                    <span class="material-symbols-outlined text-sm font-bold">shopping_bag</span>
                    <span>Mulai Belanja</span>
                </button>
            </div>
        `;
        return;
    }

    let listHtml = '';
    let totalUnread = 0;
    Object.keys(productChatHistories).forEach(key => {
        const parts = key.split('-');
        const coopId = parts[0];
        const productId = parts[1];
        const coop = state.cooperatives.find(c => c.id == coopId);
        const prod = state.products.find(p => p.id == productId);
        const messages = productChatHistories[key];
        const lastMsg = messages[messages.length - 1];
        const unreadCount = (state._customerUnreadByKey && state._customerUnreadByKey[key]) || 0;
        totalUnread += unreadCount;
        
        if (!prod || !coop) return;

        let formattedText = lastMsg.text.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>');
        const hasUnread = unreadCount > 0;

        listHtml += `
            <div onclick="openProductChatModal(${coopId}, ${productId})" class="bg-slate-800/20 border ${hasUnread ? 'border-primary/50 shadow-primary/10' : 'border-slate-700/30'} rounded-2xl p-5 shadow-xl flex items-center gap-4 cursor-pointer hover:bg-slate-800/40 hover:border-primary/40 transition relative">
                <img src="${coop.logo}" class="w-12 h-12 rounded-xl object-cover border border-slate-700 shadow-sm shrink-0">
                <div class="flex-1 min-w-0 flex flex-col gap-1">
                    <div class="flex justify-between items-center">
                        <div class="flex items-center gap-1.5">
                            <h4 class="font-heading text-sm font-bold ${hasUnread ? 'text-white' : 'text-slate-300'} truncate">${coop.nama_koperasi}</h4>
                            ${coop.status === 'aktif' ? '<span class="w-1.5 h-1.5 rounded-full bg-emerald-500 inline-block shrink-0" title="Online"></span>' : ''}
                        </div>
                        <div class="flex items-center gap-2">
                            <span class="text-[9px] text-slate-500">${lastMsg.time}</span>
                            ${hasUnread ? `<span class="bg-rose-500 text-white text-[9px] font-extrabold px-1.5 py-0.5 rounded-full min-w-[18px] text-center">${unreadCount}</span>` : ''}
                        </div>
                    </div>
                    <p class="text-[10px] bg-primary/20 text-primary px-2 py-0.5 rounded-full font-bold self-start truncate max-w-full">Tanya: ${prod.nama_produk}</p>
                    <p class="text-xs ${hasUnread ? 'text-white font-semibold' : 'text-slate-300'} truncate mt-1"><span class="text-slate-500">${lastMsg.sender === 'user' ? 'Anda: ' : '<span class="text-emerald-400">Seller: </span>'}</span>${formattedText}</p>
                </div>
            </div>
        `;
    });

    // Update the top badge with accurate total
    const topBadge = document.getElementById('market-msg-badge');
    if (topBadge) {
        if (totalUnread > 0) {
            topBadge.textContent = totalUnread;
            topBadge.classList.remove('hidden');
        } else {
            topBadge.classList.add('hidden');
        }
    }

    container.innerHTML = `
        <div class="flex flex-col gap-6 max-w-4xl mx-auto w-full">
            <div class="flex justify-between items-center border-b border-slate-800/60 pb-4">
                <h3 class="font-heading text-lg font-bold text-white flex items-center gap-2">
                    <span class="material-symbols-outlined text-primary">chat</span>
                    <span>Pesan Anda</span>
                </h3>
                <button onclick="goToMarketView('home')" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white rounded-xl text-xs font-bold transition flex items-center gap-1.5">
                    <span class="material-symbols-outlined text-sm">arrow_back</span>
                    <span>Lanjut Belanja</span>
                </button>
            </div>
            <div class="flex flex-col gap-4">
                ${listHtml}
            </div>
        </div>
    `;
}

// ----------------------------------------------------
// PRODUCT REVIEWS & RATINGS
// ----------------------------------------------------

window.openReviewModal = async function(orderId, koperasiId) {
    try {
        const res = await fetch(`/api/orders/${orderId}`);
        const data = await res.json();
        if (data.status !== 'success') {
            alert('Gagal mengambil data pesanan.');
            return;
        }

        const items = data.items;
        
        let modalHtml = `
        <div id="market-review-modal" class="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm p-4">
            <div class="w-full max-w-2xl bg-brandSurface border border-slate-800 rounded-3xl p-6 shadow-2xl relative overflow-hidden flex flex-col gap-5 max-h-[90vh]">
                <div class="absolute top-0 left-0 right-0 h-[3px] bg-gradient-to-r from-amber-500 to-orange-500"></div>
                
                <div class="flex justify-between items-center shrink-0">
                    <h3 class="font-heading text-lg font-bold text-white flex items-center gap-2">
                        <span class="material-symbols-outlined text-amber-500">reviews</span>
                        Beri Ulasan Produk
                    </h3>
                    <button onclick="document.getElementById('market-review-modal').remove()" class="text-slate-400 hover:text-white transition">
                        <span class="material-symbols-outlined">close</span>
                    </button>
                </div>

                <div class="overflow-y-auto flex flex-col gap-4 pr-2">
                    ${items.map(item => `
                        <div class="bg-slate-900/60 border border-slate-800 rounded-2xl p-4 flex flex-col gap-4">
                            <div class="flex items-center gap-3">
                                <img src="${item.product_image || 'https://via.placeholder.com/150'}" class="w-12 h-12 rounded-xl object-cover border border-slate-700/50">
                                <div class="flex-1">
                                    <h4 class="font-bold text-white text-sm">${item.product_name}</h4>
                                    <p class="text-xs text-slate-400">${item.qty} x Rp ${Number(item.harga).toLocaleString('id-ID')}</p>
                                </div>
                            </div>
                            
                            ${item.is_reviewed == 1 ? `
                                <div class="bg-emerald-950/30 border border-emerald-900/50 rounded-xl p-3 flex items-center gap-2 text-emerald-400 text-xs font-bold justify-center">
                                    <span class="material-symbols-outlined text-sm">check_circle</span>
                                    <span>Ulasan Sudah Terkirim</span>
                                </div>
                            ` : `
                                <form onsubmit="event.preventDefault(); submitProductReview(this, ${orderId}, ${item.product_id}, ${koperasiId});" class="flex flex-col gap-3">
                                    <div class="flex justify-center gap-2 py-2" id="star-rating-${item.id}">
                                        ${[1, 2, 3, 4, 5].map(star => `
                                            <span class="material-symbols-outlined text-3xl cursor-pointer text-slate-700 hover:text-amber-400 transition" onclick="setRating(${item.id}, ${star})" id="star-${item.id}-${star}">star</span>
                                        `).join('')}
                                        <input type="hidden" name="rating" id="input-rating-${item.id}" value="0" required min="1">
                                    </div>
                                    <textarea name="review" rows="2" placeholder="Bagaimana kualitas produk ini?" class="w-full bg-slate-950 border border-slate-800 rounded-xl p-3 text-white text-xs focus:outline-none focus:border-amber-500/50"></textarea>
                                    <button type="submit" class="w-full py-2 bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-400 hover:to-orange-400 text-white rounded-xl text-xs font-bold shadow-lg transition">Kirim Ulasan</button>
                                </form>
                            `}
                        </div>
                    `).join('')}
                </div>
            </div>
        </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
    } catch (e) {
        alert('Terjadi kesalahan saat memuat data pesanan.');
    }
};

window.setRating = function(itemId, rating) {
    document.getElementById(`input-rating-${itemId}`).value = rating;
    for (let i = 1; i <= 5; i++) {
        const star = document.getElementById(`star-${itemId}-${i}`);
        if (i <= rating) {
            star.classList.remove('text-slate-700');
            star.classList.add('text-amber-400');
            star.classList.add('fill-current'); // Assuming material icons outline supports this or we just color it
            // Let's use solid star if possible. For Material Symbols Outlined, setting font-variation-settings inside style works:
            star.style.fontVariationSettings = "'FILL' 1";
        } else {
            star.classList.add('text-slate-700');
            star.classList.remove('text-amber-400');
            star.style.fontVariationSettings = "'FILL' 0";
        }
    }
};

window.submitProductReview = async function(formElem, orderId, productId, koperasiId) {
    const rating = formElem.querySelector('input[name="rating"]').value;
    const review = formElem.querySelector('textarea[name="review"]').value;
    
    if (rating == 0) {
        alert('Silakan pilih rating bintang terlebih dahulu.');
        return;
    }

    const customerId = state.customerSession.id;
    const btn = formElem.querySelector('button[type="submit"]');
    btn.disabled = true;
    btn.innerHTML = 'Mengirim...';

    try {
        const formData = new URLSearchParams();
        formData.append('order_id', orderId);
        formData.append('product_id', productId);
        formData.append('customer_id', customerId);
        formData.append('koperasi_id', koperasiId);
        formData.append('rating', rating);
        formData.append('review', review);

        const res = await fetch('/api/reviews', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: formData
        });
        
        const data = await res.json();
        
        if (data.status === 'success') {
            formElem.outerHTML = `
                <div class="bg-emerald-950/30 border border-emerald-900/50 rounded-xl p-3 flex items-center gap-2 text-emerald-400 text-xs font-bold justify-center">
                    <span class="material-symbols-outlined text-sm">check_circle</span>
                    <span>Ulasan Berhasil Dikirim</span>
                </div>
            `;
            // Note: In a real app we might update the local products state here to reflect new rating
        } else {
            alert(data.message || 'Gagal mengirim ulasan');
            btn.disabled = false;
            btn.innerHTML = 'Kirim Ulasan';
        }
    } catch(e) {
        alert('Terjadi kesalahan jaringan.');
        btn.disabled = false;
        btn.innerHTML = 'Kirim Ulasan';
    }
};

window.showProductReviews = async function(productId) {
    try {
        const res = await fetch(`/api/products/${productId}/reviews`);
        const data = await res.json();
        
        if (data.status !== 'success') {
            alert('Gagal memuat ulasan produk.');
            return;
        }

        const reviews = data.data || [];
        
        let modalHtml = `
        <div id="market-view-reviews-modal" class="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm p-4">
            <div class="w-full max-w-2xl bg-brandSurface border border-slate-800 rounded-3xl p-6 shadow-2xl relative overflow-hidden flex flex-col gap-5 max-h-[90vh]">
                <div class="absolute top-0 left-0 right-0 h-[3px] bg-gradient-to-r from-amber-400 to-orange-500"></div>
                
                <div class="flex justify-between items-center shrink-0 border-b border-slate-800/80 pb-4">
                    <h3 class="font-heading text-lg font-bold text-white flex items-center gap-2">
                        <span class="material-symbols-outlined text-amber-400">star_rate</span>
                        Ulasan Pengguna
                    </h3>
                    <button onclick="document.getElementById('market-view-reviews-modal').remove()" class="text-slate-400 hover:text-white transition">
                        <span class="material-symbols-outlined">close</span>
                    </button>
                </div>

                <div class="overflow-y-auto flex flex-col gap-4 pr-2">
                    ${reviews.length === 0 ? `
                        <div class="text-center py-10">
                            <span class="material-symbols-outlined text-slate-600 text-5xl mb-3">speaker_notes_off</span>
                            <p class="text-slate-400 font-medium">Belum ada ulasan untuk produk ini.</p>
                        </div>
                    ` : reviews.map(r => `
                        <div class="bg-slate-900/60 border border-slate-800/80 rounded-2xl p-5 flex flex-col gap-3">
                            <div class="flex justify-between items-start">
                                <div class="flex items-center gap-3">
                                    <div class="w-10 h-10 rounded-full bg-slate-800 flex items-center justify-center text-slate-300 font-bold uppercase shrink-0 border border-slate-700">
                                        ${r.customer_name ? r.customer_name.substring(0, 2) : 'AN'}
                                    </div>
                                    <div class="flex flex-col">
                                        <span class="text-sm font-bold text-white">${r.customer_name || 'Anonim'}</span>
                                        <span class="text-[10px] text-slate-500">${r.created_at ? r.created_at.substring(0, 10) : ''}</span>
                                    </div>
                                </div>
                                <div class="flex gap-0.5 text-amber-400">
                                    ${[1,2,3,4,5].map(star => `
                                        <span class="material-symbols-outlined text-sm ${star <= r.rating ? 'fill-current' : 'text-slate-700'}" style="font-variation-settings: 'FILL' ${star <= r.rating ? '1' : '0'}">star</span>
                                    `).join('')}
                                </div>
                            </div>
                            ${r.review ? `<p class="text-slate-300 text-sm mt-2 leading-relaxed italic bg-slate-950/50 p-3 rounded-xl border border-slate-800/40">"${r.review}"</p>` : ''}
                        </div>
                    `).join('')}
                </div>
            </div>
        </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
    } catch (e) {
        alert('Terjadi kesalahan jaringan.');
    }
};

window.clearAuditLogs = async function() {
    if (!confirm('Apakah Anda yakin ingin menghapus seluruh riwayat audit log? Tindakan ini tidak dapat dibatalkan.')) return;
    
    try {
        const res = await fetch('/api/audit-logs/clear', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({ user_id: state.adminSession ? state.adminSession.id : '' })
        });
        
        const data = await res.json();
        if (data.status === 'success') {
            alert(data.message);
            // Refresh logs
            document.querySelector('[data-tab="super-audit"]').click();
        } else {
            alert('Gagal membersihkan log: ' + data.message);
        }
    } catch (e) {
        alert('Error: ' + e.message);
    }
};

/* ----------------------------------------------------
 * SYSTEM SETTINGS (SMTP & GLOBAL)
 * ---------------------------------------------------- */
window.loadSystemSettings = async function() {
    if (!state.adminSession || state.adminSession.role_id != 1) return;
    try {
        const res = await fetch('/api/settings', {
            headers: { 'Authorization': `Bearer ${state.adminToken}` }
        });
        const json = await res.json();
        if (json.status === 'success' && json.data) {
            const d = json.data;
            if(document.getElementById('setting-app-name')) document.getElementById('setting-app-name').value = d.app_name || '';
            if(document.getElementById('setting-active-year')) document.getElementById('setting-active-year').value = d.active_year || '';
            if(document.getElementById('setting-smtp-host')) document.getElementById('setting-smtp-host').value = d.smtp_host || '';
            if(document.getElementById('setting-smtp-port')) document.getElementById('setting-smtp-port').value = d.smtp_port || '';
            if(document.getElementById('setting-smtp-crypto')) document.getElementById('setting-smtp-crypto').value = d.smtp_crypto || 'ssl';
            if(document.getElementById('setting-smtp-user')) document.getElementById('setting-smtp-user').value = d.smtp_user || '';
            if(document.getElementById('setting-smtp-pass')) document.getElementById('setting-smtp-pass').value = d.smtp_pass || '';
            if(document.getElementById('setting-smtp-from')) document.getElementById('setting-smtp-from').value = d.smtp_from || '';
        }
    } catch(e) {
        console.error('Failed to load system settings', e);
    }
};

window.saveSystemSettings = async function() {
    if (!state.adminSession || state.adminSession.role_id != 1) return;
    
    const payload = new URLSearchParams({
        app_name: document.getElementById('setting-app-name').value,
        active_year: document.getElementById('setting-active-year').value,
        smtp_host: document.getElementById('setting-smtp-host').value,
        smtp_port: document.getElementById('setting-smtp-port').value,
        smtp_crypto: document.getElementById('setting-smtp-crypto').value,
        smtp_user: document.getElementById('setting-smtp-user').value,
        smtp_pass: document.getElementById('setting-smtp-pass').value,
        smtp_from: document.getElementById('setting-smtp-from').value
    });

    try {
        const res = await fetch('/api/settings', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Bearer ${state.adminToken}`
            },
            body: payload
        });
        const data = await res.json();
        if (data.status === 'success') {
            alert('Pengaturan sistem berhasil disimpan.');
        } else {
            alert('Gagal menyimpan: ' + data.message);
        }
    } catch(e) {
        alert('Error: ' + e.message);
    }
};

/* ----------------------------------------------------
 * AUTH PASSWORD RESET
 * ---------------------------------------------------- */
window.openForgotPasswordModal = function() {
    document.getElementById('forgot-password-modal').classList.remove('hidden');
    document.getElementById('forgot-password-modal').classList.add('flex');
};

window.closeForgotPasswordModal = function() {
    document.getElementById('forgot-password-modal').classList.add('hidden');
    document.getElementById('forgot-password-modal').classList.remove('flex');
    document.getElementById('forgot-password-alert').classList.add('hidden');
};

window.submitForgotPassword = async function() {
    const email = document.getElementById('forgot-password-email').value;
    const alertBox = document.getElementById('forgot-password-alert');
    const btn = document.getElementById('btn-submit-forgot');
    
    if(!email) {
        alertBox.innerHTML = 'Email wajib diisi.';
        alertBox.className = 'px-3 py-2 rounded-lg border bg-rose-950/40 border-rose-800 text-rose-400 text-[10px] mt-2 block';
        return;
    }
    
    btn.innerText = 'Mengirim...';
    btn.disabled = true;
    
    try {
        const res = await fetch('/api/auth/forgot-password', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({ email })
        });
        const data = await res.json();
        
        if(data.status === 'success') {
            alertBox.innerHTML = data.message;
            alertBox.className = 'px-3 py-2 rounded-lg border bg-emerald-950/40 border-emerald-800 text-emerald-400 text-[10px] mt-2 block';
        } else {
            alertBox.innerHTML = data.message;
            alertBox.className = 'px-3 py-2 rounded-lg border bg-rose-950/40 border-rose-800 text-rose-400 text-[10px] mt-2 block';
        }
    } catch(e) {
        alertBox.innerHTML = 'Gagal terhubung ke server.';
        alertBox.className = 'px-3 py-2 rounded-lg border bg-rose-950/40 border-rose-800 text-rose-400 text-[10px] mt-2 block';
    } finally {
        btn.innerText = 'Kirim Tautan Reset';
        btn.disabled = false;
    }
};

window.submitResetPassword = async function() {
    const token = document.getElementById('reset-token-val').value;
    const password = document.getElementById('new-password').value;
    const alertBox = document.getElementById('reset-password-alert');
    const btn = document.getElementById('btn-submit-reset');
    
    if(password.length < 6) {
        alertBox.innerHTML = 'Password minimal 6 karakter.';
        alertBox.className = 'px-3 py-2 rounded-lg border bg-rose-950/40 border-rose-800 text-rose-400 text-[10px] mt-2 block';
        return;
    }
    
    btn.innerText = 'Menyimpan...';
    btn.disabled = true;
    
    try {
        const res = await fetch('/api/auth/reset-password', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({ token, password })
        });
        const data = await res.json();
        
        if(data.status === 'success') {
            alertBox.innerHTML = data.message;
            alertBox.className = 'px-3 py-2 rounded-lg border bg-emerald-950/40 border-emerald-800 text-emerald-400 text-[10px] mt-2 block';
            setTimeout(() => {
                window.location.href = '/';
            }, 3000);
        } else {
            alertBox.innerHTML = data.message;
            alertBox.className = 'px-3 py-2 rounded-lg border bg-rose-950/40 border-rose-800 text-rose-400 text-[10px] mt-2 block';
            btn.innerText = 'Simpan Password Baru';
            btn.disabled = false;
        }
    } catch(e) {
        alertBox.innerHTML = 'Gagal terhubung ke server.';
        alertBox.className = 'px-3 py-2 rounded-lg border bg-rose-950/40 border-rose-800 text-rose-400 text-[10px] mt-2 block';
        btn.innerText = 'Simpan Password Baru';
        btn.disabled = false;
    }
};

// Check for reset_token on load
document.addEventListener('DOMContentLoaded', () => {
    const urlParams = new URLSearchParams(window.location.search);
    const resetToken = urlParams.get('reset_token');
    if (resetToken) {
        document.getElementById('reset-token-val').value = resetToken;
        document.getElementById('reset-password-modal').classList.remove('hidden');
        document.getElementById('reset-password-modal').classList.add('flex');
    }
});

