import { initializeApp } from "https://www.gstatic.com/firebasejs/11.9.0/firebase-app.js";
import { getDatabase, ref, get, update, push, onValue, set, serverTimestamp, runTransaction } from "https://www.gstatic.com/firebasejs/11.9.0/firebase-database.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut } from "https://www.gstatic.com/firebasejs/11.9.0/firebase-auth.js";
import { firebaseConfig } from "./firebase-config.js";

const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth(app);

// Global State
let currentStep = 1;
const totalSteps = 4;
const formData = {};
let subdomainCheckTimer;
let CURRENT_CLIENT_ID = null;
let SITE_INFO = null;
let allProducts = [];
let steadfastConfig = {};
let completedOrdersData = {};
let incompleteOrdersData = {};
let walletTransactions = {}; // Wallet state

// Order Management State
const orderState = {
    currentPage: 1,
    itemsPerPage: 25,
    searchTerm: '',
    statusFilter: 'All',
    sortOrder: 'Newest'
};

const incompleteOrderState = {
    currentPage: 1,
    itemsPerPage: 25,
    searchTerm: '',
};

// DOM Elements (Cached for performance)
const doc = {
    prevBtn: document.getElementById('prev-btn'),
    nextBtn: document.getElementById('next-btn'),
    submitBtn: document.getElementById('submit-btn'),
    loginContainer: document.getElementById('login-container'),
    wizardContainer: document.getElementById('wizard-container'),
    resultView: document.getElementById('result-view')
};

// === Helper Functions ===
const getStatusBadge = (status) => {
    const statuses = {
        'Pending': 'bg-yellow-100 text-yellow-800',
        'Confirmed': 'bg-blue-100 text-blue-800',
        'Processing': 'bg-purple-100 text-purple-800',
        'Shipped': 'bg-green-100 text-green-800',
        'Delivered': 'bg-gray-100 text-gray-800',
        'Canceled': 'bg-red-100 text-red-800',
        // Wallet Status
        'approved': 'bg-green-100 text-green-800',
        'pending': 'bg-yellow-100 text-yellow-800',
        'rejected': 'bg-red-100 text-red-800'
    };
    return `<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statuses[status] || 'bg-gray-100 text-gray-800'}">${status}</span>`;
};

// === Master-Detail UI Rendering Logic ===
function renderMasterDetailView(options) {
    const { containerId, detailContainerId, data, title, itemRenderer, detailRenderer, state } = options;
    
    const container = document.getElementById(containerId);
    const detailContainer = document.getElementById(detailContainerId);
    if (!container || !detailContainer) return;

    let filteredData = Object.entries(data);

    if (state.searchTerm) {
        const searchTerm = state.searchTerm.toLowerCase();
        filteredData = filteredData.filter(([id, order]) => {
            const customer = order.customerInfo || order;
            return customer.name?.toLowerCase().includes(searchTerm) ||
                   customer.phone?.toLowerCase().includes(searchTerm) ||
                   id.toLowerCase().includes(searchTerm);
        });
    }
    if (state.statusFilter && state.statusFilter !== 'All') {
        filteredData = filteredData.filter(([, order]) => (order.status || 'Pending') === state.statusFilter);
    }
    
    if (state.sortOrder === 'Oldest') {
        filteredData.sort(([, a], [, b]) => (a.createdAt || a.capturedAt) - (b.createdAt || b.capturedAt));
    } else {
        filteredData.sort(([, a], [, b]) => (b.createdAt || b.capturedAt) - (a.createdAt || a.capturedAt));
    }

    const totalPages = Math.ceil(filteredData.length / state.itemsPerPage) || 1;
    state.currentPage = Math.min(state.currentPage, totalPages);
    const startIndex = (state.currentPage - 1) * state.itemsPerPage;
    const paginatedData = filteredData.slice(startIndex, startIndex + state.itemsPerPage);

    container.innerHTML = paginatedData.length > 0
        ? paginatedData.map(([id, item]) => itemRenderer(id, item)).join('')
        : `<p class="text-center text-gray-500 p-4">No ${title.toLowerCase()} found.</p>`;
    
    const paginationContainer = document.getElementById(`${containerId}-pagination`);
    if (paginationContainer) {
        paginationContainer.innerHTML = `
            <button class="pagination-btn" ${state.currentPage === 1 ? 'disabled' : ''} data-page="${state.currentPage - 1}">&laquo; Prev</button>
            <span class="text-sm">Page ${state.currentPage} of ${totalPages}</span>
            <button class="pagination-btn" ${state.currentPage === totalPages ? 'disabled' : ''} data-page="${state.currentPage + 1}">Next &raquo;</button>
        `;
    }
    
    detailContainer.innerHTML = `<div class="flex items-center justify-center h-full text-gray-500 p-4">Select an item from the list to see details.</div>`;
}

// === Action Handlers (called via Event Delegation) ===
async function updateOrderStatus(orderId, newStatus) {
    const statusSelect = document.getElementById(`status-select-${orderId}`);
    const updateBtn = statusSelect.nextElementSibling;
    updateBtn.disabled = true;
    updateBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>';

    try {
        await set(ref(db, `clients/${CURRENT_CLIENT_ID}/orders/${orderId}/status`), newStatus);
        showToast('Status updated successfully!');
    } catch (error) {
        showToast('Failed to update status.', false);
        console.error("Status update failed:", error);
    } finally {
        updateBtn.disabled = false;
        updateBtn.innerHTML = 'Update';
    }
}

