import { 
    initCore, 
    state, 
    getEl, 
    formatPrice, 
    addProductToCart, 
    handleCheckoutSubmit, 
    captureLiveInput, 
    trackPixelEvent, 
    logVisitorActivity,
    showToast,
    getLandingPageUrlForProduct,
    applyCheckoutAddressMode,
    applyProductIdQueryParamAsHash,
    getMenuCategories,
    tryDismissBootLoadingOverlay
} from './shop-core.js';
import { getResponsiveImageSpec, collectImageOrigins, ensureImagePreconnects } from './image-delivery.js';

const doc = {};
/** Dedupe Search pixel when handleRouter re-runs for same hash */
let lastDefaultSearchHashForPixel = '';
let initialDefaultAtomicRenderCommitted = false;
const DEFAULT_GRID_BATCH_SIZE = 8;
let defaultGridObserver = null;
let defaultGridRenderedCount = 0;
let defaultGridProducts = [];

const getDefaultConnectionHint = () => {
    try {
        const c = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
        return {
            saveData: !!(c && c.saveData),
            effectiveType: String((c && c.effectiveType) || '').toLowerCase(),
            deviceMemory: Number(navigator.deviceMemory || 0)
        };
    } catch (_) {
        return { saveData: false, effectiveType: '', deviceMemory: 0 };
    }
};

const getDefaultEagerImageCount = () => {
    const hint = getDefaultConnectionHint();
    const slowNetwork = hint.saveData || hint.effectiveType.includes('2g') || hint.effectiveType.includes('3g');
    const lowMemory = hint.deviceMemory > 0 && hint.deviceMemory <= 2;
    if (slowNetwork || lowMemory) return 2;
    return 6;
};

const clearDefaultGridObserver = () => {
    if (defaultGridObserver) {
        defaultGridObserver.disconnect();
        defaultGridObserver = null;
    }
};
const productInCategory = (p, catName) => (p.categories && p.categories.includes(catName)) || p.category === catName;
const productInSubcategory = (p, subName) => (p.subcategories && p.subcategories.includes(subName)) || p.subcategory === subName;

const getStorefrontSubcategoryEntries = (cat) => {
    const sub = cat && cat.subcategories;
    if (sub == null) return [];
    const norm = (raw) => {
        if (raw == null) return null;
        if (typeof raw === 'string') {
            const name = String(raw).trim();
            return name ? { name, bgColor: '', textColor: '' } : null;
        }
        if (typeof raw === 'object' && raw.name) {
            const name = String(raw.name).trim();
            if (!name) return null;
            return {
                name,
                bgColor: (raw.bgColor && String(raw.bgColor).trim()) || '',
                textColor: (raw.textColor && String(raw.textColor).trim()) || ''
            };
        }
        return null;
    };
    if (Array.isArray(sub)) return sub.map(norm).filter(Boolean);
    if (typeof sub !== 'object') return [];
    return Object.values(sub).map(norm).filter(Boolean);
};

