<?php
// Include the secure database connection
require_once 'config.php';

try {
    // Fetch all products
    $stmt = $pdo->query('SELECT id, name, cat, price, oldPrice, img, rating, badge, `desc` FROM products');
    $productsData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Process the image column to decode the JSON array for the frontend
    foreach ($productsData as &$row) {
        $imgs = json_decode($row['img'], true);
        // Ensure it's an array, handle legacy string formats if any
        $row['img_array'] = is_array($imgs) ? $imgs : (!empty($row['img']) ? [$row['img']] : ['img/placeholder.jpg']);
        // Assign the first image as the main display image
        $row['main_img'] = $row['img_array'][0];
    }
    
} catch (\PDOException $e) {
    // In a real scenario, log the error rather than displaying it to the user
    $productsData = [];
    $error = "Failed to load products: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>B-A Home Appliances | Premium Store</title>
    <meta name="description" content="Award-winning premium online marketplace.">
    <link rel="icon" type="image/png" href="img/logo.png">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
    /* =========================================
       VARIABLES & THEME SETUP
       ========================================= */
    :root {
        --primary: #185FA5;
        --primary-hover: #0C447C;
        --color-background-primary: #ffffff;
        --color-background-secondary: #f4f6f8;
        --color-border-secondary: #cbd5e1;
        --color-border-tertiary: #e2e8f0;
        --color-text-primary: #0f172a;
        --color-text-secondary: #64748b;
        --glass-bg: rgba(255, 255, 255, 0.9);
        --shadow-soft: 0 4px 20px rgba(0, 0, 0, 0.03);
        --shadow-hover: 0 12px 32px rgba(24, 95, 165, 0.08);
        --shadow-modal: 0 24px 48px rgba(0, 0, 0, 0.12);
        --radius-sm: 8px;
        --radius-md: 12px;
        --radius-lg: 16px;
        --transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    }

    /* =========================================
       RESET & TYPOGRAPHY
       ========================================= */
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
        background-color: var(--color-background-secondary);
        color: var(--color-text-primary);
        line-height: 1.6;
        overflow-x: hidden;
        -webkit-font-smoothing: antialiased;
    }

    a {
        text-decoration: none;
        color: inherit;
    }

    button {
        cursor: pointer;
        border: none;
        background: none;
        font-family: inherit;
    }

    ul {
        list-style: none;
    }

    /* =========================================
       LOADER ANIMATION
       ========================================= */
    .page-loader {
        position: fixed;
        inset: 0;
        background: var(--color-background-primary);
        z-index: 9999;
        display: flex;
        justify-content: center;
        align-items: center;
        transition: opacity 0.5s ease;
    }

    .page-loader.hidden {
        opacity: 0;
        pointer-events: none;
    }

    .spinner {
        width: 40px;
        height: 40px;
        border: 3px solid var(--color-border-tertiary);
        border-top-color: var(--primary);
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        100% {
            transform: rotate(360deg);
        }
    }

    /* =========================================
       UTILITIES & BUTTONS
       ========================================= */
    .glass {
        background: var(--glass-bg);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(12px);
        border: 1px solid var(--color-border-tertiary);
    }

    .btn-primary {
        background-color: var(--primary);
        color: white;
        padding: 10px 20px;
        border-radius: var(--radius-sm);
        font-weight: 600;
        font-size: 13px;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
    }

    .btn-primary:hover {
        background-color: var(--primary-hover);
        transform: translateY(-2px);
        box-shadow: 0 8px 16px rgba(24, 95, 165, 0.2);
    }

    .btn-outline {
        flex: 1;
        padding: 10px;
        border: 1px solid var(--color-border-secondary);
        background: var(--color-background-primary);
        color: var(--color-text-secondary);
        border-radius: var(--radius-sm);
        font-weight: 600;
        font-size: 13px;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
    }

    .btn-outline:hover {
        background: var(--color-background-secondary);
        color: var(--color-text-primary);
        border-color: var(--color-text-primary);
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(15px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* =========================================
       PREMIUM HEADER & LOGO
       ========================================= */
    header.header-premium {
        position: sticky;
        top: 0;
        z-index: 1000;
        padding: 14px 4%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: var(--glass-bg);
        backdrop-filter: blur(16px);
        -webkit-backdrop-filter: blur(16px);
        border-bottom: 1px solid var(--color-border-tertiary);
        box-shadow: var(--shadow-soft);
    }

    .brand-logo {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .brand-icon {
        height: 36px;
        width: auto;
        object-fit: contain;
    }

    .brand-text {
        display: flex;
        align-items: baseline;
        gap: 8px;
    }

    .text-ba {
        font-size: 2rem;
        font-weight: 900;
        background: linear-gradient(135deg, var(--primary) 0%, #00f2fe 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        letter-spacing: -1px;
        line-height: 1;
    }

    .text-appliances {
        font-size: 0.9rem;
        font-weight: 600;
        color: var(--color-text-secondary);
        text-transform: uppercase;
        letter-spacing: 2px;
    }

    .search-bar {
        flex: 0 1 400px;
        position: relative;
    }

    .search-bar input {
        width: 100%;
        padding: 10px 16px 10px 42px;
        border-radius: 40px;
        border: 1px solid var(--color-border-secondary);
        background: var(--color-background-primary);
        color: var(--color-text-primary);
        outline: none;
        transition: var(--transition);
        font-size: 14px;
    }

    .search-bar i {
        position: absolute;
        left: 16px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--color-text-secondary);
    }

    .search-bar input:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(24, 95, 165, 0.1);
    }

    .nav-icons {
        display: flex;
        gap: 16px;
        align-items: center;
    }

    .icon-btn {
        position: relative;
        font-size: 20px;
        width: 40px;
        height: 40px;
        border-radius: var(--radius-sm);
        display: flex;
        align-items: center;
        justify-content: center;
        transition: var(--transition);
        color: var(--color-text-secondary);
    }

    .icon-btn:hover {
        background: var(--color-background-primary);
        color: var(--primary);
        transform: translateY(-2px);
    }

    .badge-count {
        position: absolute;
        top: -2px;
        right: -2px;
        background: #E24B4A;
        color: white;
        font-size: 10px;
        font-weight: bold;
        padding: 2px 6px;
        border-radius: 50%;
        display: none;
        border: 2px solid var(--color-background-primary);
    }

    /* =========================================
       LAYOUT & SIDEBAR 
       ========================================= */
    .shop-container {
        display: flex;
        padding: 0 4% 60px;
        gap: 30px;
        margin-top: 30px;
        max-width: 1440px;
        margin-inline: auto;
    }

    /* Mobile Filter Toggle */
    .mobile-filter-btn {
        display: none;
        align-items: center;
        gap: 8px;
        padding: 10px 16px;
        background: var(--color-background-primary);
        border: 1px solid var(--color-border-secondary);
        border-radius: var(--radius-sm);
        font-weight: 600;
        color: var(--color-text-primary);
        box-shadow: var(--shadow-soft);
    }

    .filter-overlay {
        position: fixed;
        inset: 0;
        background: rgba(15, 23, 42, 0.4);
        backdrop-filter: blur(4px);
        z-index: 2000;
        opacity: 0;
        pointer-events: none;
        transition: opacity 0.3s ease;
    }

    .filter-overlay.active {
        opacity: 1;
        pointer-events: all;
    }

    .sidebar {
        width: 260px;
        flex-shrink: 0;
        position: sticky;
        top: 90px;
        height: max-content;
    }

    .sidebar-header {
        display: none;
        padding: 20px;
        border-bottom: 1px solid var(--color-border-tertiary);
        justify-content: space-between;
        align-items: center;
    }

    .sidebar-header h2 {
        font-size: 18px;
    }

    .close-filter {
        font-size: 20px;
        color: var(--color-text-secondary);
    }

    .filter-group {
        margin-bottom: 24px;
        padding: 20px;
        border-radius: var(--radius-md);
        background: var(--color-background-primary);
        border: 1px solid var(--color-border-tertiary);
        box-shadow: var(--shadow-soft);
    }

    .filter-group h3 {
        margin-bottom: 16px;
        font-size: 13px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 1px;
        color: var(--color-text-secondary);
    }

    .filter-label {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 8px 12px;
        margin-bottom: 4px;
        border-radius: 8px;
        cursor: pointer;
        transition: var(--transition);
        font-size: 14px;
        color: var(--color-text-secondary);
        font-weight: 500;
    }

    .filter-label:hover {
        background: var(--color-background-secondary);
        color: var(--color-text-primary);
    }

    .filter-label input[type="checkbox"] {
        accent-color: var(--primary);
        width: 16px;
        height: 16px;
    }

    /* =========================================
       PRODUCT GRID & CARDS
       ========================================= */
    .main-content {
        flex: 1;
        min-width: 0;
    }

    .controls-bar {
        display: flex;
        justify-content: space-between;
        margin-bottom: 24px;
        align-items: center;
        padding-bottom: 16px;
        border-bottom: 1px solid var(--color-border-tertiary);
    }

    .controls-bar p {
        font-size: 14px;
        color: var(--color-text-secondary);
    }

    .controls-bar strong {
        color: var(--color-text-primary);
        font-size: 15px;
    }

    .sort-select {
        padding: 8px 16px;
        font-size: 14px;
        font-weight: 500;
        border-radius: var(--radius-sm);
        border: 1px solid var(--color-border-secondary);
        background: var(--color-background-primary);
        color: var(--color-text-primary);
        outline: none;
        cursor: pointer;
    }

    .grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
        gap: 24px;
    }

    .product-card {
        background: var(--color-background-primary);
        border: 1px solid var(--color-border-tertiary);
        border-radius: var(--radius-lg);
        padding: 16px;
        transition: var(--transition);
        position: relative;
        display: flex;
        flex-direction: column;
        animation: fadeIn 0.4s ease-out;
    }

    .product-card:hover {
        transform: translateY(-4px);
        box-shadow: var(--shadow-hover);
        border-color: var(--primary);
    }

    .product-img-wrapper {
        position: relative;
        width: 100%;
        height: 200px;
        border-radius: var(--radius-sm);
        overflow: hidden;
        margin-bottom: 16px;
        background: var(--color-background-secondary);
        cursor: pointer;
    }

    /* Card Carousel Styles */
    .card-slider {
        position: relative;
        width: 100%;
        height: 100%;
    }

    .card-slider .slide-img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
        opacity: 0;
        transition: opacity 0.4s ease, transform 0.5s ease;
    }

    .card-slider .slide-img.active {
        opacity: 1;
        position: relative;
    }

    .product-card:hover .card-slider .slide-img.active {
        transform: scale(1.05);
    }

    .slide-btn {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        background: var(--glass-bg);
        color: var(--color-text-primary);
        border: none;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: var(--transition);
        z-index: 10;
        box-shadow: var(--shadow-soft);
    }

    .product-card:hover .slide-btn {
        opacity: 1;
    }

    .slide-btn:hover {
        background: var(--primary);
        color: white;
    }

    .slide-btn.left {
        left: 8px;
    }

    .slide-btn.right {
        right: 8px;
    }

    .slide-dots {
        position: absolute;
        bottom: 8px;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        gap: 5px;
        z-index: 10;
    }

    .slide-dots .dot {
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background: rgba(0, 0, 0, 0.2);
        transition: var(--transition);
    }

    .slide-dots .dot.active {
        background: var(--primary);
        transform: scale(1.3);
    }

    .badge {
        position: absolute;
        top: 10px;
        left: 10px;
        background: #E24B4A;
        color: white;
        padding: 4px 10px;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 700;
        z-index: 15;
        letter-spacing: 0.5px;
    }

    .wishlist-btn {
        position: absolute;
        top: 10px;
        right: 10px;
        background: var(--color-background-primary);
        border: 1px solid var(--color-border-tertiary);
        border-radius: 50%;
        width: 36px;
        height: 36px;
        display: grid;
        place-items: center;
        z-index: 15;
        color: var(--color-text-secondary);
        transition: var(--transition);
        font-size: 16px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    }

    .wishlist-btn:hover,
    .wishlist-btn.active {
        color: #E24B4A;
        border-color: #E24B4A;
        transform: scale(1.1);
    }

    .product-category {
        font-size: 11px;
        color: var(--color-text-secondary);
        text-transform: uppercase;
        letter-spacing: 1px;
        font-weight: 600;
    }

    .product-title {
        font-size: 15px;
        font-weight: 600;
        margin: 6px 0;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        cursor: pointer;
    }

    .stars {
        color: #BA7517;
        font-size: 12px;
        margin-bottom: 8px;
        display: flex;
        gap: 2px;
    }

    .product-price {
        font-size: 18px;
        font-weight: 700;
        color: var(--primary);
        margin-top: auto;
    }

    .old-price {
        text-decoration: line-through;
        color: var(--color-text-secondary);
        font-size: 13px;
        margin-left: 8px;
        font-weight: normal;
    }

    .card-actions {
        margin-top: 16px;
        display: flex;
        gap: 8px;
    }

    /* =========================================
       PAGINATION
       ========================================= */
    .pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 8px;
        margin-top: 40px;
    }

    .page-btn {
        width: 36px;
        height: 36px;
        border-radius: var(--radius-sm);
        border: 1px solid var(--color-border-secondary);
        background: var(--color-background-primary);
        color: var(--color-text-primary);
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: var(--transition);
    }

    .page-btn:hover:not(:disabled) {
        border-color: var(--primary);
        color: var(--primary);
    }

    .page-btn.active {
        background: var(--primary);
        color: white;
        border-color: var(--primary);
    }

    .page-btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
        background: var(--color-background-secondary);
    }

    /* =========================================
       MODAL (QUICK VIEW)
       ========================================= */
    .modal-overlay {
        position: fixed;
        inset: 0;
        background: rgba(0, 0, 0, 0.4);
        backdrop-filter: blur(4px);
        z-index: 3000;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        pointer-events: none;
        transition: opacity 0.3s;
    }

    .modal-overlay.active {
        opacity: 1;
        pointer-events: all;
    }

    .modal-content {
        background: var(--color-background-primary);
        width: 90%;
        max-width: 850px;
        max-height: 85vh;
        overflow-y: auto;
        border-radius: var(--radius-lg);
        display: grid;
        grid-template-columns: 1fr 1fr;
        border: 1px solid var(--color-border-tertiary);
        transform: translateY(30px);
        transition: transform 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        box-shadow: var(--shadow-modal);
    }

    .modal-overlay.active .modal-content {
        transform: translateY(0);
    }

    .modal-gallery {
        display: flex;
        flex-direction: column;
        padding: 24px;
        gap: 16px;
    }

    .modal-gallery-main {
        width: 100%;
        height: 350px;
        border-radius: var(--radius-md);
        background: var(--color-background-secondary);
        overflow: hidden;
    }

    .modal-gallery-main img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: opacity 0.3s ease;
    }

    .modal-gallery-thumbs {
        display: flex;
        gap: 12px;
        overflow-x: auto;
        padding-bottom: 8px;
    }

    .thumb-img {
        width: 70px;
        height: 70px;
        border-radius: var(--radius-sm);
        object-fit: cover;
        cursor: pointer;
        border: 2px solid transparent;
        opacity: 0.6;
        transition: var(--transition);
        flex-shrink: 0;
    }

    .thumb-img:hover,
    .thumb-img.active {
        opacity: 1;
        border-color: var(--primary);
    }

    .modal-details {
        padding: 32px 32px 32px 0;
        position: relative;
    }

    .close-modal {
        position: absolute;
        top: 16px;
        right: 16px;
        width: 36px;
        height: 36px;
        border-radius: var(--radius-sm);
        font-size: 20px;
        color: var(--color-text-secondary);
        background: var(--color-background-secondary);
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .close-modal:hover {
        color: var(--color-text-primary);
        transform: rotate(90deg);
    }

    .modal-details h2 {
        font-size: 24px;
        margin: 8px 0;
        line-height: 1.2;
    }

    .modal-details .price {
        font-size: 26px;
        color: var(--primary);
        font-weight: 700;
        margin: 12px 0;
    }

    .modal-details p {
        color: var(--color-text-secondary);
        margin-bottom: 20px;
        font-size: 14px;
        line-height: 1.6;
    }

    .perk-list {
        margin-bottom: 24px;
        color: var(--color-text-secondary);
        font-size: 13px;
        font-weight: 500;
        display: flex;
        flex-direction: column;
        gap: 8px;
        border-top: 1px solid var(--color-border-tertiary);
        padding-top: 20px;
    }

    .perk-list li {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .perk-list i {
        color: var(--primary);
        font-size: 16px;
        width: 20px;
        text-align: center;
    }

    /* =========================================
       CART UI & TOASTS
       ========================================= */
    .cart-overlay {
        position: fixed;
        inset: 0;
        background: rgba(15, 23, 42, 0.4);
        backdrop-filter: blur(4px);
        z-index: 3000;
        opacity: 0;
        pointer-events: none;
        transition: opacity 0.4s ease;
    }

    .cart-overlay.active {
        opacity: 1;
        pointer-events: all;
    }

    .cart-sidebar {
        position: fixed;
        top: 0;
        right: -450px;
        width: 420px;
        max-width: 100%;
        height: 100vh;
        background: var(--color-background-primary);
        box-shadow: -10px 0 40px rgba(0, 0, 0, 0.1);
        z-index: 3001;
        transition: right 0.4s cubic-bezier(0.16, 1, 0.3, 1);
        display: flex;
        flex-direction: column;
        border-top-left-radius: 24px;
        border-bottom-left-radius: 24px;
    }

    .cart-sidebar.active {
        right: 0;
    }

    .cart-header {
        padding: 24px;
        border-bottom: 1px solid var(--color-border-tertiary);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .cart-header h2 {
        font-size: 20px;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .close-cart {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: var(--color-background-secondary);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
    }

    .cart-items {
        flex: 1;
        overflow-y: auto;
        padding: 24px;
        display: flex;
        flex-direction: column;
        gap: 16px;
    }

    .cart-item {
        display: flex;
        gap: 16px;
        align-items: center;
        padding: 16px;
        background: var(--color-background-secondary);
        border-radius: var(--radius-md);
        border: 1px solid transparent;
    }

    .cart-item img {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: var(--radius-sm);
        border: 1px solid var(--color-border-tertiary);
    }

    .cart-item-info {
        flex: 1;
    }

    .cart-item-title {
        font-size: 14px;
        font-weight: 600;
        margin-bottom: 6px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .cart-item-price {
        color: var(--primary);
        font-weight: 700;
        font-size: 16px;
    }

    .cart-item-qty {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-top: 10px;
        background: var(--color-background-primary);
        width: max-content;
        border-radius: 20px;
        border: 1px solid var(--color-border-secondary);
        padding: 2px 4px;
    }

    .qty-btn {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
    }

    .remove-btn {
        color: var(--color-text-secondary);
        font-size: 18px;
        padding: 8px;
        background: transparent;
    }

    .remove-btn:hover {
        color: #E24B4A;
    }

    .cart-footer {
        padding: 24px;
        background: var(--color-background-primary);
        border-top: 1px solid var(--color-border-tertiary);
    }

    .cart-total {
        display: flex;
        justify-content: space-between;
        font-size: 18px;
        font-weight: 700;
        margin-bottom: 20px;
    }

    .btn-checkout {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        width: 100%;
        background: var(--primary);
        color: white;
        padding: 16px;
        border-radius: var(--radius-md);
        font-weight: 600;
        font-size: 16px;
    }

    .toast-container {
        position: fixed;
        bottom: 24px;
        right: 24px;
        z-index: 9999;
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .toast {
        background: var(--color-text-primary);
        color: var(--color-background-primary);
        padding: 14px 20px;
        border-radius: var(--radius-sm);
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 500;
        font-size: 14px;
        animation: slideInRight 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
        transition: opacity 0.3s, transform 0.3s;
    }

    .toast i {
        font-size: 18px;
        color: var(--primary);
    }

    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }

        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    /* =========================================
       MOBILE RESPONSIVENESS
       ========================================= */
    @media (max-width: 1024px) {
        .shop-container {
            flex-direction: column;
            gap: 20px;
            margin-top: 15px;
        }

        .controls-bar {
            flex-wrap: wrap;
            gap: 15px;
        }

        .mobile-filter-btn {
            display: flex;
        }

        /* Sidebar becomes slide-in */
        .sidebar {
            position: fixed;
            top: 0;
            left: -100%;
            width: 320px;
            height: 100vh;
            background: var(--color-background-primary);
            z-index: 2001;
            padding: 0;
            overflow-y: auto;
            transition: left 0.4s ease;
            box-shadow: 10px 0 30px rgba(0, 0, 0, 0.1);
        }

        .sidebar.active {
            left: 0;
        }

        .sidebar-header {
            display: flex;
        }

        .filter-group {
            border: none;
            box-shadow: none;
            border-bottom: 1px solid var(--color-border-tertiary);
            border-radius: 0;
            margin-bottom: 0;
        }
    }

    @media (max-width: 768px) {
        header.header-premium {
            flex-wrap: wrap;
            gap: 12px;
            padding: 12px 4%;
        }

        .search-bar {
            order: 3;
            flex: 1 1 100%;
        }

        /* Strict 2 items per row on mobile */
        .grid {
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
        }

        .product-card {
            padding: 10px;
        }

        .product-img-wrapper {
            height: 130px;
            margin-bottom: 10px;
        }

        .product-title {
            font-size: 13px;
            margin: 4px 0;
        }

        .product-price {
            font-size: 15px;
        }

        .card-actions {
            flex-direction: column;
            margin-top: 10px;
            gap: 6px;
        }

        .btn-outline,
        .btn-primary {
            padding: 8px;
            font-size: 12px;
        }

        .wishlist-btn {
            width: 30px;
            height: 30px;
            font-size: 14px;
        }

        .badge {
            font-size: 9px;
            padding: 3px 6px;
        }

        .modal-content {
            grid-template-columns: 1fr;
        }

        .modal-details {
            padding: 24px;
        }

        .cart-sidebar {
            width: 100%;
            right: -100%;
            border-radius: 0;
        }
    }
    </style>
</head>

<body>
    <div class="page-loader" id="pageLoader">
        <div class="spinner"></div>
    </div>

    <header class="header-premium">
        <a href="index.php" class="brand-logo">
            <i class="fa-solid fa-layer-group" style="font-size: 28px; color: var(--primary);"></i>
            <div class="brand-text">
                <span class="text-ba">B-A</span>
                <span class="text-appliances">appliances.</span>
            </div>
        </a>

        <div class="search-bar">
            <i class="fa-solid fa-magnifying-glass"></i>
            <input type="text" id="searchInput" placeholder="Search premium products..." aria-label="Search">
        </div>

        <nav class="nav-icons">
            <a href="wishlist.php" class="icon-btn" aria-label="Wishlist">
                <i class="fa-regular fa-heart"></i>
                <span class="badge-count" id="wishlistBadge">0</span>
            </a>
            <button class="icon-btn" id="cartToggleBtn" aria-label="Shopping Cart">
                <i class="fa-solid fa-cart-shopping"></i>
                <span class="badge-count" id="cartBadge">0</span>
            </button>
            <button class="icon-btn" aria-label="Profile">
                <i class="fa-regular fa-user"></i>
            </button>
        </nav>
    </header>

    <main class="shop-container" id="shop">
        <div class="filter-overlay" id="filterOverlay"></div>

        <aside class="sidebar" id="mobileSidebar">
            <div class="sidebar-header">
                <h2><i class="fa-solid fa-sliders"></i> Filters</h2>
                <button class="close-filter" id="closeFilterBtn"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <div class="filter-group">
                <h3><i class="fa-solid fa-layer-group"></i> Categories</h3>
                <label class="filter-label"><input type="checkbox" class="category-filter" value="All" checked> All
                    Products</label>
                <label class="filter-label"><input type="checkbox" class="category-filter" value="Furniture">
                    Furniture</label>
                <label class="filter-label"><input type="checkbox" class="category-filter" value="Electronics">
                    Electronics</label>
                <label class="filter-label"><input type="checkbox" class="category-filter" value="Garden"> Garden &
                    Tools</label>
                <label class="filter-label"><input type="checkbox" class="category-filter" value="Appliances">
                    Appliances</label>
            </div>
            <div class="filter-group">
                <h3><i class="fa-solid fa-tag"></i> Price Range</h3>
                <input type="range" id="priceRange" min="0" max="2000" value="2000"
                    style="width: 100%; accent-color: var(--primary);">
                <p style="margin-top: 10px; color: var(--color-text-secondary); font-weight: 500; font-size: 13px;">Up
                    to: $<span id="priceValue">2000</span></p>
            </div>
        </aside>

        <section class="main-content">
            <div class="controls-bar">
                <button class="mobile-filter-btn" id="openFilterBtn">
                    <i class="fa-solid fa-sliders"></i> Filters
                </button>
                <p><strong id="productCount">0</strong> premium products</p>
                <?php if(isset($error)): ?>
                <p style="color: #E24B4A; font-weight: bold;"><?php echo $error; ?></p>
                <?php endif; ?>
                <select class="sort-select" id="sortSelect" aria-label="Sort products">
                    <option value="newest">Sort by: Newest Arrivals</option>
                    <option value="price-low">Price: Low to High</option>
                    <option value="price-high">Price: High to Low</option>
                    <option value="rating">Best Rated</option>
                </select>
            </div>

            <div class="grid" id="productGrid"></div>

            <div class="pagination" id="paginationContainer"></div>
        </section>
    </main>

    <div class="modal-overlay" id="productModal" role="dialog" aria-modal="true">
        <div class="modal-content">
            <div class="modal-gallery">
                <div class="modal-gallery-main"><img id="modalImgMain" src="" alt="Product Main Image"></div>
                <div class="modal-gallery-thumbs" id="modalImgThumbs"></div>
            </div>
            <div class="modal-details">
                <button class="close-modal" id="closeModal" aria-label="Close modal"><i
                        class="fa-solid fa-xmark"></i></button>
                <span class="product-category" id="modalCat"></span>
                <h2 id="modalTitle"></h2>
                <div class="price">$<span id="modalPrice"></span><span class="old-price" id="modalOldPrice"></span>
                </div>
                <p id="modalDesc"></p>
                <ul class="perk-list">
                    <li><i class="fa-solid fa-truck-fast"></i> Free 2-day shipping</li>
                    <li><i class="fa-solid fa-shield-halved"></i> 1 Year Premium Warranty</li>
                    <li><i class="fa-solid fa-rotate-left"></i> 30-Day Return Policy</li>
                </ul>
                <div style="display: flex; gap: 12px; margin-top: 15px;">
                    <button class="btn-primary" id="modalAddToCart" style="flex: 2;"><i
                            class="fa-solid fa-cart-plus"></i> Add to Cart</button>
                    <button class="btn-outline" id="modalBuyNow" style="flex: 1;"><i class="fa-solid fa-bolt"></i>
                        Buy</button>
                    <button class="btn-outline" id="modalShare" style="flex: 1;" title="Share Product"><i
                            class="fa-solid fa-share-nodes"></i></button>
                </div>
            </div>
        </div>
    </div>

    <div class="cart-overlay" id="cartOverlay"></div>
    <div class="cart-sidebar" id="cartSidebar">
        <div class="cart-header">
            <h2><i class="fa-solid fa-bag-shopping"></i> Shopping Cart</h2>
            <button class="close-cart" id="closeCartBtn"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <div class="cart-items" id="cartItemsContainer"></div>
        <div class="cart-footer">
            <div class="cart-total"><span>Subtotal</span><span id="cartTotalValue">$0.00</span></div>
            <a href="checkout.php" class="btn-checkout"><i class="fa-solid fa-lock"></i> Secure Checkout</a>
        </div>
    </div>

    <div class="toast-container" id="toastContainer"></div>

    <script>
    // Remove loader when page is ready
    window.addEventListener('load', () => {
        setTimeout(() => document.getElementById('pageLoader').classList.add('hidden'), 400);
    });

    // --- DATA LAYER ---
    const products =
        <?php echo json_encode($productsData, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>;
    products.forEach(p => {
        p.price = parseFloat(p.price);
        p.oldPrice = parseFloat(p.oldPrice);
        p.rating = parseInt(p.rating);
    });

    // --- STATE MANAGEMENT ---
    let cart = JSON.parse(localStorage.getItem('homepro_cart')) || [];
    let wishlist = JSON.parse(localStorage.getItem('homepro_wishlist')) || [];
    let activeFilters = {
        category: ['All'],
        search: '',
        maxPrice: 2000,
        sort: 'newest'
    };

    // Pagination State
    let currentPage = 1;
    const itemsPerPage = 8; // Adjust items per page here

    // --- UTILITIES ---
    const saveCart = () => localStorage.setItem('homepro_cart', JSON.stringify(cart));
    const saveWishlist = () => localStorage.setItem('homepro_wishlist', JSON.stringify(wishlist));
    const formatPrice = (price) => Number(price).toFixed(2);

    function showToast(message, icon = "fa-check") {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.innerHTML = `<i class="fa-solid ${icon}"></i> <span>${message}</span>`;
        container.appendChild(toast);
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    function updateBadges() {
        const cBadge = document.getElementById('cartBadge');
        const wBadge = document.getElementById('wishlistBadge');
        const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
        if (cBadge) {
            cBadge.innerText = totalItems;
            cBadge.style.display = totalItems > 0 ? 'flex' : 'none';
        }
        if (wBadge) {
            wBadge.innerText = wishlist.length;
            wBadge.style.display = wishlist.length > 0 ? 'flex' : 'none';
        }
    }

    // --- MOBILE FILTER UI LOGIC ---
    const mobileSidebar = document.getElementById('mobileSidebar');
    const filterOverlay = document.getElementById('filterOverlay');
    const openFilterBtn = document.getElementById('openFilterBtn');
    const closeFilterBtn = document.getElementById('closeFilterBtn');

    function toggleFilters() {
        mobileSidebar.classList.toggle('active');
        filterOverlay.classList.toggle('active');
    }
    openFilterBtn.addEventListener('click', toggleFilters);
    closeFilterBtn.addEventListener('click', toggleFilters);
    filterOverlay.addEventListener('click', toggleFilters);

    // --- RENDER GRID & PAGINATION ---
    const grid = document.getElementById('productGrid');
    const paginationContainer = document.getElementById('paginationContainer');

    window.changeSlide = (btn, direction) => {
        const sliderWrapper = btn.closest('.card-slider');
        const images = sliderWrapper.querySelectorAll('.slide-img');
        const dots = sliderWrapper.querySelectorAll('.dot');
        let activeIdx = Array.from(images).findIndex(img => img.classList.contains('active'));
        images[activeIdx].classList.remove('active');
        if (dots.length) dots[activeIdx].classList.remove('active');
        activeIdx = (activeIdx + direction + images.length) % images.length;
        images[activeIdx].classList.add('active');
        if (dots.length) dots[activeIdx].classList.add('active');
    };

    function renderPagination(totalItems) {
        paginationContainer.innerHTML = '';
        const totalPages = Math.ceil(totalItems / itemsPerPage);
        if (totalPages <= 1) return;

        // Prev Button
        const prevBtn = document.createElement('button');
        prevBtn.className = 'page-btn';
        prevBtn.innerHTML = '<i class="fa-solid fa-chevron-left"></i>';
        prevBtn.disabled = currentPage === 1;
        prevBtn.onclick = () => {
            currentPage--;
            renderProducts();
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        };
        paginationContainer.appendChild(prevBtn);

        // Page Numbers
        for (let i = 1; i <= totalPages; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `page-btn ${currentPage === i ? 'active' : ''}`;
            pageBtn.innerText = i;
            pageBtn.onclick = () => {
                currentPage = i;
                renderProducts();
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            };
            paginationContainer.appendChild(pageBtn);
        }

        // Next Button
        const nextBtn = document.createElement('button');
        nextBtn.className = 'page-btn';
        nextBtn.innerHTML = '<i class="fa-solid fa-chevron-right"></i>';
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.onclick = () => {
            currentPage++;
            renderProducts();
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        };
        paginationContainer.appendChild(nextBtn);
    }

    function renderProducts() {
        let filtered = products.filter(p => {
            const matchCat = activeFilters.category.includes('All') || activeFilters.category.includes(p.cat);
            const matchSearch = p.name.toLowerCase().includes(activeFilters.search.toLowerCase());
            const matchPrice = p.price <= activeFilters.maxPrice;
            return matchCat && matchSearch && matchPrice;
        });

        if (activeFilters.sort === 'price-low') filtered.sort((a, b) => a.price - b.price);
        else if (activeFilters.sort === 'price-high') filtered.sort((a, b) => b.price - a.price);
        else if (activeFilters.sort === 'rating') filtered.sort((a, b) => b.rating - a.rating);

        document.getElementById('productCount').innerText = filtered.length;
        grid.innerHTML = '';

        if (filtered.length === 0) {
            grid.innerHTML =
                '<p style="grid-column: 1/-1; text-align: center; color: var(--color-text-secondary); padding: 40px;"><i class="fa-solid fa-box-open" style="font-size: 40px; display:block; margin-bottom:10px;"></i>No products found.</p>';
            paginationContainer.innerHTML = '';
            return;
        }

        // Pagination Slice
        const startIndex = (currentPage - 1) * itemsPerPage;
        const paginatedItems = filtered.slice(startIndex, startIndex + itemsPerPage);

        paginatedItems.forEach(p => {
            const isWished = wishlist.includes(p.id);
            let imageContentHTML = '';
            if (p.img_array && p.img_array.length > 1) {
                let imgTags = p.img_array.map((src, i) =>
                    `<img src="${src}" class="slide-img ${i === 0 ? 'active' : ''}" loading="lazy" alt="${p.name}">`
                ).join('');
                let dotsHTML = p.img_array.map((_, i) => `<span class="dot ${i === 0 ? 'active' : ''}"></span>`)
                    .join('');
                imageContentHTML =
                    `<div class="card-slider">${imgTags}<button class="slide-btn left" onclick="event.stopPropagation(); changeSlide(this, -1)"><i class="fa-solid fa-chevron-left"></i></button><button class="slide-btn right" onclick="event.stopPropagation(); changeSlide(this, 1)"><i class="fa-solid fa-chevron-right"></i></button><div class="slide-dots">${dotsHTML}</div></div>`;
            } else {
                imageContentHTML =
                    `<img src="${p.main_img}" alt="${p.name}" loading="lazy" style="width:100%; height:100%; object-fit:cover; transition: transform 0.5s;">`;
            }

            const card = document.createElement('article');
            card.className = 'product-card';
            card.innerHTML = `
              <div class="product-img-wrapper" onclick="openModal(${p.id})">
                ${p.badge ? `<span class="badge">${p.badge}</span>` : ''}
                <button class="wishlist-btn ${isWished ? 'active' : ''}" onclick="event.stopPropagation(); toggleWishlist(${p.id})"><i class="${isWished ? 'fa-solid fa-heart' : 'fa-regular fa-heart'}"></i></button>
                ${imageContentHTML}
              </div>
              <span class="product-category">${p.cat}</span>
              <h3 class="product-title" onclick="openModal(${p.id})">${p.name}</h3>
              <div class="stars">${'<i class="fa-solid fa-star"></i>'.repeat(p.rating)}${'<i class="fa-regular fa-star"></i>'.repeat(5 - p.rating)}</div>
              <div class="product-price">$${formatPrice(p.price)} ${p.oldPrice > 0 ? `<span class="old-price">$${formatPrice(p.oldPrice)}</span>` : ''}</div>
              <div class="card-actions">
                <button class="btn-outline" onclick="openModal(${p.id})"><i class="fa-regular fa-eye"></i> View</button>
                <button class="btn-primary" onclick="addToCart(${p.id})"><i class="fa-solid fa-cart-plus"></i> Add</button>
              </div>
            `;
            grid.appendChild(card);
        });

        renderPagination(filtered.length);
    }

    // Filter event listeners trigger page 1 reset
    document.getElementById('searchInput').addEventListener('input', (e) => {
        activeFilters.search = e.target.value;
        currentPage = 1;
        renderProducts();
    });
    document.getElementById('priceRange').addEventListener('input', (e) => {
        activeFilters.maxPrice = e.target.value;
        document.getElementById('priceValue').innerText = e.target.value;
        currentPage = 1;
        renderProducts();
    });
    document.getElementById('sortSelect').addEventListener('change', (e) => {
        activeFilters.sort = e.target.value;
        currentPage = 1;
        renderProducts();
    });
    document.querySelectorAll('.category-filter').forEach(cb => cb.addEventListener('change', () => {
        activeFilters.category = Array.from(document.querySelectorAll('.category-filter')).filter(c => c
            .checked).map(c => c.value);
        if (activeFilters.category.length === 0) activeFilters.category = ['All'];
        currentPage = 1;
        renderProducts();
    }));

    // --- MODAL LOGIC (Untouched, Quick View Setup) ---
    const modal = document.getElementById('productModal');
    window.openModal = (id) => {
        const p = products.find(x => x.id === id);
        if (!p) return;
        document.getElementById('modalCat').innerText = p.cat;
        document.getElementById('modalTitle').innerText = p.name;
        document.getElementById('modalPrice').innerText = formatPrice(p.price);
        document.getElementById('modalOldPrice').innerText = p.oldPrice > 0 ? `$${formatPrice(p.oldPrice)}` : '';
        document.getElementById('modalDesc').innerText = p.desc;

        const mainImgEl = document.getElementById('modalImgMain');
        const thumbsContainer = document.getElementById('modalImgThumbs');
        mainImgEl.src = p.main_img;
        thumbsContainer.innerHTML = '';

        if (p.img_array && p.img_array.length > 1) {
            p.img_array.forEach((imgUrl, index) => {
                const thumb = document.createElement('img');
                thumb.src = imgUrl;
                thumb.className = `thumb-img ${index === 0 ? 'active' : ''}`;
                thumb.onclick = () => {
                    mainImgEl.style.opacity = 0;
                    setTimeout(() => {
                        mainImgEl.src = imgUrl;
                        mainImgEl.style.opacity = 1;
                    }, 150);
                    document.querySelectorAll('.thumb-img').forEach(t => t.classList.remove('active'));
                    thumb.classList.add('active');
                };
                thumbsContainer.appendChild(thumb);
            });
        }
        document.getElementById('modalAddToCart').onclick = () => {
            addToCart(p.id);
            modal.classList.remove('active');
        };
        modal.classList.add('active');
    };

    document.getElementById('closeModal').addEventListener('click', () => modal.classList.remove('active'));
    modal.addEventListener('click', (e) => {
        if (e.target === modal) modal.classList.remove('active');
    });

    // --- CART UI ---
    const cartSidebar = document.getElementById('cartSidebar');
    const cartOverlay = document.getElementById('cartOverlay');

    function toggleCartUI() {
        cartSidebar.classList.toggle('active');
        cartOverlay.classList.toggle('active');
        renderCartUI();
    }
    document.getElementById('cartToggleBtn').addEventListener('click', toggleCartUI);
    document.getElementById('closeCartBtn').addEventListener('click', toggleCartUI);
    cartOverlay.addEventListener('click', toggleCartUI);

    function renderCartUI() {
        const container = document.getElementById('cartItemsContainer');
        let total = 0;
        container.innerHTML = '';
        if (cart.length === 0) {
            container.innerHTML =
                `<div style="text-align:center; padding: 40px 20px; color:var(--color-text-secondary); margin-top: auto; margin-bottom: auto;"><i class="fa-solid fa-cart-arrow-down" style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;"></i><h3 style="color: var(--color-text-primary); margin-bottom: 8px;">Your cart is empty</h3></div>`;
        } else {
            cart.forEach(item => {
                total += item.price * item.quantity;
                container.innerHTML += `
                <div class="cart-item">
                  <img src="${item.main_img}" alt="${item.name}">
                  <div class="cart-item-info">
                    <div class="cart-item-title">${item.name}</div>
                    <div class="cart-item-price">$${formatPrice(item.price)}</div>
                    <div class="cart-item-qty">
                      <button class="qty-btn" onclick="updateQty(${item.id}, -1)"><i class="fa-solid fa-minus" style="font-size: 10px;"></i></button>
                      <span style="font-size: 13px; font-weight: 600; width: 20px; text-align: center;">${item.quantity}</span>
                      <button class="qty-btn" onclick="updateQty(${item.id}, 1)"><i class="fa-solid fa-plus" style="font-size: 10px;"></i></button>
                    </div>
                  </div>
                  <button class="remove-btn" onclick="updateQty(${item.id}, -${item.quantity})" title="Remove Item"><i class="fa-solid fa-trash-can"></i></button>
                </div>`;
            });
        }
        document.getElementById('cartTotalValue').innerText = `$${formatPrice(total)}`;
    }

    window.updateQty = (id, delta) => {
        const item = cart.find(i => i.id === id);
        if (item) {
            item.quantity += delta;
            if (item.quantity <= 0) cart = cart.filter(i => i.id !== id);
            saveCart();
            updateBadges();
            renderCartUI();
        }
    };

    window.addToCart = (id) => {
        const product = products.find(p => p.id === id);
        const existingItem = cart.find(item => item.id === id);
        if (existingItem) existingItem.quantity += 1;
        else cart.push({
            ...product,
            quantity: 1
        });
        saveCart();
        updateBadges();
        renderCartUI();
        if (!cartSidebar.classList.contains('active')) toggleCartUI();
    };

    window.toggleWishlist = (id) => {
        const index = wishlist.indexOf(id);
        if (index > -1) {
            wishlist.splice(index, 1);
            showToast("Removed from Wishlist", "fa-heart-crack");
        } else {
            wishlist.push(id);
            showToast("Added to Wishlist", "fa-heart");
        }
        saveWishlist();
        updateBadges();
        renderProducts();
    };

    // --- INIT ---
    renderProducts();
    updateBadges();
    </script>
</body>

</html>