async function sendToSteadfast(orderId) {
    const button = document.querySelector(`[data-action="sendToSteadfast"][data-id="${orderId}"]`);
    button.disabled = true;
    button.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-2"></i>Sending...';
    
    if (!steadfastConfig.apiKey || !steadfastConfig.secretKey) {
        showToast('Steadfast API keys are not set in Full Admin Panel.', false);
        button.disabled = false;
        button.innerHTML = '<i class="fa-solid fa-truck-fast mr-2"></i>Send to Steadfast';
        return;
    }
    
    const orderData = completedOrdersData[orderId];
    const payload = {
        invoice: orderId.slice(-10),
        recipient_name: orderData.customerInfo.name,
        recipient_phone: orderData.customerInfo.phone,
        recipient_address: orderData.customerInfo.address,
        cod_amount: orderData.totalBill,
        note: `Items: ${orderData.items.map(i => `${i.name} (x${i.quantity})`).join(', ')}`
    };

    try {
        const response = await fetch('https://cors-anywhere.herokuapp.com/https://portal.steadfast.com.bd/api/v1/create_order', {
            method: 'POST',
            headers: {
                'Api-Key': steadfastConfig.apiKey,
                'Secret-Key': steadfastConfig.secretKey,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        });
        const data = await response.json();

        if (response.ok && data.status === 200) {
            const sfData = data.consignment;
            const updates = {
                status: 'Shipped',
                steadfastInfo: { consignment_id: sfData.consignment_id, tracking_code: sfData.tracking_code, status: sfData.status }
            };
            await update(ref(db, `clients/${CURRENT_CLIENT_ID}/orders/${orderId}`), updates);
            showToast('Order sent to Steadfast successfully!');
        } else {
            throw new Error(data.message || 'Unknown Steadfast API error.');
        }
    } catch (error) {
        showToast(`Steadfast Error: ${error.message}`, false);
        button.disabled = false;
        button.innerHTML = '<i class="fa-solid fa-truck-fast mr-2"></i>Send to Steadfast';
    }
}

function copyOrderDetails(orderId) {
    const orderData = completedOrdersData[orderId];
    if (!orderData) return;

    const button = document.querySelector(`[data-action="copyOrderDetails"][data-id="${orderId}"]`);
    
    let itemsText = "Items:\n";
    orderData.items.forEach(item => {
        itemsText += `- ${item.name} (${item.quantity} x ${item.price}৳) = ${item.quantity * item.price}৳\n`;
    });
    
    const fullText = `Order Details:\nName: ${orderData.customerInfo.name}\nPhone: ${orderData.customerInfo.phone}\nAddress: ${orderData.customerInfo.address}\n---\n${itemsText}---\nSubtotal: ${orderData.subtotal}৳\nShipping: ${orderData.shipping.cost}৳\nTotal: ${orderData.totalBill}৳`;

    navigator.clipboard.writeText(fullText).then(() => {
        button.innerHTML = '<i class="fa-solid fa-check mr-2"></i>Copied!';
        setTimeout(() => { button.innerHTML = '<i class="fa-solid fa-copy mr-2"></i>Copy for Courier'; }, 2000);
    }).catch(err => {
        console.error('Copy failed', err);
        button.textContent = 'Copy Failed!';
    });
}

// === Render Functions ===
function renderCompletedOrders() {
    const itemRenderer = (id, order) => `
        <div class="master-item p-3 border-b border-l-4 border-transparent cursor-pointer hover:bg-gray-50" data-id="${id}" data-action="viewOrderDetail">
            <div class="flex justify-between items-start">
                <p class="font-semibold text-sm text-gray-800">${order.customerInfo.name}</p>
                ${getStatusBadge(order.status || 'Pending')}
            </div>
            <div class="flex justify-between items-center text-xs text-gray-500 mt-1">
                <span>${order.customerInfo.phone}</span>
                <span class="font-bold text-gray-700">${order.totalBill}৳</span>
            </div>
        </div>`;
    
    const detailRenderer = (id, order) => {
        const statuses = ['Pending', 'Confirmed', 'Processing', 'Shipped', 'Delivered', 'Canceled'];
        const statusOptions = statuses.map(s => `<option value="${s}" ${s === (order.status || 'Pending') ? 'selected' : ''}>${s}</option>`).join('');
        const productDetails = order.items.map(item => ({...item, imageUrl: (allProducts.find(p => p.id === item.id) || {}).imageUrl || 'https://i.ibb.co/vz1A5p1/placeholder-image.png'}));
        const steadfastButton = (order.status !== 'Shipped' && order.status !== 'Delivered' && order.status !== 'Canceled') ? `<button data-action="sendToSteadfast" data-id="${id}" class="bg-red-600 text-white font-semibold py-2 px-4 rounded-lg text-sm hover:bg-red-700 transition w-full"><i class="fa-solid fa-truck-fast mr-2"></i>Send to Steadfast</button>` : `<div class="text-center p-2 bg-gray-100 rounded-lg text-sm">Tracking: ${order.steadfastInfo?.tracking_code || 'N/A'}</div>`;

        return `
        <div class="p-6 order-detail-view">
            <div class="flex justify-between items-start mb-4">
                <h3 class="text-xl font-bold text-gray-800">Order #${id.slice(-6)}</h3>
                <button data-action="copyOrderDetails" data-id="${id}" class="bg-indigo-100 text-indigo-700 font-semibold py-2 px-4 rounded-lg text-sm hover:bg-indigo-200 transition"><i class="fa-solid fa-copy mr-2"></i>Copy for Courier</button>
            </div>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 text-sm mb-4">
                <div><strong>Name:</strong> <span data-field="name">${order.customerInfo.name}</span></div>
                <div><strong>Phone:</strong> <span data-field="phone">${order.customerInfo.phone}</span></div>
                <div class="lg:col-span-2"><strong>Address:</strong> <span data-field="address">${order.customerInfo.address}</span></div>
            </div>
            <div class="flex items-center gap-2 mb-4">
                <select id="status-select-${id}" class="admin-form-input">${statusOptions}</select>
                <button data-action="updateOrderStatus" data-id="${id}" class="bg-indigo-600 text-white font-semibold py-2 px-4 rounded-lg text-sm">Update</button>
            </div>
            <hr class="my-4"><h4 class="font-semibold mb-3">Items</h4>
            <div class="space-y-3 text-sm max-h-48 overflow-y-auto pr-2">
                ${productDetails.map(item => `<div class="order-item flex items-center gap-3 text-gray-700"><img src="${item.imageUrl}" class="w-12 h-12 object-cover rounded-md flex-shrink-0"><div class="flex-grow"><p class="item-name font-semibold">${item.name}</p><p class="item-details text-xs text-gray-500">${item.quantity} x ${item.price}৳</p></div><span class="font-semibold">${item.price * item.quantity}৳</span></div>`).join('')}
            </div>
            <hr class="my-4">
            <div class="flex justify-end"><div class="w-full max-w-xs space-y-2"><p class="flex justify-between text-sm">Subtotal: <span class="font-medium">${order.subtotal}৳</span></p><p class="flex justify-between text-sm">Shipping: <span class="font-medium">${order.shipping.cost}৳</span></p><p class="flex justify-between text-lg font-bold">Total: <span>${order.totalBill}৳</span></p></div></div>
            <div class="mt-6">${steadfastButton}</div>
        </div>`;
    };

    renderCompletedOrders.detailRenderer = detailRenderer;
    renderMasterDetailView({ containerId: 'completed-orders-list', detailContainerId: 'completed-orders-detail', data: completedOrdersData, title: "Completed Orders", itemRenderer, detailRenderer, state: orderState });
}

function renderIncompleteOrders() {
    const itemRenderer = (id, order) => `<div class="master-item p-3 border-b border-l-4 border-transparent cursor-pointer hover:bg-gray-50" data-id="${id}" data-action="viewIncompleteDetail"><p class="font-semibold text-sm text-gray-800">${order.name || 'N/A'}</p><span class="text-xs text-gray-500">${order.phone}</span></div>`;
    const detailRenderer = (id, order) => `<div class="p-6"><h3 class="text-xl font-bold text-gray-800 mb-4">Incomplete Order</h3><div class="space-y-3 text-sm"><p><strong>Name:</strong> <span>${order.name || 'Not provided'}</span></p><p><strong>Phone:</strong> <span>${order.phone}</span></p><p><strong>Address:</strong> <span>${order.address || 'Not provided'}</span></p><p class="text-xs text-gray-500 mt-4">Captured at: ${new Date(order.capturedAt).toLocaleString()}</p></div></div>`;
    
    renderIncompleteOrders.detailRenderer = detailRenderer;
    renderMasterDetailView({ containerId: 'incomplete-orders-list', detailContainerId: 'incomplete-orders-detail', data: incompleteOrdersData, title: "Incomplete Orders", itemRenderer, detailRenderer, state: incompleteOrderState });
}

// === Wallet Functions: START ===
function toggleModal(modalId, show) {
    const modal = document.getElementById(modalId);
    if (show) {
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    } else {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }
}

function renderTransactionHistory(transactions) {
    const listContainer = document.getElementById('transaction-history-list');
    if (!transactions || Object.keys(transactions).length === 0) {
        listContainer.innerHTML = '<p class="text-center text-slate-500 py-8">No transactions found.</p>';
        return;
    }

    const sortedTransactions = Object.entries(transactions).sort(([, a], [, b]) => b.timestamp - a.timestamp);

    listContainer.innerHTML = sortedTransactions.map(([, trans]) => `
        <div class="p-4 border rounded-lg flex items-center justify-between gap-4 even:bg-slate-50">
            <div>
                <p class="font-bold text-slate-800">${trans.amount} ৳</p>
                <p class="text-xs text-slate-500">${new Date(trans.timestamp).toLocaleString()}</p>
            </div>
            ${getStatusBadge(trans.status)}
        </div>
    `).join('');
}

async function handleRechargeSubmit(e) {
    e.preventDefault();
    const form = e.target;
    const submitBtn = form.querySelector('button[type="submit"]');
    const btnText = submitBtn.querySelector('.button-text');
    const btnSpinner = submitBtn.querySelector('.spinner');

    const amount = parseFloat(document.getElementById('recharge-amount').value);
    const phone = document.getElementById('recharge-phone').value.trim();
    const trxId = document.getElementById('recharge-trx-id').value.trim();
    const screenshotUrl = document.getElementById('recharge-screenshot-url').value.trim();
    const errorEl = document.getElementById('recharge-error');

    errorEl.textContent = '';
    if (isNaN(amount) || amount <= 0 || !phone || !screenshotUrl) {
        errorEl.textContent = "Please fill all required fields.";
        return;
    }

    submitBtn.disabled = true;
    btnText.style.display = 'none';
    btnSpinner.style.display = 'inline-block';

    try {
        const newTransaction = {
            amount: amount,
            phone: phone,
            trxId: trxId || 'N/A',
            screenshotUrl: screenshotUrl,
            timestamp: serverTimestamp(),
            status: 'approved' // Auto-approve
        };

        await push(ref(db, `clients/${CURRENT_CLIENT_ID}/wallet/transactions`), newTransaction);

        const balanceRef = ref(db, `clients/${CURRENT_CLIENT_ID}/wallet/currentBalance`);
        await runTransaction(balanceRef, (currentBalance) => {
            return (currentBalance || 0) + amount;
        });

        showToast("Recharge request submitted and approved!");
        toggleModal('recharge-modal', false);
        form.reset();
        document.getElementById('screenshot-filename').value = '';

    } catch (error) {
        console.error("Recharge failed:", error);
        errorEl.textContent = "An error occurred. Please try again.";
        showToast("Recharge failed. Please try again.", false);
    } finally {
        submitBtn.disabled = false;
        btnText.style.display = 'inline-block';
        btnSpinner.style.display = 'none';
    }
}
// === Wallet Functions: END ===

function updateOrderNotification() {
    const totalOrders = Object.keys(completedOrdersData).length;
    const lastViewedCount = parseInt(localStorage.getItem(`last_viewed_${CURRENT_CLIENT_ID}`) || '0', 10);
    const newOrders = totalOrders - lastViewedCount;
    const badge = document.getElementById('new-orders-badge');
    if (badge) {
        if (newOrders > 0) { badge.textContent = newOrders; badge.classList.remove('hidden'); } 
        else { badge.classList.add('hidden'); }
    }
}

async function prepareAndShowDashboard(clientId, subdomain, siteName) {
    CURRENT_CLIENT_ID = clientId;
    SITE_INFO = { clientId, subdomain, siteName };
    
    doc.wizardContainer.style.display = 'none';
    doc.loginContainer.style.display = 'none';
    document.getElementById('recovery-login-modal').classList.add('hidden');
    doc.resultView.style.display = 'flex';
    document.body.classList.remove('items-center');

    const publicUrl = `shop.html?site=${subdomain}`;
    const basePath = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1);
    document.getElementById('dashboard-site-name').textContent = siteName;
    document.getElementById('visit-shop-btn').href = publicUrl;
    document.getElementById('website-link-input').value = basePath + publicUrl;
    
    const customDomainBtn = document.getElementById('custom-domain-btn');
    if (customDomainBtn) {
        customDomainBtn.href = `domain-setup.html?clientId=${clientId}&site=${subdomain}`;
    }
    
    const productsSnapshot = await get(ref(db, `clients/${CURRENT_CLIENT_ID}/products`));
    if (productsSnapshot.exists()) {
        allProducts = Object.entries(productsSnapshot.val()).map(([id, val]) => ({ id, ...val }));
    }
    const settingsSnapshot = await get(ref(db, `clients/${CURRENT_CLIENT_ID}/siteSettings/steadfastConfig`));
    if(settingsSnapshot.exists()) {
        steadfastConfig = settingsSnapshot.val();
    }

    populateCategoryDropdown();

    onValue(ref(db, `clients/${CURRENT_CLIENT_ID}/orders`), (snapshot) => {
        completedOrdersData = snapshot.val() || {};
        updateOrderNotification();
        if (document.getElementById('dashboard-completed-orders').classList.contains('active')) {
            renderCompletedOrders();
        }
    });
    onValue(ref(db, `clients/${CURRENT_CLIENT_ID}/incompleteOrders`), (snapshot) => {
        incompleteOrdersData = snapshot.val() || {};
         if (document.getElementById('dashboard-incomplete-orders').classList.contains('active')) {
            renderIncompleteOrders();
        }
    });

    // === Wallet Data Listeners: START ===
    const balanceEl = document.getElementById('wallet-balance');
    onValue(ref(db, `clients/${CURRENT_CLIENT_ID}/wallet/currentBalance`), (snapshot) => {
        const balance = snapshot.val() || 0;
        balanceEl.textContent = balance.toFixed(2);
    });

    onValue(ref(db, `clients/${CURRENT_CLIENT_ID}/wallet/transactions`), (snapshot) => {
        walletTransactions = snapshot.val() || {};
        if (!document.getElementById('transaction-history-modal').classList.contains('hidden')) {
            renderTransactionHistory(walletTransactions);
        }
    });
    // === Wallet Data Listeners: END ===

    document.getElementById('order-search').addEventListener('input', (e) => {
        orderState.searchTerm = e.target.value;
        orderState.currentPage = 1;
        renderCompletedOrders();
    });
    document.getElementById('order-status-filter').addEventListener('change', (e) => {
        orderState.statusFilter = e.target.value;
        orderState.currentPage = 1;
        renderCompletedOrders();
    });
    document.getElementById('completed-orders-list-pagination').addEventListener('click', (e) => {
        const button = e.target.closest('.pagination-btn');
        if (button && !button.disabled) {
            orderState.currentPage = parseInt(button.dataset.page, 10);
            renderCompletedOrders();
        }
    });
}