const defaultSubcatPillStyle = (e) => {
    const st = [];
    if (e.bgColor && /^#[0-9A-Fa-f]{3,8}$/i.test(e.bgColor)) st.push(`background-color:${e.bgColor}`);
    if (e.textColor && /^#[0-9A-Fa-f]{3,8}$/i.test(e.textColor)) st.push(`color:${e.textColor}`);
    return st.length ? ` style="${st.join(';')}"` : '';
};

// ============================================================
// 1. DOM INITIALIZATION (Safe Mode)
// ============================================================
const initDOM = () => {
    // Safely get elements. If not found, it won't crash later checks.
    doc.header = getEl('header');
    doc.searchInput = getEl('search-input');
    doc.mobileNavDrawer = getEl('mobile-nav-drawer');
    doc.mobileNavOverlay = getEl('mobile-nav-overlay');
    doc.productDisplayArea = getEl('product-display-area');
    doc.promoBannerSection = getEl('promo-banner-section');
    doc.singleBanner = getEl('single-banner');
    doc.homepageFeaturesSection = getEl('homepage-features-section');
    doc.homepageFeaturesGrid = getEl('homepage-features-grid');
    
    // Sections
    doc.mainShopContent = getEl('main-shop-content');
    doc.productDetailSection = getEl('product-detail-section');
    doc.checkoutPageSection = getEl('checkout-page-section');
    doc.thankYouPageSection = getEl('thank-you-page-section');
    
    // Checkout Elements
    doc.shippingOptionsContainer = getEl('shipping-options-container');
    doc.checkoutOrderSummary = getEl('checkout-order-summary');
    doc.checkoutForm = getEl('checkout-form');
    doc.mobileCheckoutBar = getEl('mobile-checkout-bar');
    doc.mobileCheckoutTotal = getEl('mobile-checkout-total');
    doc.bottomNavBar = getEl('bottom-nav-bar');
    
    // Product Detail Elements
    doc.detailImage = getEl('product-detail-image');
    doc.detailThumbnailContainer = getEl('product-thumbnail-container');
    doc.detailName = getEl('product-detail-name');
    doc.detailPrice = getEl('product-detail-price');
    doc.detailDesc = getEl('product-detail-description');
    doc.detailVariants = getEl('product-detail-variants');
    doc.detailAddToCartBtn = getEl('product-detail-add-to-cart-btn');
    doc.detailOrderBtn = getEl('product-detail-cod-order-btn');
    
    // Misc
    doc.loadingOverlay = getEl('loading-overlay');
};

// ============================================================
// 2. UI RENDERING FUNCTIONS
// ============================================================

const renderDefaultProductCard = (product, index) => {
    let priceHTML;
    const eagerCount = getDefaultEagerImageCount();
    const imgLoadingAttrs = index < eagerCount
        ? 'loading="eager" fetchpriority="high" decoding="async"'
        : 'loading="lazy" decoding="async"';
    if (product.hasVariants && product.variants) {
        const prices = Object.values(product.variants).map(v => v.salePrice || 0);
        const minPrice = prices.length ? Math.min(...prices) : 0;
        priceHTML = `<div class="price-wrapper"><ins>${formatPrice(minPrice)}+</ins></div>`;
    } else {
        const hasDiscount = product.regularPrice > 0 && product.regularPrice > product.salePrice;
        priceHTML = `
            <div class="price-wrapper">
                ${hasDiscount ? `<del>${formatPrice(product.regularPrice)}</del>` : ''}
                <ins>${formatPrice(product.salePrice)}</ins>
            </div>`;
    }

    const isOrderCall = state.siteSettings?.layout?.productDisplayStyle === 'orderCall';
    const contact = state.siteSettings?.contactInfo || {};
    const phoneRaw = String(contact.phoneNumber || contact.hotlineNumber || '').trim();
    const telHref = phoneRaw ? `tel:${phoneRaw.replace(/\s/g, '')}` : '';
    const productHref = getLandingPageUrlForProduct(product) || `#/product/${product.id}`;
    const imageSpec = getResponsiveImageSpec(product.imageUrl, {
        widths: [240, 420, 640, 920],
        fallbackWidth: 420,
        quality: 78,
        sizes: '(max-width: 768px) 50vw, (max-width: 1024px) 33vw, 25vw'
    });
    if (isOrderCall) {
        const callHtml = telHref
            ? `<a href="${telHref}" class="product-call-btn" title="Call"><i class="fa-solid fa-phone"></i></a>`
            : `<button type="button" class="product-call-btn product-call-btn--disabled" disabled title="Set phone number in admin"><i class="fa-solid fa-phone"></i></button>`;
        return `
            <div class="product-card product-card--order-call">
                <a href="${productHref}" class="product-image-container">
                    <img ${imgLoadingAttrs} src="${imageSpec.src}"${imageSpec.srcset ? ` srcset="${imageSpec.srcset}" sizes="${imageSpec.sizes}"` : ''} alt="${product.name}" onerror="this.src='https://placehold.co/300x300?text=No+Image'"/>
                </a>
                <div class="product-info">
                    <h3 class="product-title"><a href="${productHref}">${product.name}</a></h3>
                    ${priceHTML}
                    <div class="product-order-row">
                        <button type="button" class="product-order-now-btn" data-id="${product.id}">Order now</button>
                        ${callHtml}
                    </div>
                </div>
            </div>`;
    }
    return `
        <div class="product-card">
            <a href="${productHref}" class="product-image-container">
                <img ${imgLoadingAttrs} src="${imageSpec.src}"${imageSpec.srcset ? ` srcset="${imageSpec.srcset}" sizes="${imageSpec.sizes}"` : ''} alt="${product.name}" onerror="this.src='https://placehold.co/300x300?text=No+Image'"/>
            </a>
            <div class="product-info">
                <h3 class="product-title"><a href="${productHref}">${product.name}</a></h3>
                ${priceHTML}
                <button class="product-action-btn" data-id="${product.id}">
                    <i class="fa-solid fa-cart-plus"></i> অর্ডার করুন
                </button>
            </div>
        </div>`;
};

const appendDefaultGridBatch = (gridEl) => {
    if (!gridEl) return;
    if (defaultGridRenderedCount >= defaultGridProducts.length) return;
    const nextEnd = Math.min(defaultGridRenderedCount + DEFAULT_GRID_BATCH_SIZE, defaultGridProducts.length);
    const html = defaultGridProducts
        .slice(defaultGridRenderedCount, nextEnd)
        .map((p, idx) => renderDefaultProductCard(p, defaultGridRenderedCount + idx))
        .join('');
    if (html) gridEl.insertAdjacentHTML('beforeend', html);
    defaultGridRenderedCount = nextEnd;
};

const syncDefaultShopAriaBusy = () => {
    const el = doc.mainShopContent || getEl('main-shop-content');
    if (!el) return;
    const h = (window.location.hash || '').split('?')[0];
    const onShop = h === '' || h === '#/' || h === '#/shop' || h.startsWith('#/shop');
    if (!onShop || el.classList.contains('hidden')) {
        el.removeAttribute('aria-busy');
        return;
    }
    const st = state.storeCatalogFetchStatus || 'idle';
    const n = (state.allProducts && state.allProducts.length) || 0;
    const waiting = n === 0 && (st === 'loading' || st === 'idle');
    el.setAttribute('aria-busy', waiting ? 'true' : 'false');
};

const renderProductGrid = (products) => {
    const container = doc.productDisplayArea;
    if (!container) {
        syncDefaultShopAriaBusy();
        return;
    }
    clearDefaultGridObserver();

    if (!products || products.length === 0) {
        const fetchStatus = state.storeCatalogFetchStatus || 'idle';
        if (fetchStatus === 'loading' || fetchStatus === 'idle') {
            container.innerHTML = '';
            container.style.minHeight = '40vh';
            syncDefaultShopAriaBusy();
            return;
        }
        container.style.minHeight = '';
        container.innerHTML = `<div class="text-center py-10 text-gray-500">কোনো পণ্য পাওয়া যায়নি</div>`;
        syncDefaultShopAriaBusy();
        return;
    }

    container.style.minHeight = '';
    container.innerHTML = `
        <h2 class="section-title">আমাদের কালেকশন</h2>
        <div id="default-products-grid" class="products-grid"></div>
        <div id="default-products-sentinel" style="height:1px;visibility:hidden;pointer-events:none"></div>`;

    defaultGridProducts = Array.isArray(products) ? [...products] : [];
    defaultGridRenderedCount = 0;
    const gridEl = container.querySelector('#default-products-grid');
    const sentinel = container.querySelector('#default-products-sentinel');
    if (!gridEl) {
        syncDefaultShopAriaBusy();
        return;
    }

    const eagerCount = getDefaultEagerImageCount();
    const firstBatch = Math.min(defaultGridProducts.length, Math.max(DEFAULT_GRID_BATCH_SIZE, eagerCount + 2));
    const firstBatchHtml = defaultGridProducts.slice(0, firstBatch).map((p, idx) => renderDefaultProductCard(p, idx)).join('');
    gridEl.innerHTML = firstBatchHtml;
    defaultGridRenderedCount = firstBatch;

    if (defaultGridRenderedCount >= defaultGridProducts.length || !sentinel) {
        if (sentinel) sentinel.remove();
        syncDefaultShopAriaBusy();
        return;
    }
    defaultGridObserver = new IntersectionObserver((entries) => {
        if (!entries[0]?.isIntersecting) return;
        appendDefaultGridBatch(gridEl);
        if (defaultGridRenderedCount >= defaultGridProducts.length) {
            clearDefaultGridObserver();
            sentinel.remove();
        }
    }, { rootMargin: '180px' });
    defaultGridObserver.observe(sentinel);
    syncDefaultShopAriaBusy();
};

const renderMobileCategories = () => {
    const container = getEl('mobile-category-list');
    if (!container || !state.allCategories) return;

    const esc = (s) => String(s).replace(/</g, '&lt;');
    const menuCategories = getMenuCategories();
    container.innerHTML = `<a href="#/shop" class="font-bold text-accent-color border-b p-3 block">সকল পণ্য</a>` +
        menuCategories.map((cat) => {
            const subs = getStorefrontSubcategoryEntries(cat);
            const pills = subs.length
                ? `<div class="px-3 pb-2 flex flex-wrap gap-1 border-b border-gray-100">${subs.map((e) =>
                    `<span class="inline-block text-xs px-2 py-0.5 rounded border border-gray-200"${defaultSubcatPillStyle(e)}>${esc(e.name)}</span>`
                ).join('')}</div>`
                : '';
            return `
            <div class="border-b border-gray-100">
                <a href="#/shop?search=${encodeURIComponent(cat.name)}" class="mobile-cat-link block p-3 hover:bg-gray-50">${esc(cat.name)}</a>
                ${pills}
            </div>`;
        }).join('');
        
    // Handle category filtering
    document.querySelectorAll('.mobile-cat-link').forEach(link => {
        link.addEventListener('click', () => {
            toggleMobileNav(false);
        });
    });
};

const HOMEPAGE_FEATURE_DEFAULTS = [
    { icon: 'fa-solid fa-truck-fast', title: '60 Mins Delivery', subtitle: 'Free shipping over 1500tk' },
    { icon: 'fa-solid fa-shield-halved', title: 'Authorized Products', subtitle: 'Within 30 days for an exchange' },
    { icon: 'fa-solid fa-headset', title: 'Customer Service Support', subtitle: '8am to 10pm' },
    { icon: 'fa-solid fa-credit-card', title: 'Flexible Payments', subtitle: 'Pay with multiple credit cards' }
];

const escapeHtml = (value) => String(value ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');

const sanitizeIconClass = (value, fallback) => {
    const cleaned = String(value || '').trim().replace(/[^a-zA-Z0-9\-\s]/g, '');
    return cleaned || fallback;
};

const HOMEPAGE_FEATURE_ROOT_VAR_NAMES = [
    '--optional-feature-card-bg',
    '--optional-feature-card-border',
    '--optional-feature-card-shadow',
    '--optional-feature-icon-bg',
    '--optional-feature-icon-border',
    '--optional-feature-icon-color',
    '--optional-feature-title-color',
    '--optional-feature-subtitle-color',
    '--optional-feature-grid-gap',
];

function clearHomepageFeatureRootVars() {
    const root = document.documentElement.style;
    HOMEPAGE_FEATURE_ROOT_VAR_NAMES.forEach((name) => root.removeProperty(name));
}

function normalizeHomepageFeatureCssColor(raw) {
    const s = String(raw == null ? '' : raw).trim();
    if (!s) return null;
    const lower = s.toLowerCase();
    if (lower === 'transparent') return 'transparent';
    let hex = s.startsWith('#') ? s.slice(1) : s;
    if (/^[0-9a-f]{3}$/i.test(hex)) {
        hex = hex.split('').map((c) => c + c).join('');
    }
    if (/^[0-9a-f]{6}$/i.test(hex)) return `#${hex.toLowerCase()}`;
    return null;
}

function normalizeHomepageFeatureShadow(raw) {
    const s = String(raw == null ? '' : raw).trim();
    if (!s || s.length > 200) return null;
    const lower = s.toLowerCase();
    if (lower.includes('url(') || lower.includes('<') || lower.includes('expression') || lower.includes('@import')) return null;
    return s;
}

function normalizeHomepageFeatureGapPx(raw) {
    const n = Number(raw);
    if (!Number.isFinite(n)) return null;
    const i = Math.round(n);
    if (i < 0 || i > 48) return null;
    return `${i}px`;
}

function applyHomepageFeatureStyles(settings) {
    clearHomepageFeatureRootVars();
    const config = settings && settings.layout && settings.layout.homepageFeatures ? settings.layout.homepageFeatures : {};
    const styles = config.styles && typeof config.styles === 'object' ? config.styles : {};
    const root = document.documentElement.style;
    const setColor = (cssName, key) => {
        const v = normalizeHomepageFeatureCssColor(styles[key]);
        if (v) root.setProperty(cssName, v);
    };
    setColor('--optional-feature-card-bg', 'cardBg');
    setColor('--optional-feature-card-border', 'cardBorder');
    const shadow = normalizeHomepageFeatureShadow(styles.cardShadow);
    if (shadow) root.setProperty('--optional-feature-card-shadow', shadow);
    setColor('--optional-feature-icon-bg', 'iconBg');
    setColor('--optional-feature-icon-border', 'iconBorder');
    setColor('--optional-feature-icon-color', 'iconColor');
    setColor('--optional-feature-title-color', 'titleColor');
    setColor('--optional-feature-subtitle-color', 'subtitleColor');
    const gap = normalizeHomepageFeatureGapPx(styles.gridGapPx);
    if (gap) root.setProperty('--optional-feature-grid-gap', gap);
}

const renderHomepageFeatures = (settings) => {
    if (!doc.homepageFeaturesSection || !doc.homepageFeaturesGrid) return;
    const config = settings && settings.layout && settings.layout.homepageFeatures ? settings.layout.homepageFeatures : {};
    const enabled = config.enabled === true;
    const items = Array.isArray(config.items) ? config.items : [];
    if (!enabled) {
        clearHomepageFeatureRootVars();
        doc.homepageFeaturesSection.classList.add('hidden');
        doc.homepageFeaturesGrid.innerHTML = '';
        return;
    }
    applyHomepageFeatureStyles(settings);
    const rows = HOMEPAGE_FEATURE_DEFAULTS.map((defaults, idx) => {
        const item = items[idx] && typeof items[idx] === 'object' ? items[idx] : {};
        const icon = sanitizeIconClass(item.icon, defaults.icon);
        const title = String(item.title || defaults.title || '').trim();
        const subtitle = String(item.subtitle || defaults.subtitle || '').trim();
        return `
            <article class="homepage-feature-card">
                <span class="homepage-feature-icon"><i class="${escapeHtml(icon)}" aria-hidden="true"></i></span>
                <div>
                    <p class="homepage-feature-title">${escapeHtml(title)}</p>
                    <p class="homepage-feature-subtitle">${escapeHtml(subtitle)}</p>
                </div>
            </article>
        `;
    });
    doc.homepageFeaturesGrid.innerHTML = rows.join('');
    doc.homepageFeaturesSection.classList.remove('hidden');
};

const renderShippingOptions = (options) => {
    const container = doc.shippingOptionsContainer;
    if (!container) return;
    
    // Default fallback if no options set in admin
    if (!options || options.length === 0) {
        options = [{ label: 'সারা বাংলাদেশ', cost: 120 }];
    }
    
    container.innerHTML = options.map((opt, index) => `
        <label class="shipping-option ${index === 0 ? 'active' : ''} block cursor-pointer border p-3 rounded mb-2 hover:bg-gray-50">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-2">
                    <input type="radio" name="shipping" value="${opt.cost}" data-label="${opt.label}" ${index === 0 ? 'checked' : ''} class="accent-red-500 w-4 h-4">
                    <span class="font-medium text-sm">${opt.label}</span>
                </div>
                <span class="font-bold text-sm text-gray-700">${formatPrice(opt.cost)}</span>
            </div>
        </label>
    `).join('');
    
    updateCheckoutSummary();
};

const updateCheckoutSummary = () => {
    const container = doc.checkoutOrderSummary;
    if (!container) return;
    
    const subtotal = state.cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    const shippingOption = document.querySelector('input[name="shipping"]:checked');
    const shippingCost = shippingOption ? Number(shippingOption.value) : 0;
    const total = subtotal + shippingCost;
    
    const itemsHTML = state.cartItems.map(item => `
        <div class="flex justify-between items-center mb-2 text-sm border-b pb-2">
            <div class="flex items-center gap-2">
                <img src="${item.image}" class="w-10 h-10 rounded object-cover" loading="lazy" decoding="async" onerror="this.src='https://placehold.co/50'">
                <div>
                    <p class="font-medium line-clamp-1">${item.name} ${item.variantName ? `(${item.variantName})` : ''}</p>
                    <p class="text-xs text-gray-500">${item.quantity} x ${formatPrice(item.price)}</p>
                </div>
            </div>
            <span class="font-bold">${formatPrice(item.price * item.quantity)}</span>
        </div>
    `).join('');
    
    container.innerHTML = `
        <div class="mb-4 max-h-40 overflow-y-auto">${itemsHTML}</div>
        <div class="space-y-2 text-sm border-t pt-3">
            <div class="flex justify-between"><span>সাব-টোটাল:</span> <span>${formatPrice(subtotal)}</span></div>
            <div class="flex justify-between"><span>ডেলিভারি চার্জ:</span> <span>${formatPrice(shippingCost)}</span></div>
            <div class="flex justify-between text-lg font-bold border-t pt-2 text-red-600">
                <span>সর্বমোট:</span> <span>${formatPrice(total)}</span>
            </div>
        </div>
        <button type="submit" form="checkout-form" class="checkout-submit-btn hidden lg:flex w-full bg-green-600 text-white font-bold py-3.5 rounded-lg mt-4 hover:bg-green-700 transition shadow-lg justify-center items-center gap-2">
            <span>অর্ডার কনফার্ম করুন</span>
            <div class="button-spinner hidden w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
        </button>
    `;
    if (doc.mobileCheckoutTotal) doc.mobileCheckoutTotal.textContent = `${formatPrice(total)}`;
};

// ============================================================
// 3. ROUTING & VIEW HANDLING
// ============================================================

const showProductDetail = (productId) => {
    const product = state.allProducts.find(p => p.id === productId);
    state.currentViewingProduct = product;
    
    // Reset UI
    if(doc.detailVariants) doc.detailVariants.innerHTML = '';
    doc.detailThumbnailContainer.innerHTML = '';
    
    if (!product) {
        doc.detailName.textContent = "পণ্যটি পাওয়া যায়নি";
        return;
    }

    let defaultGalleryPixelSent = false;
    const fireImageGallerySwipedOnce = () => {
        if (defaultGalleryPixelSent) return;
        defaultGalleryPixelSent = true;
        try {
            trackPixelEvent('ImageGallerySwiped', { content_name: product.name, content_ids: [String(product.id)] });
        } catch (_) { /* noop */ }
    };
    
    // Set Basic Info
    const detailMainSpec = getResponsiveImageSpec(product.imageUrl, {
        widths: [640, 960, 1280, 1600],
        fallbackWidth: 960,
        quality: 82,
        sizes: '(max-width: 1024px) 100vw, 50vw'
    });
    doc.detailImage.src = detailMainSpec.src || product.imageUrl;
    if (detailMainSpec.srcset) {
        doc.detailImage.srcset = detailMainSpec.srcset;
        doc.detailImage.sizes = detailMainSpec.sizes;
    }
    doc.detailName.textContent = product.name;
    doc.detailDesc.innerHTML = product.description || "কোনো বিবরণ নেই";
    
    // Thumbnails
    const allImages = [product.imageUrl, ...(product.galleryImageUrls || [])];
    if (allImages.length > 1) {
        allImages.forEach((url, index) => {
            const img = document.createElement('img');
            const thumbSpec = getResponsiveImageSpec(url, {
                widths: [120, 240, 360],
                fallbackWidth: 240,
                quality: 76,
                sizes: '72px'
            });
            img.src = thumbSpec.src || url;
            if (thumbSpec.srcset) {
                img.srcset = thumbSpec.srcset;
                img.sizes = thumbSpec.sizes;
            }
            img.loading = 'lazy';
            img.decoding = 'async';
            img.className = `product-thumbnail-image ${index === 0 ? 'active' : ''}`;
            img.onclick = () => {
                doc.detailImage.src = url;
                const mainSpec = getResponsiveImageSpec(url, {
                    widths: [640, 960, 1280, 1600],
                    fallbackWidth: 960,
                    quality: 82,
                    sizes: '(max-width: 1024px) 100vw, 50vw'
                });
                if (mainSpec.srcset) {
                    doc.detailImage.src = mainSpec.src || url;
                    doc.detailImage.srcset = mainSpec.srcset;
                    doc.detailImage.sizes = mainSpec.sizes;
                }
                document.querySelectorAll('.product-thumbnail-image').forEach(el => el.classList.remove('active'));
                img.classList.add('active');
                fireImageGallerySwipedOnce();
            };
            doc.detailThumbnailContainer.appendChild(img);
        });
    }

    // Pricing & Variants Logic
    const updatePriceDisplay = (variant) => {
        let html = `<ins>${formatPrice(variant.salePrice)}</ins>`;
        if (variant.regularPrice > variant.salePrice) {
            html = `<del class="text-gray-400 text-lg mr-2">${formatPrice(variant.regularPrice)}</del>` + html;
        }
        doc.detailPrice.innerHTML = html;
        
        // Update Buttons Data
        doc.detailAddToCartBtn.dataset.id = product.id;
        doc.detailOrderBtn.dataset.id = product.id;
        
        if (variant.id) {
            doc.detailAddToCartBtn.dataset.variantId = variant.id;
            doc.detailOrderBtn.dataset.variantId = variant.id;
        } else {
            delete doc.detailAddToCartBtn.dataset.variantId;
            delete doc.detailOrderBtn.dataset.variantId;
        }
    };

    let usableVariantEntries = [];
    if (product.hasVariants && product.variants && typeof product.variants === 'object') {
        try {
            usableVariantEntries = Object.entries(product.variants).filter(([key, v]) => {
                if (!key || !v || typeof v !== 'object') return false;
                const sp = Number(v.salePrice);
                const nm = v.name != null ? String(v.name).trim() : '';
                return !!nm && Number.isFinite(sp) && sp > 0;
            });
        } catch (_) {
            usableVariantEntries = [];
        }
    }

    if (usableVariantEntries.length > 0) {
        const select = document.createElement('select');
        select.className = 'w-full p-2 border rounded mb-2 bg-white';
        usableVariantEntries.forEach(([key, v]) => {
            const opt = document.createElement('option');
            opt.value = key;
            opt.textContent = `${String(v.name).trim()} - ${formatPrice(Number(v.salePrice))}`;
            select.appendChild(opt);
        });

        select.onchange = (e) => {
            const v = product.variants[e.target.value];
            try {
                trackPixelEvent('VariantSelected', {
                    content_name: product.name,
                    content_ids: [String(product.id)],
                    variant: String(v?.name || '').slice(0, 200),
                });
            } catch (_) { /* noop */ }
            updatePriceDisplay({ ...v, id: e.target.value });
        };

        doc.detailVariants.appendChild(select);
        const firstKey = usableVariantEntries[0][0];
        const firstVar = product.variants[firstKey];
        updatePriceDisplay({ ...firstVar, id: firstKey });
    } else {
        updatePriceDisplay(product);
        if (product.hasVariants && doc.detailVariants) {
            doc.detailVariants.innerHTML = '<p class="text-sm text-gray-500 italic">No options available.</p>';
        }
    }
    
    // Render Related Products (any shared category)
    const productCats = product.categories || (product.category ? [product.category] : []);
    const productSubcats = product.subcategories || (product.subcategory ? [product.subcategory] : []);
    const related = state.allProducts
        .filter(p => p.id !== product.id && (productCats.some(c => productInCategory(p, c)) || productSubcats.some(s => productInSubcategory(p, s))))
        .slice(0, 4);
    
    const relatedContainer = getEl('related-products-grid');
    if(relatedContainer) {
        relatedContainer.innerHTML = related.map(p => {
            const href = getLandingPageUrlForProduct(p) || `#/product/${p.id}`;
            return `
            <div class="product-card border p-2 rounded">
                <a href="${href}" class="product-image-container block aspect-square overflow-hidden mb-2">
                    <img src="${getResponsiveImageSpec(p.imageUrl, { widths: [200, 320, 480], fallbackWidth: 320, quality: 76, sizes: '(max-width: 768px) 46vw, 180px' }).src}" loading="lazy" decoding="async" class="w-full h-full object-cover">
                </a>
                <div class="text-center">
                    <h4 class="font-bold text-sm truncate"><a href="${href}">${p.name}</a></h4>
                    <p class="text-red-600 font-bold">${formatPrice(p.salePrice)}</p>
                </div>
            </div>
        `;
        }).join('');
    }

    trackPixelEvent('ViewContent', { content_name: product.name, content_ids: [product.id], value: product.salePrice, currency: 'BDT' });
    logVisitorActivity('View Product', `Viewing ${product.name}`);
};

const syncMobileCheckoutChrome = (hash) => {
    const onCheckout = hash === '#/checkout';
    if (doc.mobileCheckoutBar) {
        if (onCheckout) doc.mobileCheckoutBar.classList.remove('translate-y-full');
        else doc.mobileCheckoutBar.classList.add('translate-y-full');
    }
    if (doc.bottomNavBar) {
        doc.bottomNavBar.style.transform = onCheckout ? 'translateY(100%)' : '';
    }
};

const handleRouter = () => {
    const hash = window.location.hash;

    // Safely Hide All Sections
    [doc.mainShopContent, doc.productDetailSection, doc.checkoutPageSection, doc.thankYouPageSection].forEach(el => {
        if(el) el.classList.add('hidden');
    });
    
    window.scrollTo({ top: 0, behavior: 'auto' });
    
    if (hash.startsWith('#/product/')) {
        const id = hash.split('/')[2];
        if (id) {
            const product = state.allProducts.find(p => p.id === id);
            const landingUrl = product && getLandingPageUrlForProduct(product);
            if (landingUrl) {
                window.location.href = landingUrl;
                return;
            }
            doc.productDetailSection?.classList.remove('hidden');
            showProductDetail(id);
        }
    } else if (hash === '#/checkout') {
        if(state.cartItems.length === 0) {
            window.location.hash = '#/shop';
            showToast('আপনার কার্ট খালি!', 'error');
            return;
        }
        doc.checkoutPageSection?.classList.remove('hidden');
        applyCheckoutAddressMode(state.siteSettings);
        renderShippingOptions(state.siteSettings.shippingOptions);
        trackPixelEvent('InitiateCheckout');
        state.incompleteOrderId = Date.now().toString();
    } else if (hash === '#/thank-you') {
        doc.thankYouPageSection?.classList.remove('hidden');
        state.incompleteOrderId = null;
    } else {
        // Default: Shop Home
        doc.mainShopContent?.classList.remove('hidden');
        
        // Check for Search Query
        const query = new URLSearchParams(window.location.hash.split('?')[1]).get('search');
        if (query) {
            // Decode URI component to handle Bengali characters properly
            const decodedQuery = decodeURIComponent(query);
            const fullHash = window.location.hash;
            if (fullHash !== lastDefaultSearchHashForPixel) {
                lastDefaultSearchHashForPixel = fullHash;
                try {
                    trackPixelEvent('Search', { search_string: decodedQuery });
                } catch (_) { /* noop */ }
            }
            const filtered = state.allProducts.filter(p => 
                p.name.toLowerCase().includes(decodedQuery.toLowerCase()) || 
                (p.categories && p.categories.some(c => c.toLowerCase().includes(decodedQuery.toLowerCase()))) ||
                (p.category && p.category.toLowerCase().includes(decodedQuery.toLowerCase())) ||
                (p.subcategories && p.subcategories.some(s => s.toLowerCase().includes(decodedQuery.toLowerCase()))) ||
                (p.subcategory && p.subcategory.toLowerCase().includes(decodedQuery.toLowerCase()))
            );
            
            if(doc.productDisplayArea) {
                doc.productDisplayArea.innerHTML = `<h2 class="section-title">ফলাফল: "${decodedQuery}"</h2>`;
                // Create a temporary div to render grid
                const tempDiv = document.createElement('div');
                // We reuse the logic, but renderProductGrid targets doc.productDisplayArea directly.
                // So we clear it and append manually for search results
                renderProductGrid(filtered);
            }
        } else {
            renderProductGrid(state.allProducts);
        }
        logVisitorActivity('View Home', 'Browsing Shop');
    }
    syncMobileCheckoutChrome(window.location.hash);
    syncDefaultShopAriaBusy();
};

/** FB in-app browser: programmatic hash may skip hashchange */
const scheduleDefaultRouteSync = () => {
    setTimeout(() => {
        try {
            handleRouter();
        } catch (err) {
            console.warn('[scheduleDefaultRouteSync]', err);
        }
    }, 0);
};
if (typeof window !== 'undefined') {
    window.sbDefaultSyncRouteAfterHash = scheduleDefaultRouteSync;
}

// ============================================================
// 4. UI HELPERS (Menu, Search, Toggles)
// ============================================================

const toggleMobileNav = (show) => {
    if (!doc.mobileNavDrawer || !doc.mobileNavOverlay) return;
    if(show) {
        doc.mobileNavDrawer.classList.add('open');
        doc.mobileNavOverlay.classList.remove('hidden');
    } else {
        doc.mobileNavDrawer.classList.remove('open');
        doc.mobileNavOverlay.classList.add('hidden');
    }
};

const toggleSearch = () => {
    const container = getEl('search-container');
    if(container) {
        container.classList.toggle('hidden');
        if(!container.classList.contains('hidden') && doc.searchInput) {
            doc.searchInput.focus();
        }
    }
};

const updateCartCount = () => {
    const count = state.cartItems.reduce((sum, i) => sum + i.quantity, 0);
    document.querySelectorAll('.cart-count').forEach(el => el.textContent = count);
    
    // Update Cart Drawer List
    const cartBody = getEl('cart-body');
    if (cartBody) {
        if (state.cartItems.length === 0) {
            cartBody.innerHTML = '<div class="text-center text-gray-400 py-10">কার্ট খালি</div>';
        } else {
            cartBody.innerHTML = state.cartItems.map(item => `
                <div class="flex gap-3 mb-4 border-b pb-2">
                    <img src="${item.image}" class="w-16 h-16 rounded object-cover" loading="lazy" decoding="async">
                    <div class="flex-grow">
                        <h4 class="font-bold text-sm line-clamp-1">${item.name}</h4>
                        <p class="text-xs text-gray-500">${item.variantName || ''}</p>
                        <div class="flex justify-between items-center mt-1">
                            <span class="font-bold text-red-600">${formatPrice(item.price)}</span>
                            <div class="flex items-center gap-2">
                                <button class="decrease-qty-btn bg-gray-200 w-6 h-6 rounded" data-id="${item.variantId ? `${item.id}_${item.variantId}` : item.id}">-</button>
                                <span class="text-sm">${item.quantity}</span>
                                <button class="increase-qty-btn bg-gray-200 w-6 h-6 rounded" data-id="${item.variantId ? `${item.id}_${item.variantId}` : item.id}">+</button>
                            </div>
                        </div>
                    </div>
                    <button class="remove-from-cart-btn text-gray-400 hover:text-red-500" data-id="${item.variantId ? `${item.id}_${item.variantId}` : item.id}"><i class="fa-solid fa-trash"></i></button>
                </div>
            `).join('');
        }
    }
    
    // Update Total
    const total = state.cartItems.reduce((sum, i) => sum + (i.price * i.quantity), 0);
    document.querySelectorAll('.cart-total-price').forEach(el => el.textContent = formatPrice(total));
};

/** Dashboard → Customization → Typography (same keys as Classic storefront). */
const applyTypographyVars = (settings) => {
    if (!settings) return;
    const root = document.documentElement;
    const typo = settings.layout && settings.layout.typography ? settings.layout.typography : {};
    const isMob = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(max-width: 767px)').matches;
    const num = (v) => {
        if (v == null || v === '') return null;
        const n = Number(v);
        return Number.isFinite(n) && n >= 8 && n <= 40 ? n : null;
    };
    const pick = (g) => {
        const o = typo[g] || {};
        const v = isMob ? o.mobile : o.pc;
        const n = num(v);
        return n != null ? `${n}px` : '';
    };
    const map = {
        '--font-body': 'body',
        '--font-heading': 'heading',
        '--font-button': 'button',
        '--font-product-title': 'productTitle',
        '--font-product-price': 'productPrice',
        '--font-nav': 'nav',
        '--font-sidebar-category': 'sidebarCategory',
        '--font-sidebar-category-icon': 'sidebarCategoryIcon',
        '--font-sidebar-header': 'sidebarHeader',
        '--font-footer': 'footer',
        '--font-top-bar': 'topBar',
        '--font-category-pill': 'categoryPill',
        '--font-card-description': 'cardDescription',
        '--font-badge': 'badge',
        '--font-cart-drawer': 'cartDrawer'
    };
    Object.entries(map).forEach(([cssVar, group]) => {
        const val = pick(group);
        if (val) root.style.setProperty(cssVar, val);
        else root.style.removeProperty(cssVar);
    });
};

let typographyResizeTimerDefault = null;
const scheduleTypographyVarsReapplyDefault = () => {
    if (typeof window === 'undefined') return;
    clearTimeout(typographyResizeTimerDefault);
    typographyResizeTimerDefault = window.setTimeout(() => {
        try {
            applyTypographyVars(state.siteSettings);
        } catch (_) { /* ignore */ }
    }, 150);
};

if (typeof window !== 'undefined') {
    window.addEventListener('resize', scheduleTypographyVarsReapplyDefault, { passive: true });
}

const toggleCartDrawer = (show) => {
    const drawer = getEl('cart-drawer');
    const overlay = getEl('cart-overlay');
    if (!drawer || !overlay) return;
    
    if (show) {
        drawer.style.transform = 'translateX(0)';
        overlay.classList.remove('hidden');
        updateCartCount();
    } else {
        drawer.style.transform = 'translateX(100%)';
        overlay.classList.add('hidden');
    }
};

const applySettings = (settings) => {
    if(!settings) return;
    ensureImagePreconnects(collectImageOrigins(settings));
    
    // Colors
    if (settings.colors) {
        const root = document.documentElement;
        const c = settings.colors;
        if (c.primary_color) root.style.setProperty('--primary-color', c.primary_color);
        if (c.accent_color) root.style.setProperty('--accent-color', c.accent_color);
        if (c.header_icon_color) root.style.setProperty('--header-icon-color', c.header_icon_color);
        const layout = settings.layout || {};
        const fbBg = (c.btn_primary_bg && String(c.btn_primary_bg).trim()) || (c.accent_color && String(c.accent_color).trim()) || '#dc2626';
        const fbTx = (c.btn_primary_text && String(c.btn_primary_text).trim()) || '#ffffff';
        const ocBg = String(layout.orderCallOrderNowBg || '').trim();
        const ocTx = String(layout.orderCallOrderNowText || '').trim();
        root.style.setProperty('--order-call-order-bg', ocBg || fbBg);
        root.style.setProperty('--order-call-order-text', ocTx || fbTx);
    }

    applyTypographyVars(settings);

    const navBar = getEl('bottom-nav-bar');
    if (navBar) {
        const hideBottomNav = settings.layout?.bottomNavEnabled === false || settings.layout?.bottomNavDesign === 'hidden';
        navBar.style.display = hideBottomNav ? 'none' : '';
    }
    
    // Text & Logo
    const topBarText = getEl('top-bar-text');
    if (topBarText) {
        topBarText.innerText = settings.textContent?.topBarText || '';
        if(settings.textContent?.topBarText) getEl('top-bar')?.classList.remove('hidden');
    }
    
    const logoImg = getEl('site-logo-img');
    if (logoImg && settings.logoUrl) logoImg.src = settings.logoUrl;
    renderHomepageFeatures(settings);
    
    // Banner
    if (settings.bannerUrl && doc.singleBanner) {
        const img = doc.singleBanner.querySelector('img');
        if(img) img.src = settings.bannerUrl;
        doc.promoBannerSection?.classList.remove('hidden');
    }
    
    // Footer Info
    if (getEl('about-title')) getEl('about-title').innerText = settings.textContent?.aboutTitle || 'About Us';
    if (getEl('about-description')) getEl('about-description').innerText = settings.textContent?.aboutDescription || '';
    if (getEl('copyright-text')) getEl('copyright-text').innerText = settings.textContent?.copyright || '';
    if (getEl('developer-credit')) getEl('developer-credit').innerHTML = settings.textContent?.developerCredit || '';
    
    // Contact Links
    if (settings.contactInfo) {
        const phoneLink = getEl('product-page-phone');
        if(phoneLink) {
            phoneLink.href = `tel:${settings.contactInfo.phoneNumber}`;
            phoneLink.innerText = settings.contactInfo.phoneNumber;
        }
        const waLink = getEl('product-page-whatsapp');
        if(waLink) {
            waLink.href = `https://wa.me/${settings.contactInfo.whatsappNumber}`;
        }
    }
};

// ============================================================
// 5. INITIALIZATION (CRASH PROOF)
// ============================================================

const onStoreDataRefreshedDefault = () => {
    if (!initialDefaultAtomicRenderCommitted && state.storeCatalogFetchStatus === 'loading') {
        const hasProducts = Array.isArray(state.allProducts) && state.allProducts.length > 0;
        if (!hasProducts) return;
    }
    applySettings(state.siteSettings);
    applyCheckoutAddressMode(state.siteSettings);
    renderProductGrid(state.allProducts);
    renderMobileCategories();
    handleRouter();
    tryDismissBootLoadingOverlay();
    syncDefaultShopAriaBusy();
};

let defaultStoreDataRefreshRaf = 0;
const scheduleStoreDataRefreshedDefault = () => {
    if (defaultStoreDataRefreshRaf) cancelAnimationFrame(defaultStoreDataRefreshRaf);
    defaultStoreDataRefreshRaf = requestAnimationFrame(() => {
        defaultStoreDataRefreshRaf = 0;
        onStoreDataRefreshedDefault();
    });
};

const init = async () => {
    try {
        console.log("Initializing Shop...");
        initDOM();
        applyProductIdQueryParamAsHash();
        document.addEventListener('storeDataRefreshed', scheduleStoreDataRefreshedDefault);

        // Load Data from Core (settings-first + background catalog for instantHome)
        const data = await initCore({ bootMode: 'instantHome' });

        // FAILSAFE: If no data, show error but REMOVE loader
        if (!data) {
            if(doc.productDisplayArea) {
                doc.productDisplayArea.innerHTML = `
                    <div class="text-center py-20">
                        <i class="fa-solid fa-triangle-exclamation text-4xl text-red-500 mb-4"></i>
                        <p class="text-xl font-bold">দোকান লোড করা সম্ভব হয়নি</p>
                        <p class="text-gray-500">ইন্টারনেট সংযোগ চেক করুন অথবা অ্যাডমিন প্যানেল কনফিগার করুন।</p>
                    </div>`;
            }
            throw new Error("Core initialization failed: No data returned.");
        }
        
        const { settings, products, categories } = data;
        
        // Safe Apply
        applySettings(settings);
        applyCheckoutAddressMode(settings);
        renderProductGrid(products);
        renderMobileCategories();
        
        // Initial Route
        handleRouter();
        initialDefaultAtomicRenderCommitted = true;
        tryDismissBootLoadingOverlay();
        syncDefaultShopAriaBusy();

        // --- EVENT LISTENERS ---

        // Routing
        window.addEventListener('hashchange', handleRouter);
        
        // Search
        doc.searchInput?.addEventListener('input', (e) => {
            if(e.target.value.length > 2) {
                window.location.hash = `#/shop?search=${encodeURIComponent(e.target.value)}`;
            }
        });
        
        // Toggles
        document.querySelectorAll('.mobile-menu-toggle').forEach(btn => 
            btn.addEventListener('click', () => toggleMobileNav(true))
        );
        getEl('close-mobile-nav')?.addEventListener('click', () => toggleMobileNav(false));
        doc.mobileNavOverlay?.addEventListener('click', () => toggleMobileNav(false));
        
        document.querySelectorAll('.search-toggle-btn').forEach(btn => 
            btn.addEventListener('click', (e) => { e.preventDefault(); toggleSearch(); })
        );
        getEl('close-search-btn')?.addEventListener('click', toggleSearch);
        
        // Cart Toggles
        document.querySelectorAll('.cart-toggle').forEach(btn =>
            btn.addEventListener('click', (e) => { e.preventDefault(); toggleCartDrawer(true); })
        );
        document.querySelectorAll('.close-modal-btn, #cart-overlay').forEach(el => 
            el?.addEventListener('click', () => toggleCartDrawer(false))
        );
        
        // Cart Actions (Delegated in core, but listening for events here)
        document.addEventListener('cartUpdated', () => updateCartCount());
        
        // Clear Cart
        getEl('clear-cart-btn')?.addEventListener('click', () => {
            state.cartItems = [];
            localStorage.removeItem('sb_cart_items');
            updateCartCount();
        });
        
        // Checkout Button in Cart Drawer
        getEl('checkout-btn')?.addEventListener('click', () => {
            toggleCartDrawer(false);
            window.location.hash = '#/checkout';
            scheduleDefaultRouteSync();
        });

        // Product Detail Actions
        doc.detailAddToCartBtn?.addEventListener('click', (e) => {
            addProductToCart(e.target.dataset.id, e.target.dataset.variantId);
            toggleCartDrawer(true); // Auto open cart
        });
        
        doc.detailOrderBtn?.addEventListener('click', (e) => {
            addProductToCart(e.target.dataset.id, e.target.dataset.variantId, false);
            setTimeout(() => {
                window.location.hash = '#/checkout';
                scheduleDefaultRouteSync();
            }, 100);
        });
        
        // Delegated click: Order + Call style (checkout) vs default card (checkout)
        document.addEventListener('click', (e) => {
            const orderNow = e.target.closest('.product-order-now-btn');
            if (orderNow) {
                e.preventDefault();
                const id = orderNow.dataset.id;
                if (id) {
                    const product = state.allProducts.find(p => String(p.id) === String(id));
                    if (product) {
                        trackPixelEvent('AddToCart', { content_name: product.name, content_ids: [product.id], value: product.salePrice, currency: 'BDT' });
                    }
                    addProductToCart(id, null, false);
                    window.location.hash = '#/checkout';
                    scheduleDefaultRouteSync();
                }
                return;
            }
            const btn = e.target.closest('.product-action-btn');
            if (btn) {
                const id = btn.dataset.id;
                addProductToCart(id, null, false);
                window.location.hash = '#/checkout';
                scheduleDefaultRouteSync();
            }
        });
        
        // Checkout Form
        doc.checkoutForm?.addEventListener('submit', (e) => {
            handleCheckoutSubmit(e);
        });
        
        // Live Input Capture
        ['customer-name', 'customer-phone', 'customer-address'].forEach(id => {
            getEl(id)?.addEventListener('input', (e) => {
                const field = id.replace('customer-', '');
                captureLiveInput(field, e.target.value);
            });
        });
        
        // Shipping Option Selection
        doc.shippingOptionsContainer?.addEventListener('click', (e) => {
            const label = e.target.closest('.shipping-option');
            if (label) {
                document.querySelectorAll('.shipping-option').forEach(el => {
                    el.classList.remove('active');
                    el.classList.remove('bg-red-50');
                    el.classList.remove('border-red-500');
                    el.querySelector('input').checked = false;
                });
                
                label.classList.add('active', 'bg-red-50', 'border-red-500');
                label.querySelector('input').checked = true;
                updateCheckoutSummary();
            }
        });
        
        // Initial Cart UI Update
        updateCartCount();

    } catch (error) {
        console.error("Critical Shop Error:", error);
        tryDismissBootLoadingOverlay({ force: true });
    }
};

// Run
document.addEventListener('DOMContentLoaded', init);