function showDashboardPanel(panelId) {
    document.querySelectorAll('.dashboard-panel').forEach(p => p.classList.remove('active'));
    document.getElementById(`dashboard-${panelId}`).classList.add('active');
    document.querySelectorAll('.bottom-nav-btn').forEach(b => b.classList.remove('text-indigo-600', 'bg-indigo-50'));
    const activeBtn = document.querySelector(`.bottom-nav-btn[data-panel="${panelId}"]`);
    if (activeBtn) activeBtn.classList.add('text-indigo-600', 'bg-indigo-50');

    if (panelId === 'completed-orders') {
        localStorage.setItem(`last_viewed_${CURRENT_CLIENT_ID}`, Object.keys(completedOrdersData).length);
        updateOrderNotification();
        renderCompletedOrders();
    } else if (panelId === 'incomplete-orders') {
        renderIncompleteOrders();
    }
}

function showWizardStep(stepNumber) {
    document.querySelectorAll('.wizard-panel').forEach(p => p.classList.remove('active'));
    document.getElementById(`step-${stepNumber}`).classList.add('active');
    const percentage = (stepNumber / totalSteps) * 100;
    document.getElementById('progress-bar-fill').style.width = `${percentage}%`;
    document.getElementById('step-indicator').textContent = `Step ${stepNumber} / ${totalSteps}`;
    doc.prevBtn.style.display = (stepNumber === 1) ? 'none' : 'block';
    doc.nextBtn.style.display = (stepNumber === totalSteps) ? 'none' : 'flex';
    doc.submitBtn.style.display = (stepNumber === totalSteps) ? 'flex' : 'none';
    if (stepNumber === 1) doc.nextBtn.classList.add('ml-auto'); else doc.nextBtn.classList.remove('ml-auto');
}

function validateStep(stepNumber) {
    const currentPanel = document.getElementById(`step-${stepNumber}`); let isValid = true;
    currentPanel.querySelectorAll('.text-red-500').forEach(el => el.textContent = '');
    currentPanel.querySelectorAll('.invalid').forEach(el => el.classList.remove('invalid'));
    currentPanel.querySelectorAll('input[required]').forEach(input => {
        if (!input.value.trim()) { input.classList.add('invalid'); const errorEl = document.getElementById(`${input.id}-error`); if(errorEl) errorEl.textContent = 'This field is required.'; isValid = false; }
    });
    if (stepNumber === 2 && document.getElementById('site-name').dataset.available === 'false') { document.getElementById('site-name').classList.add('invalid'); document.getElementById('site-name-error').textContent = 'This name is already taken.'; isValid = false; }
    if(stepNumber === 4) {
        const emailInput = document.getElementById('admin-email'); const passwordInput = document.getElementById('admin-password');
        if(!/^\S+@\S+\.\S+$/.test(emailInput.value)) { emailInput.classList.add('invalid'); document.getElementById('admin-email-error').textContent = 'Please enter a valid email.'; isValid = false; }
        if(passwordInput.value.length < 6){ passwordInput.classList.add('invalid'); document.getElementById('admin-password-error').textContent = 'Password must be at least 6 characters.'; isValid = false; }
    }
    return isValid;
}

function storeData() { document.querySelectorAll('#wizard-form input, #wizard-form select').forEach(input => { if(input.id) formData[input.id] = input.value; }); localStorage.setItem('wizardFormData', JSON.stringify(formData)); }
function loadDataFromStorage() { const savedData = localStorage.getItem('wizardFormData'); if (savedData) { const parsedData = JSON.parse(savedData); Object.keys(parsedData).forEach(key => { const input = document.getElementById(key); if (input) { input.value = parsedData[key]; if(key.includes('url')) updateImagePreview(`#${key}`, `#${key}-preview`); } }); } if(!document.getElementById('logo-url').value) useDemo('logo'); if(!document.getElementById('banner-url').value) useDemo('banner'); }

function normalizeSubdomain(raw) {
    return String(raw || '')
        .trim()
        .toLowerCase()
        .replace(/\s+/g, '-')
        .replace(/[^a-z0-9-]/g, '')
        .replace(/-+/g, '-')
        .replace(/^-+|-+$/g, '');
}

function sanitizeEmailKey(email) {
    return String(email || '').trim().toLowerCase().replace(/[.#$\[\]/]/g, '_');
}

function extractSiteCandidates(source) {
    if (!source || typeof source !== 'object') return [];
    return Object.entries(source)
        .map(([clientId, info]) => ({
            clientId,
            subdomain: info?.subdomain || '',
            siteName: info?.siteName || info?.subdomain || 'Untitled Site'
        }))
        .filter((item) => item.clientId && item.subdomain);
}

function pickSiteForRecovery(sites) {
    if (!Array.isArray(sites) || sites.length === 0) return null;
    if (sites.length === 1) return sites[0];
    const numberedSites = sites.map((item, idx) => `${idx + 1}. ${item.siteName} (${item.subdomain})`).join('\n');
    const answer = window.prompt(`Multiple sites found. Enter a site number:\n${numberedSites}`, '1');
    const picked = Number(answer);
    if (!Number.isFinite(picked) || picked < 1 || picked > sites.length) return null;
    return sites[picked - 1];
}

function getSubdomainVariants(input) {
    const base = normalizeSubdomain(input);
    const variants = new Set([base]);
    if (base) {
        variants.add(`${base}-`);
        variants.add(`-${base}`);
        variants.add(base.replace(/-/g, ''));
    }
    return Array.from(variants).filter(Boolean);
}

async function resolveSiteFromTypedName(siteName) {
    const variants = getSubdomainVariants(siteName);
    for (const key of variants) {
        const snap = await get(ref(db, `publicSiteMappings/${key}`));
        if (snap.exists()) return { clientId: snap.val(), subdomain: key };
    }
    return null;
}

async function resolveSiteAccessViaServer(user, options = {}) {
    const idToken = await user.getIdToken();
    const payload = {
        idToken,
        siteName: options.siteName || '',
        clientId: options.clientId || '',
        subdomain: options.subdomain || ''
    };
    const response = await fetch('api/auth-recover-compat.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    });
    const data = await response.json().catch(() => ({}));
    if (!response.ok || !data?.siteInfo?.clientId) {
        throw new Error(data?.message || 'Could not verify account access.');
    }
    return data.siteInfo;
}

async function checkCreatorAccess(user) {
    const idToken = await user.getIdToken();
    const response = await fetch('api/creator-access-check.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ idToken })
    });
    const data = await response.json().catch(() => ({}));
    if (!response.ok) {
        throw new Error(data?.message || 'Creator access check failed.');
    }
    return !!data?.allowed;
}

async function isUserAuthorizedForClient(user, clientId) {
    const uidPathRef = ref(db, `clients/${clientId}/admins/${user.uid}`);
    try {
        const uidSnap = await get(uidPathRef);
        if (uidSnap.exists()) {
            return { ok: true, migrated: false };
        }

        const adminsRef = ref(db, `clients/${clientId}/admins`);
        const adminsSnap = await get(adminsRef);
        if (!adminsSnap.exists()) {
            return { ok: false, reason: 'no_admins' };
        }

        const admins = adminsSnap.val() || {};
        const normalizedEmail = String(user.email || '').trim().toLowerCase();
        const legacyEntry = Object.values(admins).find((admin) => {
            const adminEmail = String(admin?.email || '').trim().toLowerCase();
            return adminEmail && adminEmail === normalizedEmail;
        });

        if (!legacyEntry) {
            return { ok: false, reason: 'not_admin' };
        }

        await update(ref(db), {
            [`clients/${clientId}/admins/${user.uid}`]: {
                email: user.email || '',
                role: legacyEntry.role || 'owner',
                migratedAt: Date.now()
            }
        });

        return { ok: true, migrated: true };
    } catch (err) {
        const code = String(err?.code || '').toLowerCase();
        const message = String(err?.message || '').toLowerCase();
        if (code.includes('permission') || message.includes('permission_denied')) {
            return { ok: false, reason: 'db_permission' };
        }
        return { ok: false, reason: 'db_error' };
    }
}

function getAuthFlowErrorMessage(reason) {
    switch (reason) {
        case 'not_admin':
        case 'no_admins':
            return "This account is not an admin for the selected site.";
        case 'db_permission':
            return "Database permission denied while verifying admin access.";
        case 'db_error':
            return "Could not verify site access due to a database error.";
        default:
            return "Access verification failed. Please try again.";
    }
}

async function checkSubdomainAvailability() {
    const siteNameInput = document.getElementById('site-name'); const statusDiv = document.getElementById('subdomain-status'); const errorP = document.getElementById('site-name-error');
    const subdomain = normalizeSubdomain(siteNameInput.value);
    statusDiv.innerHTML = `<div class="subdomain-spinner"></div>`; errorP.textContent = ``; siteNameInput.dataset.available = 'false';
    if (!subdomain) { statusDiv.innerHTML = ''; return; }
    const snapshot = await get(ref(db, 'publicSiteMappings/' + subdomain));
    if (snapshot.exists()) { statusDiv.innerHTML = `<i class="fa-solid fa-times-circle text-red-500 text-lg"></i>`; errorP.textContent = `This name is already taken. Try another.`; siteNameInput.dataset.available = 'false'; } 
    else { statusDiv.innerHTML = `<i class="fa-solid fa-check-circle text-green-500 text-lg"></i>`; errorP.textContent = ``; siteNameInput.dataset.available = 'true'; }
}

function showToast(message, isSuccess = true) {
    const toast = document.getElementById('toast'); const toastMessage = document.getElementById('toast-message');
    toastMessage.textContent = message;
    toast.className = `fixed top-5 right-5 text-white py-2 px-5 rounded-lg shadow-lg opacity-0 translate-y-10 transition-all duration-300 z-50 ${isSuccess ? 'bg-green-500' : 'bg-red-500'}`;
    toast.classList.remove('opacity-0', 'translate-y-10');
    setTimeout(() => { toast.classList.add('opacity-0', 'translate-y-10'); }, 3000);
}

function openAdminIframe(hash = '') {
    if (SITE_INFO) {
        const adminUrl = `admin.html?id=${SITE_INFO.clientId}${hash}`;
        document.getElementById('admin-panel-iframe').src = adminUrl;
        const modal = document.getElementById('iframe-modal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }
}

function populateCategoryDropdown() {
    if (!CURRENT_CLIENT_ID) return;
    const noCategoryAlert = document.getElementById('no-category-alert');
    const categorySelect = document.getElementById('product-category');
    onValue(ref(db, `clients/${CURRENT_CLIENT_ID}/categories`), (snapshot) => {
        categorySelect.innerHTML = '';
        if(snapshot.exists()) {
            noCategoryAlert.classList.add('hidden');
            snapshot.forEach(childSnapshot => {
                const category = childSnapshot.val();
                if (category && category.name) {
                    categorySelect.innerHTML += `<option value="${category.name}">${category.name}</option>`;
                }
            });
        } else {
            noCategoryAlert.classList.remove('hidden');
            categorySelect.innerHTML = '<option value="">Please add a category first</option>';
        }
    });
}

async function handleLogin(email, password, clientId, siteInfo) {
    try {
        const userCredential = await signInWithEmailAndPassword(auth, email, password);
        const user = userCredential.user;
        const canonicalSiteInfo = await resolveSiteAccessViaServer(user, { clientId, siteName: siteInfo?.siteName || '', subdomain: siteInfo?.subdomain || '' });
        localStorage.setItem('siteInfo', JSON.stringify(canonicalSiteInfo));
        await prepareAndShowDashboard(canonicalSiteInfo.clientId, canonicalSiteInfo.subdomain, canonicalSiteInfo.siteName);
        return { success: true };
    } catch (err) {
        if (err?.code) {
            return { success: false, message: "Invalid email or password." };
        }
        return { success: false, message: err?.message || "Login failed." };
    }
}

// === GLOBAL EVENT DELEGATION for dynamic content ===
document.addEventListener('click', (e) => {
    const target = e.target.closest('[data-action]');
    if (!target) return;

    const { action, id } = target.dataset;

    if (action === 'viewOrderDetail') {
        const itemElement = target;
        document.querySelectorAll('#completed-orders-list .master-item').forEach(el => el.classList.remove('bg-indigo-50', 'border-indigo-400'));
        itemElement.classList.add('bg-indigo-50', 'border-indigo-400');
        
        const detailContainer = document.getElementById('completed-orders-detail');
        if (renderCompletedOrders.detailRenderer) {
            detailContainer.innerHTML = renderCompletedOrders.detailRenderer(id, completedOrdersData[id]);
        }
    }

    if (action === 'viewIncompleteDetail') {
        const itemElement = target;
        document.querySelectorAll('#incomplete-orders-list .master-item').forEach(el => el.classList.remove('bg-indigo-50', 'border-indigo-400'));
        itemElement.classList.add('bg-indigo-50', 'border-indigo-400');
        
        const detailContainer = document.getElementById('incomplete-orders-detail');
        if (renderIncompleteOrders.detailRenderer) {
            detailContainer.innerHTML = renderIncompleteOrders.detailRenderer(id, incompleteOrdersData[id]);
        }
    }

    if (action === 'updateOrderStatus') {
        const select = document.getElementById(`status-select-${id}`);
        updateOrderStatus(id, select.value);
    }
    if (action === 'copyOrderDetails') {
        copyOrderDetails(id);
    }
    if (action === 'sendToSteadfast') {
        sendToSteadfast(id);
    }
});

// === INITIALIZATION and STATIC EVENT LISTENERS ===
function initializeAppOnLoad() {
    const savedSiteInfo = localStorage.getItem('siteInfo');
    if (savedSiteInfo) {
        doc.wizardContainer.style.display = 'none';
        doc.loginContainer.style.display = 'block';
    } else {
        doc.wizardContainer.style.display = 'block';
        doc.loginContainer.style.display = 'none';
        loadDataFromStorage();
        showWizardStep(currentStep);
    }
    
    doc.nextBtn.addEventListener('click', () => { if (validateStep(currentStep)) { if (currentStep < totalSteps) { currentStep++; showWizardStep(currentStep); } } });
    doc.prevBtn.addEventListener('click', () => { if (currentStep > 1) { currentStep--; showWizardStep(currentStep); } });
    document.getElementById('site-name').addEventListener('keyup', () => { clearTimeout(subdomainCheckTimer); subdomainCheckTimer = setTimeout(checkSubdomainAvailability, 500); });
    document.getElementById('wizard-form').addEventListener('input', storeData);
    document.getElementById('login-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const button = e.target.querySelector('button[type="submit"]');
        button.disabled = true; button.querySelector('.spinner').style.display = 'inline-block';
        const errorEl = document.getElementById('login-error'); errorEl.textContent = '';
        try {
            const email = document.getElementById('login-email').value;
            const password = document.getElementById('login-password').value;
            const userCredential = await signInWithEmailAndPassword(auth, email, password);
            const user = userCredential.user;
            const isCreator = await checkCreatorAccess(user);
            const creatorHintEl = document.getElementById('creator-login-hint');
            if (creatorHintEl) {
                creatorHintEl.textContent = isCreator
                    ? 'Creator verified. You can create new websites.'
                    : 'This account can access existing sites only. Use Account Recovery.';
            }
            if (isCreator) {
                doc.wizardContainer.style.display = 'block';
                doc.loginContainer.style.display = 'none';
                loadDataFromStorage();
                showWizardStep(currentStep);
            } else {
                const savedSiteInfo = JSON.parse(localStorage.getItem('siteInfo'));
                if (!savedSiteInfo || !savedSiteInfo.clientId) { errorEl.textContent = "Use Account Recovery for existing sites."; return; }
                const canonicalSiteInfo = await resolveSiteAccessViaServer(user, { clientId: savedSiteInfo.clientId, siteName: savedSiteInfo.siteName || '', subdomain: savedSiteInfo.subdomain || '' });
                localStorage.setItem('siteInfo', JSON.stringify(canonicalSiteInfo));
                await prepareAndShowDashboard(canonicalSiteInfo.clientId, canonicalSiteInfo.subdomain, canonicalSiteInfo.siteName);
            }
        } catch (err) {
            errorEl.textContent = err?.code ? "Invalid email or password." : (err?.message || "Login failed.");
        }
        button.disabled = false; button.querySelector('.spinner').style.display = 'none';
    });
    document.getElementById('recovery-login-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const button = e.target.querySelector('button[type="submit"]');
        button.disabled = true; button.querySelector('.spinner').style.display = 'inline-block';
        const errorEl = document.getElementById('recovery-login-error'); errorEl.textContent = '';
        const siteName = document.getElementById('recovery-site-name').value;
        const email = document.getElementById('recovery-email').value;
        const password = document.getElementById('recovery-password').value;
        try {
            const userCredential = await signInWithEmailAndPassword(auth, email, password);
            const user = userCredential.user;
            const siteInfo = await resolveSiteAccessViaServer(user, { siteName });
            localStorage.setItem('siteInfo', JSON.stringify(siteInfo));
            await prepareAndShowDashboard(siteInfo.clientId, siteInfo.subdomain, siteInfo.siteName);
        } catch (err) { 
            console.error("Recovery Login Error:", err);
            if (err?.code) errorEl.textContent = "Invalid email or password.";
            else errorEl.textContent = err?.message || "An error occurred.";
        } finally { button.disabled = false; button.querySelector('.spinner').style.display = 'none'; }
    });
    document.getElementById('logout-btn').addEventListener('click', (e) => { e.preventDefault(); if (confirm("Are you sure? This will remove your current login session.")) { localStorage.removeItem('siteInfo'); window.location.reload(); } });
    doc.submitBtn.addEventListener('click', async (e) => {
        if (!validateStep(currentStep)) return; storeData();
        const button = e.target.closest('button');
        button.disabled = true; button.querySelector('.button-text').style.display = 'none'; button.querySelector('.spinner').style.display = 'inline-block';
        try {
            const creatorUser = auth.currentUser;
            if (!creatorUser) throw new Error('Creator session not found. Please login again.');
            const canCreate = await checkCreatorAccess(creatorUser);
            if (!canCreate) throw new Error('Only creator accounts can create new websites.');

            const subdomain = normalizeSubdomain(formData['site-name']);
            if (!subdomain) {
                throw new Error("Business name must include at least one English letter or number.");
            }
            const existingSnap = await get(ref(db, `publicSiteMappings/${subdomain}`));
            if (existingSnap.exists()) {
                throw new Error("This name is already taken. Try another business name.");
            }
            const userCredential = await createUserWithEmailAndPassword(auth, formData['admin-email'], formData['admin-password']);
            const user = userCredential.user;
            const newClientRef = push(ref(db, 'clients'));
            const clientId = newClientRef.key;
            const finalData = {
                siteSettings: { siteName: formData['site-name'], logoUrl: formData['logo-url'], bannerUrl: formData['banner-url'], textContent: { topBarText: 'Cash on delivery available nationwide!', copyright: `© ${new Date().getFullYear()} ${formData['site-name']}. All Rights Reserved.` }, contactInfo: { phoneNumber: formData['contact-phone'] }, layout: { activeDesign: 'fashion' } },
                admins: { [user.uid]: { email: user.email, role: 'owner' } }
            };
            const updates = {};
            updates[`/clients/${clientId}`] = finalData;
            updates[`/publicSiteMappings/${subdomain}`] = clientId;
            const emailKey = sanitizeEmailKey(user.email);
            updates[`/userSites/${user.uid}/${clientId}`] = { subdomain, siteName: formData['site-name'] };
            updates[`/usersByEmail/${emailKey}/${clientId}`] = { subdomain, siteName: formData['site-name'] };
            await update(ref(db), updates);
            localStorage.removeItem('wizardFormData');
            localStorage.setItem('siteInfo', JSON.stringify({ clientId, subdomain, siteName: formData['site-name'] }));
            await prepareAndShowDashboard(clientId, subdomain, formData['site-name']);
        } catch (error) { console.error("Error creating website:", error); alert("Something went wrong. Please try again.");
        } finally { button.disabled = false; button.querySelector('.button-text').style.display = 'inline-block'; button.querySelector('.spinner').style.display = 'none'; }
    });
    document.querySelectorAll('.dashboard-nav-btn, .bottom-nav-btn').forEach(btn => { btn.addEventListener('click', (e) => { e.preventDefault(); const panelId = btn.dataset.panel; if(panelId) showDashboardPanel(panelId); }); });
    document.querySelectorAll('.admin-tool-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const hash = btn.dataset.hash || '';
            if (hash === '#orders') { showDashboardPanel('completed-orders'); }
            else if (hash === '#incomplete-orders') { showDashboardPanel('incomplete-orders'); }
            else { openAdminIframe(hash); }
        });
    });
    document.getElementById('product-form').addEventListener('submit', async (e) => { e.preventDefault(); });
    document.getElementById('category-form').addEventListener('submit', async (e) => { e.preventDefault(); });
    document.getElementById('share-btn').addEventListener('click', () => { toggleModal('share-modal', true); });
    document.getElementById('close-modal-btn').addEventListener('click', () => { toggleModal('share-modal', false); });
    document.getElementById('copy-link-btn').addEventListener('click', (e) => { navigator.clipboard.writeText(document.getElementById('website-link-input').value); e.target.textContent = 'Copied!'; setTimeout(() => e.target.textContent = 'Copy', 2000); });
    document.getElementById('bottom-nav-admin').addEventListener('click', () => openAdminIframe());
    document.getElementById('close-iframe-btn').addEventListener('click', () => { document.getElementById('iframe-modal').classList.add('hidden'); document.getElementById('iframe-modal').classList.remove('flex'); document.getElementById('admin-panel-iframe').src = 'about:blank'; });
    document.getElementById('show-recovery-login').addEventListener('click', (e) => { e.preventDefault(); toggleModal('recovery-login-modal', true); });
    document.getElementById('close-recovery-modal-btn').addEventListener('click', () => { toggleModal('recovery-login-modal', false); });
    document.getElementById('add-category-shortcut-btn').addEventListener('click', () => showDashboardPanel('add-category'));

    // === Wallet Event Listeners: START ===
    document.getElementById('add-fund-btn').addEventListener('click', () => {
        toggleModal('recharge-modal', true);
    });
    document.getElementById('close-recharge-modal-btn').addEventListener('click', () => {
        toggleModal('recharge-modal', false);
    });
    document.getElementById('view-transactions-link').addEventListener('click', (e) => {
        e.preventDefault();
        renderTransactionHistory(walletTransactions);
        toggleModal('transaction-history-modal', true);
    });
    document.getElementById('close-history-modal-btn').addEventListener('click', () => {
        toggleModal('transaction-history-modal', false);
    });
    document.getElementById('upload-screenshot-btn').addEventListener('click', (e) => {
        const button = e.target.closest('button');
        button.dataset.targetInput = '#recharge-screenshot-url';
        triggerUpload(button);
    });
    document.getElementById('recharge-form').addEventListener('submit', handleRechargeSubmit);
    document.querySelectorAll('.copy-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const targetSelector = btn.dataset.copyTarget;
            const textToCopy = document.querySelector(targetSelector).textContent;
            navigator.clipboard.writeText(textToCopy).then(() => {
                const originalText = btn.textContent;
                btn.textContent = 'COPIED!';
                setTimeout(() => { btn.textContent = originalText; }, 2000);
            });
        });
    });
    // === Wallet Event Listeners: END ===
}

initializeAppOnLoad();