import React, { useEffect, useMemo, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import './styles.css';
import productsCatalog from './products_data.json';
import postsCatalog from './posts_data.json';

const media = 'https://muyecncar.com/wp-content/uploads';

const images = {
  logo: '/banner/logo.png',
  heroBanner: '/banner/banner-1.webp',
  neptrCard: '/banner/4-neptr.webp',
  neptCard: '/banner/12.webp',
  moreCard: '/banner/13.webp',
  contactBg: '/banner/contact-bg.webp',
  products: [
    ['Armed A pillar mechanical handle', '/products/handle-1.jpg', '/products/handle-2.jpg', '$249.00', '$269.00', 'more-series'],
    ['Armed blind area sandboard mirror', '/products/mirror-1.jpg', '/products/mirror-2.jpg', '$189.00', '$229.00', 'more-series'],
    ['Armed carbon fiber handlebars', '/products/carbon-1.jpg', '/products/carbon-2.jpg', '$220.00', '$238.00', 'more-series'],
    ['Armed tail lamp shade', '/products/taillamp-1.jpg', '/products/taillamp-2.jpg', '$309.00', '$329.00', 'more-series'],
    ['Multi-function rearview mirror rain shield', '/products/rainshield-1.jpg', '/products/rainshield-2.jpg', '$319.00', '$349.00', 'more-series'],
    ['MUYE INDUSTRY GWM TANK key case', '/products/keycase-1.jpg', '/products/keycase-2.jpg', '$79.00', '$99.00', 'more-series'],
  ],
  testimonials: [
    {
      author: 'US. MARTIN',
      image: '/testimonials/testimonial-car-1.jpg',
      quote: 'The craftsmanship of these products is evident in every detail. The materials used are of the highest quality, ensuring durability and reliability. The designs are innovative and eye-catching, making your off-roader stand out from the crowd.',
    },
    {
      author: 'AU. LUCAS',
      image: '/testimonials/testimonial-car-2.jpg',
      quote: 'The quality of these products is superb. The materials are robust and built to last, capable of withstanding the toughest off-roading challenges. The design is a perfect blend of style and functionality. It gives the vehicle a bold and attractive look while enhancing its performance on and off the road.',
    },
    {
      author: 'FR. JUSTIN LU',
      image: '/testimonials/testimonial-car-3.jpg',
      quote: 'The installation process is user-friendly, with clear instructions that make it easy to get the modifications done right. The suspension upgrades from these brands offer an incredibly smooth ride, ensuring comfort even on the roughest terrains. The larger tires provide excellent traction and stability, giving you the confidence to take on any obstacle',
    },
    {
      author: 'US. OSAKA',
      image: '/testimonials/testimonial-car-4.jpg',
      quote: 'The customer service provided by NEPT and MORE is outstanding. The team is highly knowledgeable and always ready to assist. They answer queries promptly and offer valuable suggestions to ensure the best possible modification experience.',
    },
  ],
  brand: [
    `${media}/2025/12/Introduction-to-Muye-IndustryNEW_012-scaled.jpg`,
    `${media}/2025/12/Introduction-to-Muye-IndustryNEW_011-scaled.jpg`,
    `${media}/2025/12/Introduction-to-Muye-IndustryNEW_013-scaled.jpg`,
    `${media}/2025/12/Introduction-to-Muye-IndustryNEW_015-scaled.jpg`,
  ],
};

const pages = {
  home: '/',
  shop: '/shop-2/',
  nept: '/product-category/modified-parts-exclusive-to-ford-bronco/',
  neptr: '/product-category/neptr-series/',
  more: '/product-category/more-series/',
  blog: '/our-blog/',
  brand: '/brand/',
  contact: '/contact/',
  supports: '/supports-center/',
  cart: '/cart/',
  checkout: '/checkout/',
  orderReceived: '/checkout/order-received/',
};

const articleSlugs = [
  '/exploring-the-market-prospect-of-off-road-vehicle-modification/',
  '/exploring-the-market-size-of-off-road-car-modification-parts/',
  '/33796-2/',
  '/33822-2/',
  '/shenzhen-muye-industrial-to-showcase-ford-bronco-carbon-fiber-accessories-at-automechanika-shanghai-2025/',
  '/tank-300/',
  '/muye-industrial-introduces-the-adjustable-40-52-roof-spotlight-bracket-at-automechanika-shanghai-2025/',
  '/bronco-central-control-integrated-rail-platform-automechanika/',
  '/nept-x-muye-industry-meet-us-at-automechanika-shanghai-booth-8-2k123/',
  '/the-ultimate-dashboard-organizer-for-your-ford-ranger/',
  '/ford-ranger/',
  '/a-pillar-dual-spotlight-bracket-for-2023-2025-ford-ranger/',
  '/multi-functional-flagpole-mount-for-off-road-adventures/',
  '/universal-roof-spotlight-bracket-for-serious-off-road-builds/',
  '/enhance-off-road-safety-with-a-wide-angle-blind-spot-mirror/',
  '/elevate-the-ritual-why-you-need-a-transparent-fuel-door-upgrade/',
  '/the-ultimate-rear-guard-why-your-rig-needs-cnc-aluminum-tail-light-covers/',
  '/quick-release-blind-spot-mirror/',
  '/rear-trunk-integration-platform-drawers-table/'
];

function prettySlug(slug) {
  return slug
    .split('-')
    .filter(Boolean)
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}

function go(path) {
  window.history.pushState({}, '', path);
  window.dispatchEvent(new PopStateEvent('popstate'));
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

/* ===================================================
   SVG ICONS
   =================================================== */
function GlobeIcon() {
  return (
    <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10" />
      <line x1="2" y1="12" x2="22" y2="12" />
      <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
    </svg>
  );
}

function SocialIcons() {
  return (
    <div className="topbar-socials">
      <a href="https://www.facebook.com/share/1HyfwQ9ARi/" target="_blank" rel="noopener noreferrer" aria-label="Facebook">
        <svg viewBox="0 0 24 24" width="13" height="13" fill="currentColor">
          <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" />
        </svg>
      </a>
      <a href="https://www.instagram.com/muyeindustry/" target="_blank" rel="noopener noreferrer" aria-label="Instagram">
        <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <rect x="2" y="2" width="20" height="20" rx="5" ry="5" />
          <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z" />
          <line x1="17.5" y1="6.5" x2="17.51" y2="6.5" />
        </svg>
      </a>
      <a href="https://www.tiktok.com/@muyeindustry" target="_blank" rel="noopener noreferrer" aria-label="TikTok">
        <svg viewBox="0 0 24 24" width="13" height="13" fill="currentColor">
          <path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-2.88 2.89 2.89 2.89 0 0 1-2.89-2.89 2.89 2.89 0 0 1 2.89-2.89c.31 0 .61.05.89.14V9.41a6.34 6.34 0 0 0-.89-.06 6.34 6.34 0 0 0-6.34 6.34 6.34 6.34 0 0 0 6.34 6.34 6.34 6.34 0 0 0 6.34-6.34V8.41a8.27 8.27 0 0 0 4.76 1.5V6.78a4.86 4.86 0 0 1-1.05-.09z" />
        </svg>
      </a>
      <a href="https://www.youtube.com/@Muyeindustry/shorts" target="_blank" rel="noopener noreferrer" aria-label="YouTube">
        <svg viewBox="0 0 24 24" width="13" height="13" fill="currentColor">
          <path d="M22.54 6.42a2.78 2.78 0 0 0-1.94-2C18.88 4 12 4 12 4s-6.88 0-8.6.46a2.78 2.78 0 0 0-1.94 2A29 29 0 0 0 1 11.75a29 29 0 0 0 .46 5.33A2.78 2.78 0 0 0 3.4 19c1.72.46 8.6.46 8.6.46s6.88 0 8.6-.46a2.78 2.78 0 0 0 1.94-2 29 29 0 0 0 .46-5.25 29 29 0 0 0-.46-5.33z" />
        </svg>
      </a>
      <a href="https://vk.com" target="_blank" rel="noopener noreferrer" aria-label="VK">
        <svg viewBox="0 0 24 24" width="13" height="13" fill="currentColor">
          <path d="M13.162 18.994c.609 0 .858-.406.851-.915-.011-.799.049-1.602.441-2.285.344-.6 1.002-.572 1.542-.162 1.156.88 1.946 2.052 3.018 3.019.261.236.567.343.916.343h2.646c.49 0 .749-.247.606-.723-.323-1.077-1.467-2.317-2.127-3.155-.544-.691-.977-1.203-.306-2.036.953-1.182 2.162-2.308 2.659-3.754.168-.488-.135-.726-.642-.726h-2.583c-.391 0-.649.195-.788.572-.638 1.729-1.574 3.256-2.834 4.542-.317.324-.575.253-.736-.188-.415-1.139-.304-2.348-.344-3.535-.06-1.782-.931-2.31-2.42-2.378-.445-.02-1.01.076-1.393.3-.327.192-.486.417-.376.818.17.621.849.691 1.087 1.487.328 1.096.223 2.228.182 3.351-.06.744-.45.989-.861.474-1.259-1.578-2.155-3.344-2.905-5.234-.143-.361-.384-.589-.785-.589H2.825c-.534 0-.69.255-.595.688.89 4.07 2.766 7.423 5.485 10.28 1.488 1.564 3.298 2.373 5.447 2.373z" />
        </svg>
      </a>
      <a href="https://www.linkedin.com/in/muye-industry-8209b4392" target="_blank" rel="noopener noreferrer" aria-label="LinkedIn">
        <svg viewBox="0 0 24 24" width="13" height="13" fill="currentColor">
          <path d="M19 3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14m-.5 15.5v-5.3a3.26 3.26 0 0 0-3.26-3.26c-.85 0-1.84.52-2.28 1.3v-1.11h-2.79v8.37h2.79v-4.93c0-.77.62-1.4 1.39-1.4a1.4 1.4 0 0 1 1.4 1.4v4.93h2.75M6.88 8.56a1.68 1.68 0 0 0 1.68-1.68c0-.93-.75-1.69-1.68-1.69a1.69 1.69 0 0 0-1.69 1.69c0 .93.76 1.68 1.69 1.68m1.39 9.94v-8.37H5.5v8.37h2.77z" />
        </svg>
      </a>
    </div>
  );
}

function WhatsAppIcon() {
  return (
    <svg viewBox="0 0 24 24" width="20" height="20" fill="#ffffff">
      <path d="M12.04 2c-5.46 0-9.91 4.45-9.91 9.91 0 1.75.46 3.45 1.32 4.95L2.05 22l5.25-1.38c1.45.79 3.08 1.21 4.74 1.21 5.46 0 9.91-4.45 9.91-9.91 0-2.65-1.03-5.14-2.9-7.01A9.816 9.816 0 0 0 12.04 2zm0 1.67c4.54 0 8.24 3.7 8.24 8.24 0 2.2-.86 4.28-2.42 5.83a8.188 8.188 0 0 1-5.82 2.41c-1.45 0-2.88-.38-4.14-1.11l-.3-.17-3.12.82.83-3.04-.2-.31a8.167 8.167 0 0 1-1.25-4.43c0-4.54 3.7-8.24 8.24-8.24zm4.51 11.66c-.25-.13-1.47-.72-1.7-.81-.23-.08-.39-.13-.56.13-.17.25-.64.81-.79.97-.14.17-.29.19-.54.06-.25-.13-1.07-.39-2.03-1.25-.75-.67-1.26-1.5-1.41-1.75-.14-.25-.02-.39.11-.51.11-.11.25-.29.38-.44.13-.14.17-.25.25-.42.08-.17.04-.31-.02-.44s-.56-1.36-.77-1.86c-.2-.49-.41-.42-.56-.43h-.48c-.17 0-.44.06-.67.31-.23.25-.88.86-.88 2.1 0 1.24.9 2.44 1.03 2.61.13.17 1.78 2.72 4.31 3.81.6.26 1.07.42 1.44.54.61.19 1.16.17 1.6.1.49-.07 1.47-.6 1.68-1.18.21-.58.21-1.08.15-1.18-.06-.1-.23-.17-.48-.29z" />
    </svg>
  );
}

function SearchIcon() {
  return (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="11" cy="11" r="7" />
      <line x1="21" y1="21" x2="16.65" y2="16.65" />
    </svg>
  );
}

function UserIcon() {
  return (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
      <circle cx="12" cy="7" r="4" />
    </svg>
  );
}

function CartIcon() {
  return (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="9" cy="21" r="1" />
      <circle cx="20" cy="21" r="1" />
      <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6" />
    </svg>
  );
}

function MailSolidIcon({ size = 16, color = '#111' }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill={color} style={{ minWidth: size, display: 'block' }}>
      <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4-8 5-8-5V6l8 5 8-5v2z" />
    </svg>
  );
}

function WhatsAppSolidIcon({ size = 17, color = '#111' }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill={color} style={{ minWidth: size, display: 'block' }}>
      <path d="M12.04 2c-5.46 0-9.91 4.45-9.91 9.91 0 1.75.46 3.45 1.32 4.95L2.05 22l5.25-1.38c1.45.79 3.08 1.21 4.74 1.21 5.46 0 9.91-4.45 9.91-9.91 0-2.65-1.03-5.14-2.9-7.01A9.816 9.816 0 0 0 12.04 2m.01 1.67c2.2 0 4.26.86 5.82 2.42a8.225 8.225 0 0 1 2.41 5.83c0 4.54-3.7 8.24-8.24 8.24-1.45 0-2.87-.38-4.12-1.1l-.3-.17-3.06.8.82-2.98-.19-.32a8.18 8.18 0 0 1-1.26-4.47c0-4.54 3.7-8.24 8.24-8.24m4.52 11.64c-.25-.13-1.47-.72-1.7-.81-.23-.08-.39-.13-.56.13-.17.25-.64.81-.79.97-.14.17-.29.19-.54.06-.25-.13-1.06-.39-2.03-1.25-.75-.67-1.26-1.5-1.41-1.75-.15-.25-.02-.39.11-.51.11-.11.25-.29.37-.44.13-.14.17-.25.25-.42.08-.17.04-.31-.02-.44-.06-.13-.56-1.35-.77-1.85-.2-.49-.41-.42-.56-.43h-.48c-.17 0-.44.06-.67.31-.23.25-.88.86-.88 2.1s.9 2.44 1.02 2.6c.13.17 1.77 2.7 4.28 3.79.6.26 1.07.41 1.43.53.6.19 1.15.16 1.58.1.48-.07 1.47-.6 1.68-1.18.21-.58.21-1.07.15-1.18-.06-.11-.23-.17-.48-.29z" />
    </svg>
  );
}

function PinSolidIcon({ size = 16, color = '#111' }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill={color} style={{ minWidth: size, display: 'block' }}>
      <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" />
    </svg>
  );
}

/* ===================================================
   HEADER COMPONENT
   =================================================== */
function Header({ currentPath, cartCount, onCart, onSearch }) {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [searchCategory, setSearchCategory] = useState('all');

  const [searchOpen, setSearchOpen] = useState(false);
  const searchWrapRef = useRef(null);

  useEffect(() => {
    function handleOutsideClick(e) {
      if (searchWrapRef.current && !searchWrapRef.current.contains(e.target)) {
        setSearchOpen(false);
      }
    }
    function handleKeyDown(e) {
      if (e.key === 'Escape') setSearchOpen(false);
    }
    if (searchOpen) {
      document.addEventListener('mousedown', handleOutsideClick);
      document.addEventListener('keydown', handleKeyDown);
      return () => {
        document.removeEventListener('mousedown', handleOutsideClick);
        document.removeEventListener('keydown', handleKeyDown);
      };
    }
  }, [searchOpen]);

  const handleSearchSubmit = (e) => {
    e.preventDefault();
    if (onSearch) {
      onSearch(searchTerm, searchCategory);
    }
    setSearchOpen(false);
  };

  const navLinks = [
    { label: 'HOME', path: pages.home },
    { label: 'NEPT SERIES', path: pages.nept },
    { label: 'NEPTR SERIES', path: pages.neptr },
    { label: 'MORE SERIES', path: pages.more },
    { label: 'SHOP', path: pages.shop },
    { label: 'BLOG', path: pages.blog },
    { label: 'CONTACT', path: pages.contact },
  ];

  return (
    <>
      {/* 1. TOP BAR */}
      <div className="topbar-wrap">
        <div className="topbar">
          <div className="topbar-left">
            <button className="topbar-lang" title="Select Language">
              <GlobeIcon />
              <span>EN</span>
            </button>
          </div>
          <SocialIcons />
        </div>
      </div>

      {/* 2. MAIN HEADER */}
      <header className="site-header">
        <div className="header-main-row">
          {/* Left: WhatsApp Only */}
          <div className="header-left">
            <a
              href="https://wa.me/8617727960741"
              target="_blank"
              rel="noopener noreferrer"
              className="whatsapp-widget"
              title="Chat with MUYE on WhatsApp"
            >
              <div className="whatsapp-icon-badge">
                <WhatsAppIcon />
              </div>
              <div className="whatsapp-info">
                <span className="whatsapp-label">Whatsapp Me:</span>
                <span className="whatsapp-number">+86-17727960741</span>
              </div>
            </a>
          </div>

          {/* Center: Logo */}
          <div className="header-center">
            <a
              href="/"
              className="brand-logo"
              onClick={(e) => {
                e.preventDefault();
                go('/');
              }}
            >
              <img src={images.logo} alt="MUYE INDUSTRY" />
            </a>
          </div>

          {/* Right: Actions (Search Icon -> Account -> Cart -> Mobile Menu) */}
          <div className="header-right">
            {/* Search Icon & Dropdown Menu */}
            <div className="header-search-dropdown-wrap" ref={searchWrapRef}>
              <button
                className={`header-icon-btn ${searchOpen ? 'active' : ''}`}
                aria-label="Search"
                title="Search Products"
                onClick={() => setSearchOpen(!searchOpen)}
              >
                <SearchIcon />
              </button>

              {searchOpen && (
                <div className="header-search-popover">
                  <form className="header-search-form-popover" onSubmit={handleSearchSubmit}>
                    <input
                      type="text"
                      className="header-search-input"
                      placeholder="Search products, SKU or vehicle..."
                      value={searchTerm}
                      autoFocus
                      onChange={(e) => setSearchTerm(e.target.value)}
                    />
                    <div className="header-search-divider" />
                    <select
                      className="header-search-select"
                      value={searchCategory}
                      onChange={(e) => setSearchCategory(e.target.value)}
                    >
                      <option value="all">All Categories</option>
                      <option value="nept">NEPT Series</option>
                      <option value="neptr">NEPTR Series</option>
                      <option value="more">MORE Series</option>
                    </select>
                    <button type="submit" className="header-search-btn" aria-label="Submit Search">
                      <SearchIcon />
                    </button>
                  </form>
                </div>
              )}
            </div>

            <button
              className="header-icon-btn"
              aria-label="My Account"
              title="My Account"
              onClick={() => go('/my-account-2/')}
            >
              <UserIcon />
            </button>
            <button
              className="header-icon-btn cart-icon-btn"
              aria-label="Cart"
              title="Cart"
              onClick={onCart}
            >
              <CartIcon />
              {cartCount > 0 && <span className="cart-badge">{cartCount}</span>}
            </button>
            <button
              className="mobile-menu-btn"
              onClick={() => setMobileOpen(true)}
              aria-label="Toggle Navigation"
            >
              ☰
            </button>
          </div>
        </div>

        {/* 3. CENTERED NAV ROW */}
        <nav className="site-nav-row">
          {navLinks.map((link) => {
            const isActive =
              link.path === '/'
                ? currentPath === '/' || currentPath === ''
                : currentPath.startsWith(link.path);
            return (
              <a
                key={link.path}
                href={link.path}
                className={`nav-link ${isActive ? 'active' : ''}`}
                onClick={(e) => {
                  e.preventDefault();
                  go(link.path);
                }}
              >
                {link.label}
              </a>
            );
          })}
        </nav>
      </header>

      {/* Mobile Drawer */}
      {mobileOpen && (
        <div className="drawer-overlay" onClick={() => setMobileOpen(false)}>
          <aside className="mobile-drawer" onClick={(e) => e.stopPropagation()}>
            <button className="drawer-close" onClick={() => setMobileOpen(false)}>
              ×
            </button>
            <a
              href="/"
              onClick={(e) => {
                e.preventDefault();
                setMobileOpen(false);
                go('/');
              }}
              style={{ border: 'none', padding: 0 }}
            >
              <img src={images.logo} alt="MUYE INDUSTRY" style={{ height: 48, width: 'auto' }} />
            </a>
            {navLinks.map((link) => (
              <a
                key={link.path}
                href={link.path}
                onClick={(e) => {
                  e.preventDefault();
                  setMobileOpen(false);
                  go(link.path);
                }}
              >
                {link.label}
              </a>
            ))}
            <div style={{ marginTop: 'auto', paddingTop: 20 }}>
              <a
                href="https://wa.me/8617727960741"
                target="_blank"
                rel="noopener noreferrer"
                style={{ fontSize: 14, textTransform: 'none', display: 'flex', alignItems: 'center', gap: 8, color: '#0e6233', fontWeight: 600 }}
              >
                <WhatsAppIcon /> +86-17727960741
              </a>
            </div>
          </aside>
        </div>
      )}
    </>
  );
}

/* ===================================================
   HERO BANNER COMPONENT
   =================================================== */
function HeroBanner() {
  return (
    <div className="hero-container">
      <section className="hero-banner">
        <img
          src={images.heroBanner}
          alt="Exploring Never Stop - MUYE Off-Road Equipment"
          className="hero-bg-img"
        />
        <div className="hero-overlay" />
        <div className="hero-content">
          <h1 className="hero-title-top">EXPLORING NEVER</h1>
          <div className="hero-title-main">STOP</div>
          <p className="hero-subtitle">THE ULTIMATE OFF-ROAD EQUIPMENT</p>
          <a
            href={pages.shop}
            className="hero-cta-btn"
            onClick={(e) => {
              e.preventDefault();
              go(pages.shop);
            }}
          >
            Explore Collection <span>↗</span>
          </a>
        </div>
      </section>
    </div>
  );
}

/* ===================================================
   PRODUCT CATEGORIES COMPONENT
   =================================================== */
function ProductCategories() {
  const categories = [
    {
      title: 'NEPTR SERIES',
      desc: 'Ford Ranger & Raptor',
      image: images.neptrCard,
      path: pages.neptr,
    },
    {
      title: 'NEPT SERIES',
      desc: 'Ford Bronco Exclusive',
      image: images.neptCard,
      path: pages.nept,
    },
    {
      title: 'MORE SERIES',
      desc: 'GWM Tank 300 & Universal',
      image: images.moreCard,
      path: pages.more,
    },
  ];

  return (
    <div className="categories-container">
      <div className="categories-grid">
        {categories.map((cat) => (
          <a
            key={cat.title}
            href={cat.path}
            className="category-tile"
            onClick={(e) => {
              e.preventDefault();
              go(cat.path);
            }}
          >
            <img src={cat.image} alt={cat.title} className="category-tile-img" />
            <div className="category-tile-gradient" />
            <span className="category-tile-badge" title="View Series">
              ↗
            </span>
            <div className="category-tile-info">
              <h3 className="category-tile-title">{cat.title}</h3>
              <p className="category-tile-desc">{cat.desc}</p>
            </div>
          </a>
        ))}
      </div>
    </div>
  );
}

/* ===================================================
   PRODUCT CARDS & GRIDS (4:3 pure white background hero image + right-to-left hover slide)
   =================================================== */
function ProductCard({ product, onAdd }) {
  const isObj = product && typeof product === 'object' && !Array.isArray(product);
  const title = isObj ? product.name : product[0];
  const img1 = isObj ? (product.hero_white || product.gallery?.[0]) : product[1];
  const img2 = isObj ? (product.hero_lifestyle || product.gallery?.[1] || img1) : product[2];
  const price = isObj ? product.price : product[3];
  const origPrice = isObj ? product.regular_price : product[4];
  const discount = isObj
    ? product.discount_percent
    : Math.round((1 - parseFloat(price.slice(1)) / parseFloat(origPrice.slice(1))) * 100);
  const slug = isObj ? product.slug : title.toLowerCase().replace(/[^a-z0-9]+/g, '-');
  const targetUrl = `/product/${slug}/`;

  return (
    <article
      className="product-card product-card-interactive"
      onClick={() => go(targetUrl)}
    >
      <div className="product-image-box">
        <span className="sale-badge">-{discount}%</span>
        <img src={img1} alt={title} className="product-img-primary" loading="lazy" />
        {img2 && (
          <img src={img2} alt={`${title} detail`} className="product-img-secondary" loading="lazy" />
        )}
      </div>
      <div className="product-info">
        <div className="product-divider" />
        <div className="product-meta">
          <h3 className="product-title" title={title}>
            <a
              href={targetUrl}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                go(targetUrl);
              }}
            >
              {title}
            </a>
          </h3>
          <div className="product-card-price-action-row">
            <p className="product-price">
              <del className="price-del">{origPrice}</del>
              <strong className="price-current">{price}</strong>
            </p>
            {onAdd && (
              <button
                type="button"
                className="card-quick-add-btn"
                title="Add to cart"
                onClick={(e) => {
                  e.stopPropagation();
                  onAdd(product, 1);
                }}
              >
                <span>+</span>
              </button>
            )}
          </div>
        </div>
      </div>
    </article>
  );
}

function ProductGrid({
  items = productsCatalog,
  onAdd,
  title = 'FEATURED OF MORE SERIES',
  showViewAll = false,
  viewAllUrl = pages.more
}) {
  return (
    <section className="product-section">
      {title && (
        <div className="section-heading center">
          <h2 className="section-title">{title}</h2>
        </div>
      )}
      <div className="product-grid-3">
        {items.map((p) => (
          <ProductCard key={p.id || p.slug || p[0]} product={p} onAdd={onAdd} />
        ))}
      </div>
      {showViewAll && (
        <div className="product-grid-view-all-wrap">
          <a
            className="product-grid-view-all-btn"
            href={viewAllUrl}
            onClick={(e) => {
              e.preventDefault();
              go(viewAllUrl);
            }}
          >
            <span>VIEW ALL PRODUCTS</span>
            <span>↗</span>
          </a>
        </div>
      )}
    </section>
  );
}

/* ===================================================
   HOMEPAGE
   =================================================== */
function Home({ onAdd }) {
  const [testimonial, setTestimonial] = useState(0);

  // Pick top 9 MORE series items for the featured section
  const moreFeatured = useMemo(() => {
    return productsCatalog.filter((p) => p.series === 'MORE SERIES').slice(0, 9);
  }, []);

  return (
    <main>
      {/* 1. Hero Banner matching screenshot */}
      <HeroBanner />

      {/* 2. Product Category Cards matching screenshot */}
      <ProductCategories />

      {/* 3. Highlight Feature Banner (Exact match to Wasteland Roof Rack screenshot) */}
      <section className="feature-banner" onClick={() => go('/product/wasteland-roof-rack/')}>
        <img
          src="/banner/wasteland-roof-rack-bg.jpg"
          alt="Wasteland roof rack"
          className="feature-banner-bg"
          loading="lazy"
        />
        <div className="feature-banner-gradient-overlay" />
        <div className="feature-banner-content">
          <h2 className="feature-banner-title">WASTELAND ROOF RACK</h2>
          <p className="feature-banner-desc">
            ORIGINAL VEHICLE POSITION LOSSLESS INSTALLATION<br />
            WITHSTAND A STATIC LOAD OF 160KG
          </p>
          <div className="feature-banner-price">$1500</div>
          <a
            className="feature-banner-btn"
            href="/product/wasteland-roof-rack/"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              go('/product/wasteland-roof-rack/');
            }}
          >
            SHOP NOW
          </a>
        </div>
      </section>

      {/* 4. Product Showcase (9 MORE Series Products + View All Products button) */}
      <ProductGrid
        items={moreFeatured}
        onAdd={onAdd}
        title="Featured of MORE Series"
        showViewAll={true}
        viewAllUrl={pages.more}
      />

      {/* 5. Highlight Feature Banner below Featured (Armed Carbon Fiber Handlebars matching screenshot) */}
      <section
        className="feature-banner feature-banner-handlebars"
        onClick={() => go('/product/armed-carbon-fiber-handlebars/')}
      >
        <img
          src="/banner/armed-carbon-fiber-handlebars-bg.jpg"
          alt="Armed Carbon Fiber Handlebars"
          className="feature-banner-bg"
          loading="lazy"
        />
        <div className="feature-banner-gradient-overlay" />
        <div className="feature-banner-content">
          <h2 className="feature-banner-title">ARMED CARBON FIBER HANDLEBARS</h2>
          <p className="feature-banner-desc">
            CARBON FIBER HAS EXCELLENT DAMPING EFFECT TO IMPROVE<br />
            THE HANDLING FEEL
          </p>
          <div className="feature-banner-price">$1480</div>
          <a
            className="feature-banner-btn"
            href="/product/armed-carbon-fiber-handlebars/"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              go('/product/armed-carbon-fiber-handlebars/');
            }}
          >
            SHOP NOW
          </a>
        </div>
      </section>

      {/* 5B. Community & Newsletter Section (Exact match to screenshot) */}
      <section className="community-newsletter-section">
        <div className="community-newsletter-grid">
          {/* Left Card: Follow Us on Social Media with Tire Tread Background */}
          <div className="community-card follow-us-card">
            <div className="community-card-overlay" />
            <div className="community-card-inner">
              <h2 className="community-card-title">FOLLOW US</h2>
              <h3 className="community-card-subtitle">SOCIAL MEDIA</h3>
              <p className="community-card-text">
                Follow MUYE INDUSTRY across social networks for official releases, field testing footage, and precision installation guides.
              </p>
              <div className="community-social-links">
                <a href="https://www.facebook.com/share/1HyfwQ9ARi/" target="_blank" rel="noopener noreferrer" aria-label="Facebook">
                  <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                    <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" />
                  </svg>
                </a>
                <a href="https://www.youtube.com/@Muyeindustry/shorts" target="_blank" rel="noopener noreferrer" aria-label="YouTube">
                  <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                    <path d="M22.54 6.42a2.78 2.78 0 0 0-1.94-2C18.88 4 12 4 12 4s-6.88 0-8.6.46a2.78 2.78 0 0 0-1.94 2A29 29 0 0 0 1 11.75a29 29 0 0 0 .46 5.33A2.78 2.78 0 0 0 3.4 19c1.72.46 8.6.46 8.6.46s6.88 0 8.6-.46a2.78 2.78 0 0 0 1.94-2 29 29 0 0 0 .46-5.25 29 29 0 0 0-.46-5.33z" />
                  </svg>
                </a>
                <a href="https://www.instagram.com/muyeindustry/" target="_blank" rel="noopener noreferrer" aria-label="Instagram">
                  <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <rect x="2" y="2" width="20" height="20" rx="5" ry="5" />
                    <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z" />
                    <line x1="17.5" y1="6.5" x2="17.51" y2="6.5" />
                  </svg>
                </a>
                <a href="https://www.tiktok.com/@muyeindustry" target="_blank" rel="noopener noreferrer" aria-label="TikTok">
                  <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                    <path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-2.88 2.89 2.89 2.89 0 0 1-2.89-2.89 2.89 2.89 0 0 1 2.89-2.89c.31 0 .61.05.89.14V9.41a6.34 6.34 0 0 0-.89-.06 6.34 6.34 0 0 0-6.34 6.34 6.34 6.34 0 0 0 6.34 6.34 6.34 6.34 0 0 0 6.34-6.34V8.41a8.27 8.27 0 0 0 4.76 1.5V6.78a4.86 4.86 0 0 1-1.05-.09z" />
                  </svg>
                </a>
                <a href="https://vk.com" target="_blank" rel="noopener noreferrer" aria-label="VK">
                  <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                    <path d="M13.162 18.994c.609 0 .858-.406.851-.915-.011-.799.049-1.602.441-2.285.344-.6 1.002-.572 1.542-.162 1.156.88 1.946 2.052 3.018 3.019.261.236.567.343.916.343h2.646c.49 0 .749-.247.606-.723-.323-1.077-1.467-2.317-2.127-3.155-.544-.691-.977-1.203-.306-2.036.953-1.182 2.162-2.308 2.659-3.754.168-.488-.135-.726-.642-.726h-2.583c-.391 0-.649.195-.788.572-.638 1.729-1.574 3.256-2.834 4.542-.317.324-.575.253-.736-.188-.415-1.139-.304-2.348-.344-3.535-.06-1.782-.931-2.31-2.42-2.378-.445-.02-1.01.076-1.393.3-.327.192-.486.417-.376.818.17.621.849.691 1.087 1.487.328 1.096.223 2.228.182 3.351-.06.744-.45.989-.861.474-1.259-1.578-2.155-3.344-2.905-5.234-.143-.361-.384-.589-.785-.589H2.825c-.534 0-.69.255-.595.688.89 4.07 2.766 7.423 5.485 10.28 1.488 1.564 3.298 2.373 5.447 2.373z" />
                  </svg>
                </a>
              </div>
            </div>
          </div>

          {/* Right Card: Green Subscribe & Actions Card */}
          <div className="community-card subscribe-card">
            {/* Top Quick Actions */}
            <div className="subscribe-top-actions">
              <a href={pages.contact} onClick={(e) => { e.preventDefault(); go(pages.contact); }} className="subscribe-top-item">
                <div className="subscribe-top-icon">
                  <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                    <line x1="8" y1="10" x2="8.01" y2="10" />
                    <line x1="12" y1="10" x2="12.01" y2="10" />
                    <line x1="16" y1="10" x2="16.01" y2="10" />
                  </svg>
                </div>
                <span>SUPPORTS CENTER</span>
              </a>

              <a href={pages.contact} onClick={(e) => { e.preventDefault(); go(pages.contact); }} className="subscribe-top-item">
                <div className="subscribe-top-icon">
                  <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="12" cy="12" r="10" />
                    <line x1="2" y1="12" x2="22" y2="12" />
                    <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
                  </svg>
                </div>
                <span>BECOME OUR DEALER</span>
              </a>
            </div>

            {/* Subscribe Form Content */}
            <div className="subscribe-form-content">
              <h2 className="subscribe-title">SUBSCRIBE</h2>
              <p className="subscribe-text">
                Sign up for our newsletter to receive new product alerts and personalized deals
              </p>
              <form
                className="subscribe-form-row"
                onSubmit={(e) => {
                  e.preventDefault();
                  alert('Thank you for subscribing to MUYE INDUSTRY updates!');
                }}
              >
                <input
                  type="email"
                  className="subscribe-input"
                  placeholder="Email"
                  required
                />
                <button type="submit" className="subscribe-btn">
                  Subscribe
                </button>
              </form>
            </div>
          </div>
        </div>
      </section>

      {/* 6. Customer Testimonials */}
      {/* 6. Customer Testimonials (4 Cards Matching Screenshot) */}
      <section className="testimonial-section">
        <div className="section-heading center">
          <p className="eyebrow">WHAT OUR CUSTOMERS SAY</p>
          <h2 className="section-title">REAL MILES. REAL STORIES.</h2>
        </div>

        <div className="testimonial-cards-grid">
          {images.testimonials.map((t, idx) => (
            <div className="testimonial-card-item" key={idx}>
              <div className="testimonial-card-img-wrap">
                <img
                  src={t.image}
                  alt={`Off-road vehicle by ${t.author}`}
                  loading="lazy"
                />
              </div>
              <div className="testimonial-card-body">
                <div className="testimonial-stars">★★★★★</div>
                <p className="testimonial-card-quote">“{t.quote}”</p>
                <div className="testimonial-card-author-wrap">
                  <div className="testimonial-card-author-line" />
                  <span className="testimonial-card-author">{t.author}</span>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Carousel Indicator Dots */}
        <div className="dots testimonial-dots">
          {images.testimonials.map((_, i) => (
            <button
              key={i}
              className={testimonial === i ? 'active' : ''}
              onClick={() => setTestimonial(i)}
              aria-label={`Testimonial card ${i + 1}`}
            />
          ))}
        </div>
      </section>
    </main>
  );
}

/* ===================================================
   FOOTER
   =================================================== */
function Footer() {
  return (
    <footer className="site-footer">
      <div className="footer-cta">
        <div>
          <p className="eyebrow">Follow Us</p>
          <h3>Adventure is waiting.</h3>
        </div>
        <div className="socials">
          <a href="https://www.facebook.com/share/1HyfwQ9ARi/" target="_blank" rel="noopener noreferrer">f</a>
          <a href="https://www.instagram.com/muyeindustry/" target="_blank" rel="noopener noreferrer">◎</a>
          <a href="https://www.tiktok.com/@muyeindustry" target="_blank" rel="noopener noreferrer">♪</a>
          <a href="https://www.youtube.com/@Muyeindustry/shorts" target="_blank" rel="noopener noreferrer">▶</a>
          <a href="https://www.linkedin.com/in/muye-industry-8209b4392" target="_blank" rel="noopener noreferrer">in</a>
        </div>
      </div>
      <div className="footer-main">
        <div>
          <h4>MUYE INDUSTRY</h4>
          <p>Premium CNC aluminum and carbon fiber upgrades for Ford Bronco, Ranger and Tank.</p>
        </div>
        <div>
          <h4>Information</h4>
          <p>
            <a href="mailto:info@muyecncar.com">info@muyecncar.com</a><br />
            <a href="https://wa.me/8617727960741">+86-17727960741</a><br />
            101, Building 4, Baiwang Creative Factory, Shenzhen, China
          </p>
        </div>
        <div>
          <h4>Customer Service</h4>
          <a href={pages.brand} onClick={(e) => { e.preventDefault(); go(pages.brand); }}>Brand</a>
          <a href={pages.shop} onClick={(e) => { e.preventDefault(); go(pages.shop); }}>Shop</a>
          <a href={pages.blog} onClick={(e) => { e.preventDefault(); go(pages.blog); }}>Stories</a>
          <a href={pages.contact} onClick={(e) => { e.preventDefault(); go(pages.contact); }}>Contact</a>
        </div>
        <div>
          <h4>Subscribe</h4>
          <p>Sign up for new product alerts and personalized deals.</p>
          <form onSubmit={(e) => e.preventDefault()}>
            <input id="subscribe-email" name="email" autoComplete="email" type="email" placeholder="Email" required />
            <button>Subscribe</button>
          </form>
        </div>
      </div>
      <div className="footer-bottom">
        <span>2024 © Copyright MUYECNCAR</span>
        <span>
          <a href="/shipping-delivery-policy/">Shipping Policy</a> · <a href="/refund_returns/">Return & Refund</a> · <a href="/privacy-policy/">Privacy Policy</a>
        </span>
      </div>
    </footer>
  );
}

/* ===================================================
   OTHER PAGES
   =================================================== */
function Listing({ kind, onAdd, searchQuery = '' }) {
  const [selectedCategory, setSelectedCategory] = useState(
    kind === 'nept' ? 'NEPT SERIES' :
    kind === 'neptr' ? 'NEPTR SERIES' :
    kind === 'more' ? 'MORE SERIES' : 'ALL'
  );
  const [sortBy, setSortBy] = useState('featured');

  useEffect(() => {
    if (kind === 'nept') setSelectedCategory('NEPT SERIES');
    else if (kind === 'neptr') setSelectedCategory('NEPTR SERIES');
    else if (kind === 'more') setSelectedCategory('MORE SERIES');
    else if (kind === 'shop') setSelectedCategory('ALL');
  }, [kind]);

  const filteredItems = useMemo(() => {
    let list = [...productsCatalog];
    if (selectedCategory !== 'ALL') {
      list = list.filter((p) => p.series === selectedCategory);
    }
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      list = list.filter((p) =>
        p.name.toLowerCase().includes(q) ||
        (p.compatibility && p.compatibility.toLowerCase().includes(q)) ||
        (p.sku && p.sku.toLowerCase().includes(q))
      );
    }
    if (sortBy === 'price-low') {
      list.sort((a, b) => a.price_numeric - b.price_numeric);
    } else if (sortBy === 'price-high') {
      list.sort((a, b) => b.price_numeric - a.price_numeric);
    } else if (sortBy === 'name') {
      list.sort((a, b) => a.name.localeCompare(b.name));
    }
    return list;
  }, [selectedCategory, searchQuery, sortBy]);

  const title =
    searchQuery
      ? `Search Results: "${searchQuery}"`
      : selectedCategory === 'ALL'
      ? 'All Off-Road Products'
      : selectedCategory;

  return (
    <main className="inner-page">
      <div className="breadcrumbs-bar">
        <div className="breadcrumbs-nav">
          <a href="/" onClick={(e) => { e.preventDefault(); go('/'); }}>Home</a>
          <span className="breadcrumb-separator">/</span>
          <a href={pages.shop} onClick={(e) => { e.preventDefault(); go(pages.shop); }}>Shop</a>
          {selectedCategory !== 'ALL' && (
            <>
              <span className="breadcrumb-separator">/</span>
              <span className="breadcrumb-current">{selectedCategory}</span>
            </>
          )}
        </div>
      </div>

      <div className="page-title" style={{ padding: '36px var(--site-padding) 0' }}>
        <p className="eyebrow">MUYE Catalog</p>
        <h1>{title}</h1>
      </div>

      <div style={{ padding: '0 var(--site-padding)' }}>
        <div className="shop-toolbar">
          <div className="shop-filter-pills">
            <button
              className={`shop-filter-pill ${selectedCategory === 'ALL' ? 'active' : ''}`}
              onClick={() => setSelectedCategory('ALL')}
            >
              All Products ({productsCatalog.length})
            </button>
            <button
              className={`shop-filter-pill ${selectedCategory === 'NEPT SERIES' ? 'active' : ''}`}
              onClick={() => setSelectedCategory('NEPT SERIES')}
            >
              NEPT Series · Bronco ({productsCatalog.filter((p) => p.series === 'NEPT SERIES').length})
            </button>
            <button
              className={`shop-filter-pill ${selectedCategory === 'NEPTR SERIES' ? 'active' : ''}`}
              onClick={() => setSelectedCategory('NEPTR SERIES')}
            >
              NEPTR Series · Ranger ({productsCatalog.filter((p) => p.series === 'NEPTR SERIES').length})
            </button>
            <button
              className={`shop-filter-pill ${selectedCategory === 'MORE SERIES' ? 'active' : ''}`}
              onClick={() => setSelectedCategory('MORE SERIES')}
            >
              MORE Series · Tank ({productsCatalog.filter((p) => p.series === 'MORE SERIES').length})
            </button>
          </div>

          <div className="shop-sort-controls">
            <span className="shop-count-label">Showing {filteredItems.length} products</span>
            <select
              className="shop-sort-select"
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value)}
            >
              <option value="featured">Featured</option>
              <option value="price-low">Price: Low to High</option>
              <option value="price-high">Price: High to Low</option>
              <option value="name">Product Name (A-Z)</option>
            </select>
          </div>
        </div>
      </div>

      <ProductGrid items={filteredItems} title="" onAdd={onAdd} />
    </main>
  );
}

function Brand() {
  return (
    <main className="inner-page">
      <div className="page-title">
        <p className="eyebrow">The company</p>
        <h1>Brand</h1>
      </div>
      <section className="brand-story">
        <div>
          <p className="eyebrow">About MUYE INDUSTRY</p>
          <h2>We build the parts that take you further.</h2>
          <p>MUYE INDUSTRY creates CNC aluminum and carbon fiber upgrades for modern off-road vehicles. From the first sketch to the final fit, each part is built around real-world use, clean engineering and a desire to explore.</p>
          <p>Our NEPT, NEPTR and MORE series are designed to be installed without compromise and to keep their character for years of dust, sun and mud.</p>
        </div>
        <div className="brand-gallery">
          {images.brand.map((src) => (
            <img key={src} src={src} alt="MUYE INDUSTRY workshop" loading="lazy" />
          ))}
        </div>
      </section>
    </main>
  );
}

function Blog() {
  const [selectedCategory, setSelectedCategory] = useState('All');
  const [searchWord, setSearchWord] = useState('');

  const categories = useMemo(() => {
    const set = new Set();
    postsCatalog.forEach((p) => {
      if (p.category) set.add(p.category);
    });
    return ['All', ...Array.from(set)];
  }, []);

  const filteredPosts = useMemo(() => {
    return postsCatalog.filter((p) => {
      const matchCat = selectedCategory === 'All' || p.category === selectedCategory;
      const matchSearch =
        !searchWord ||
        p.title.toLowerCase().includes(searchWord.toLowerCase()) ||
        p.excerpt.toLowerCase().includes(searchWord.toLowerCase());
      return matchCat && matchSearch;
    });
  }, [selectedCategory, searchWord]);

  const featuredPost = filteredPosts[0];
  const gridPosts = filteredPosts.slice(1);

  return (
    <main className="blog-page-wrap">
      {/* Blog Hero Header */}
      <div className="blog-hero-header">
        <div className="blog-hero-inner">
          <p className="eyebrow">FIELD NOTES & ENGINEERING</p>
          <h1 className="blog-hero-title">MUYE JOURNAL</h1>
          <p className="blog-hero-desc">
            Technical build breakdowns, extreme terrain field testing, and precision CNC engineering stories for Ford Bronco, Ranger, and Tank 300.
          </p>

          {/* Filter Bar */}
          <div className="blog-filter-bar">
            <div className="blog-chips-row">
              {categories.map((cat) => (
                <button
                  key={cat}
                  className={`blog-chip-btn ${selectedCategory === cat ? 'active' : ''}`}
                  onClick={() => setSelectedCategory(cat)}
                >
                  {cat}
                </button>
              ))}
            </div>
            <div className="blog-search-box">
              <input
                type="text"
                placeholder="Search articles..."
                value={searchWord}
                onChange={(e) => setSearchWord(e.target.value)}
                className="blog-search-input"
              />
            </div>
          </div>
        </div>
      </div>

      <div className="blog-container">
        {/* Featured Card */}
        {featuredPost && (
          <article
            className="blog-featured-card"
            onClick={() => go(featuredPost.url)}
          >
            <div className="blog-featured-img-wrap">
              <img src={featuredPost.image} alt={featuredPost.title} loading="lazy" />
              <span className="blog-tag-badge">{featuredPost.category}</span>
            </div>
            <div className="blog-featured-content">
              <div className="blog-meta-row">
                <span className="blog-date">{featuredPost.date}</span>
                <span className="blog-meta-dot">•</span>
                <span className="blog-read-time">{featuredPost.read_time}</span>
              </div>
              <h2 className="blog-featured-title">
                <a href={featuredPost.url} onClick={(e) => { e.preventDefault(); go(featuredPost.url); }}>
                  {featuredPost.title}
                </a>
              </h2>
              <p className="blog-featured-excerpt">{featuredPost.excerpt}</p>
              <div className="blog-read-more-link">
                <span>Read Full Story</span>
                <span className="arrow">→</span>
              </div>
            </div>
          </article>
        )}

        {/* 3-Column Grid for Remaining Articles */}
        <div className="blog-grid">
          {gridPosts.map((post) => (
            <article
              key={post.id}
              className="blog-card"
              onClick={() => go(post.url)}
            >
              <div className="blog-card-img-wrap">
                <img src={post.image} alt={post.title} loading="lazy" />
                <span className="blog-tag-badge">{post.category}</span>
              </div>
              <div className="blog-card-body">
                <div className="blog-meta-row">
                  <span className="blog-date">{post.date}</span>
                  <span className="blog-meta-dot">•</span>
                  <span className="blog-read-time">{post.read_time}</span>
                </div>
                <h3 className="blog-card-title">
                  <a href={post.url} onClick={(e) => { e.preventDefault(); go(post.url); }}>
                    {post.title}
                  </a>
                </h3>
                <p className="blog-card-excerpt">{post.excerpt}</p>
                <div className="blog-card-footer">
                  <span className="blog-read-link">Read Story ↗</span>
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </main>
  );
}

function Contact() {
  const [formData, setFormData] = useState({
    company: '',
    name: '',
    email: '',
    phone: '',
    message: '',
  });
  const [submitted, setSubmitted] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    setSubmitted(true);
  };

  return (
    <main className="contact-page-wrapper">
      <section className="contact-hero-section">
        <div className="contact-content-container">
          {/* Left Column: CONTACT US */}
          <div className="contact-col-left">
            <h2 className="contact-section-heading">CONTACT US</h2>
            <div className="contact-text-body">
              <p>
                Customer service is our number one priority. Please feel free to reach out to us for regarding your order or giving feedback by{' '}
                <a href="mailto:info@muyecncar.com" className="contact-inline-link">info@muyecncar.com</a> (Please show us your order number first).
              </p>
              <p>
                We warmly welcome people with lofty ideals to join us. If you are interested in becoming our dealer, please contact us by{' '}
                <a href="mailto:info@muyecncar.com" className="contact-inline-link">info@muyecncar.com</a>
              </p>
              <p className="contact-text-notice">
                Important!!! We will definitely reply to the mail, but sometimes the mail will be considered as spam, please check the spam mailbox to find our mail in time.
              </p>
            </div>

            <div className="contact-info-list">
              <a href="mailto:info@muyecncar.com" className="contact-info-link">
                <span className="contact-icon-box">
                  <MailSolidIcon size={16} />
                </span>
                <span>info@muyecncar.com</span>
              </a>

              <a href="https://wa.me/8617727960741" target="_blank" rel="noopener noreferrer" className="contact-info-link">
                <span className="contact-icon-box">
                  <WhatsAppSolidIcon size={17} />
                </span>
                <span>+86-17727960741</span>
              </a>

              <div className="contact-info-item address-item">
                <span className="contact-icon-box">
                  <PinSolidIcon size={16} />
                </span>
                <span>101, Building 4, Baiwang Creative Factory, 1051 Songbai Road, Xili Street, Nanshan District, Shenzhen , China</span>
              </div>
            </div>
          </div>

          {/* Right Column: GET IN TOUCH */}
          <div className="contact-col-right">
            <h2 className="contact-section-heading">GET IN TOUCH</h2>

            {submitted ? (
              <div className="contact-success-box">
                <div className="contact-success-title">THANK YOU FOR GETTING IN TOUCH!</div>
                <p>We have received your message. Our team will review your inquiry and reply via email within 24 hours.</p>
                <button
                  type="button"
                  className="contact-submit-btn"
                  onClick={() => {
                    setSubmitted(false);
                    setFormData({ company: '', name: '', email: '', phone: '', message: '' });
                  }}
                  style={{ marginTop: 16 }}
                >
                  Send Another Message
                </button>
              </div>
            ) : (
              <form className="contact-form-grid" onSubmit={handleSubmit}>
                <div className="contact-input-row">
                  <input
                    type="text"
                    name="company"
                    placeholder="Company"
                    value={formData.company}
                    onChange={(e) => setFormData({ ...formData, company: e.target.value })}
                    className="contact-field-input"
                  />
                  <input
                    type="text"
                    name="name"
                    placeholder="Name"
                    required
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="contact-field-input"
                  />
                </div>

                <div className="contact-input-row">
                  <input
                    type="email"
                    name="email"
                    placeholder="Email"
                    required
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    className="contact-field-input"
                  />
                  <input
                    type="tel"
                    name="phone"
                    placeholder="Phone"
                    value={formData.phone}
                    onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                    className="contact-field-input"
                  />
                </div>

                <div className="contact-textarea-row">
                  <textarea
                    name="message"
                    placeholder="Message"
                    rows={5}
                    required
                    value={formData.message}
                    onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                    className="contact-field-textarea"
                  ></textarea>
                </div>

                <button type="submit" className="contact-submit-btn">
                  Send
                </button>
              </form>
            )}
          </div>
        </div>
      </section>
    </main>
  );
}

function GenericPage({ title, eyebrow = 'Customer service', children }) {
  return (
    <main className="inner-page">
      <div className="page-title">
        <p className="eyebrow">{eyebrow}</p>
        <h1>{title}</h1>
      </div>
      <section className="rich-content">
        {children || (
          <>
            <h2>We're here to help.</h2>
            <p>Browse our collection, read our latest stories, or contact the MUYE INDUSTRY team for product and order support.</p>
          </>
        )}
      </section>
    </main>
  );
}

function ProductPage({ onAdd, slug }) {
  const product = useMemo(() => {
    if (!slug) return productsCatalog[0];
    const s = slug.toLowerCase().replace(/\/$/, '');
    return (
      productsCatalog.find(
        (p) =>
          p.slug.toLowerCase() === s ||
          String(p.id) === s ||
          p.slug.toLowerCase().includes(s) ||
          s.includes(p.slug.toLowerCase())
      ) || productsCatalog[0]
    );
  }, [slug]);

  const [activeImgIndex, setActiveImgIndex] = useState(0);
  const [qty, setQty] = useState(1);
  const [activeTab, setActiveTab] = useState('desc');
  const [lightboxOpen, setLightboxOpen] = useState(false);

  // Gallery array
  const gallery = useMemo(() => {
    const list = [product.hero_white];
    if (product.hero_lifestyle && product.hero_lifestyle !== product.hero_white) {
      list.push(product.hero_lifestyle);
    }
    (product.gallery || []).forEach((img) => {
      if (!list.includes(img)) list.push(img);
    });
    return list.filter(Boolean);
  }, [product]);

  // Curated 4:3 white-background angle shots
  const whiteShots = useMemo(() => {
    if (product.white_gallery && product.white_gallery.length > 0) {
      return product.white_gallery;
    }
    const list = [product.hero_white];
    (product.gallery || []).forEach((img) => {
      if (img !== product.hero_lifestyle && !list.includes(img) && list.length < 4) {
        list.push(img);
      }
    });
    return list.filter(Boolean);
  }, [product]);

  // Lifestyle / on-car images for lookbook
  const lookbookImages = useMemo(() => {
    return (product.gallery || []).filter((img) => img !== product.hero_white).slice(0, 4);
  }, [product]);

  useEffect(() => {
    setActiveImgIndex(0);
    setQty(1);
    setLightboxOpen(false);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [product]);

  const currentImg = gallery[activeImgIndex] || product.hero_white;

  const nextImg = () => {
    setActiveImgIndex((prev) => (prev + 1) % gallery.length);
  };
  const prevImg = () => {
    setActiveImgIndex((prev) => (prev - 1 + gallery.length) % gallery.length);
  };

  const whatsappMessage = encodeURIComponent(
    `Hello MUYE INDUSTRY!\n\nI want to order: *${product.name}*\nPrice: ${product.price}\nSKU: ${product.sku}\nVehicle: ${product.compatibility}\n\nPlease check shipping rate and availability to my address.`
  );
  const whatsappUrl = `https://wa.me/8617727960741?text=${whatsappMessage}`;

  const relatedProducts = useMemo(() => {
    return productsCatalog
      .filter((p) => p.id !== product.id && p.series === product.series)
      .slice(0, 3);
  }, [product]);

  // Highlights fallback
  const highlights = product.feature_highlights && product.feature_highlights.length >= 2
    ? product.feature_highlights
    : [
        { title: 'Aviation 6061-T6 Billet', text: 'Precision CNC machined from single-block aluminum for maximum strength.' },
        { title: '100% Lossless Fitment', text: 'Uses original OEM bolt provisions with zero cutting or vehicle drilling.' },
        { title: 'Mil-Spec Hard Anodizing', text: 'Electrolytic corrosion and UV-resistant finish for severe trail conditions.' },
        { title: 'Off-Road Tested', text: 'Rigid stress-tested across dunes, rock crawls, and high-speed vibrations.' }
      ];

  return (
    <main className="pdp-wrapper">
      {/* Lightbox Modal */}
      {lightboxOpen && (
        <div className="pdp-lightbox-overlay" onClick={() => setLightboxOpen(false)}>
          <div className="pdp-lightbox-content" onClick={(e) => e.stopPropagation()}>
            <button className="pdp-lightbox-close" onClick={() => setLightboxOpen(false)}>
              ×
            </button>
            <img src={currentImg} alt={product.name} className="pdp-lightbox-img" />
          </div>
        </div>
      )}

      {/* Breadcrumbs Bar */}
      <div className="breadcrumbs-bar">
        <div className="breadcrumbs-inner">
          <div className="breadcrumbs-nav">
            <a href="/" onClick={(e) => { e.preventDefault(); go('/'); }}>Home</a>
            <span className="breadcrumb-separator">/</span>
            <a href={pages.shop} onClick={(e) => { e.preventDefault(); go(pages.shop); }}>Shop</a>
            <span className="breadcrumb-separator">/</span>
            <a
              href={
                product.series === 'NEPT SERIES' ? pages.nept :
                product.series === 'NEPTR SERIES' ? pages.neptr : pages.more
              }
              onClick={(e) => {
                e.preventDefault();
                go(
                  product.series === 'NEPT SERIES' ? pages.nept :
                  product.series === 'NEPTR SERIES' ? pages.neptr : pages.more
                );
              }}
            >
              {product.series}
            </a>
            <span className="breadcrumb-separator">/</span>
            <span className="breadcrumb-current">{product.name}</span>
          </div>

          <div className="breadcrumbs-fitment-badge">
            <span>✓ Confirmed Fitment:</span>
            <strong>{product.compatibility}</strong>
          </div>
        </div>
      </div>

      <div className="pdp-page">
        {/* Main 2-Column Showcase */}
        <div className="pdp-main-grid">
          {/* Left Column: Gallery */}
          <div className="pdp-gallery-wrap">
            <div className="pdp-stage" onClick={() => setLightboxOpen(true)}>
              <span className="pdp-badge-sale">-{product.discount_percent}% OFF</span>
              <span className="pdp-badge-series">{product.series}</span>

              <img
                src={currentImg}
                alt={`${product.name} - View ${activeImgIndex + 1}`}
                className="pdp-main-image"
              />

              <button
                className="pdp-zoom-btn"
                onClick={(e) => {
                  e.stopPropagation();
                  setLightboxOpen(true);
                }}
              >
                <span>🔍</span>
                <span>Zoom & Inspect</span>
              </button>

              <span className="pdp-counter-badge">
                {activeImgIndex + 1} / {gallery.length}
              </span>

              {gallery.length > 1 && (
                <>
                  <button
                    className="pdp-nav-btn pdp-nav-prev"
                    onClick={(e) => {
                      e.stopPropagation();
                      prevImg();
                    }}
                    aria-label="Previous image"
                  >
                    ‹
                  </button>
                  <button
                    className="pdp-nav-btn pdp-nav-next"
                    onClick={(e) => {
                      e.stopPropagation();
                      nextImg();
                    }}
                    aria-label="Next image"
                  >
                    ›
                  </button>
                </>
              )}
            </div>

            {/* Thumbnail Strip */}
            {gallery.length > 1 && (
              <div className="pdp-thumbs-strip">
                {gallery.map((img, i) => (
                  <button
                    key={i}
                    className={`pdp-thumb-item ${i === activeImgIndex ? 'active' : ''}`}
                    onClick={() => setActiveImgIndex(i)}
                    aria-label={`Select view ${i + 1}`}
                  >
                    <img src={img} alt={`Thumbnail ${i + 1}`} />
                  </button>
                ))}
              </div>
            )}

            {/* Gallery Trust Badges */}
            <div className="pdp-gallery-trust-pills">
              <span className="pdp-gallery-trust-pill">✓ 4:3 Studio White Clean Shot</span>
              <span className="pdp-gallery-trust-pill">✓ CNC Billet Detail Inspected</span>
              <span className="pdp-gallery-trust-pill">✓ Real Vehicle Fit Tested</span>
            </div>
          </div>

          {/* Right Column: Information & Actions */}
          <div className="pdp-info-wrap">
            <div className="pdp-kicker-row">
              <span className="pdp-series-kicker">{product.series} · RACING & OFF-ROAD SPEC</span>
            </div>

            <h1 className="pdp-title">{product.name}</h1>

            <div className="pdp-meta-row">
              <div className="pdp-rating">
                <span className="stars">★★★★★</span>
                <span className="score">5.0</span>
                <span>(28 Verified Reviews)</span>
              </div>
              <div className="pdp-stock-status">
                <span className="pdp-stock-dot" />
                <span>In Stock & Ready to Dispatch</span>
              </div>
              <div className="pdp-sku">SKU: {product.sku}</div>
            </div>

            {/* Guaranteed Vehicle Fitment Card */}
            <div className="pdp-fitment-card">
              <div className="pdp-fitment-card-icon">🚗</div>
              <div className="pdp-fitment-card-body">
                <span className="pdp-fitment-card-title">Guaranteed Vehicle Fitment</span>
                <span className="pdp-fitment-card-val">{product.compatibility}</span>
                <span className="pdp-fitment-card-sub">
                  Direct factory bolt-on · 100% reversible · No drilling or welding required
                </span>
              </div>
            </div>

            {/* Price Box */}
            <div className="pdp-price-wrap">
              <div className="pdp-price-primary-row">
                <span className="pdp-price-current">{product.price}</span>
                <del className="pdp-price-del">{product.regular_price}</del>
                <span className="pdp-price-save-badge">
                  Save ${(product.regular_price_numeric - product.price_numeric).toFixed(2)} (-{product.discount_percent}% OFF)
                </span>
              </div>
              <span className="pdp-price-tax-hint">
                Import taxes included. Worldwide DHL/FedEx Express shipping calculated at checkout.
              </span>
            </div>

            {/* 4 Feature Highlights Grid */}
            <div className="pdp-highlights-grid">
              {highlights.map((h, i) => (
                <div className="pdp-highlight-card" key={i}>
                  <div className="pdp-highlight-header">
                    <span className="icon">✓</span>
                    <span>{h.title}</span>
                  </div>
                  <p className="pdp-highlight-desc">{h.text}</p>
                </div>
              ))}
            </div>

            {/* Purchase Row */}
            <div className="pdp-actions-row">
              <div className="pdp-qty-picker">
                <button
                  className="pdp-qty-btn"
                  onClick={() => setQty((q) => Math.max(1, q - 1))}
                  aria-label="Decrease quantity"
                >
                  -
                </button>
                <span className="pdp-qty-val">{qty}</span>
                <button
                  className="pdp-qty-btn"
                  onClick={() => setQty((q) => q + 1)}
                  aria-label="Increase quantity"
                >
                  +
                </button>
              </div>

              <button
                className="pdp-btn-add"
                onClick={() => {
                  onAdd(product, qty);
                }}
              >
                <span>Add to Cart</span>
                <span>↗</span>
              </button>
            </div>

            {/* Direct WhatsApp Ordering */}
            <a
              href={whatsappUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="pdp-btn-whatsapp"
            >
              <span>💬 Direct Order via WhatsApp (+86-17727960741)</span>
            </a>

            {/* Live Stock & Dispatch Pill */}
            <div className="pdp-shipping-live-pill">
              <span className="pdp-stock-dot" />
              <span>
                <strong>In Stock:</strong> Dispatching within 24h via DHL Express (3-5 days delivery to US/EU).
              </span>
            </div>

            {/* Guarantees Bar */}
            <div className="pdp-trust-grid">
              <div className="pdp-trust-card">
                <span className="trust-icon">✈️</span>
                <span className="trust-title">Global Express</span>
                <span className="trust-desc">DHL / FedEx 3-7 Days</span>
              </div>
              <div className="pdp-trust-card">
                <span className="trust-icon">🛡️</span>
                <span className="trust-title">2-Year Warranty</span>
                <span className="trust-desc">Factory Guarantee</span>
              </div>
              <div className="pdp-trust-card">
                <span className="trust-icon">🔧</span>
                <span className="trust-title">Lossless Fit</span>
                <span className="trust-desc">Zero Drilling Needed</span>
              </div>
              <div className="pdp-trust-card">
                <span className="trust-icon">💬</span>
                <span className="trust-title">24/7 Support</span>
                <span className="trust-desc">Engineering Team</span>
              </div>
            </div>
          </div>
        </div>

        {/* Section A: Engineered for the Wild 3-Card Dark Banner */}
        <div className="pdp-features-strip">
          <div className="pdp-features-strip-title">
            <p className="eyebrow">ENGINEERING EXCELLENCE</p>
            <h2>Built Around the Rigors of the Wild.</h2>
          </div>
          <div className="pdp-features-strip-grid">
            <div className="pdp-features-strip-item">
              <span className="icon">💎</span>
              <h3>6061-T6 Billet & Carbon Fiber</h3>
              <p>Milled from single-billet aerospace aluminum blocks and pre-preg carbon fiber for zero flex and maximum torsional rigidity.</p>
            </div>
            <div className="pdp-features-strip-item">
              <span className="icon">🔧</span>
              <h3>100% Reversible Non-Destructive Fit</h3>
              <p>Engineered directly against 3D laser-scanned OEM chassis data to utilize existing vehicle screw provisions without drilling.</p>
            </div>
            <div className="pdp-features-strip-item">
              <span className="icon">🛡️</span>
              <h3>Mil-Spec Type III Hard Anodizing</h3>
              <p>Electrolytic surface coating impervious to intense UV rays, desert sand blasting, salty mud, and trail abrasions.</p>
            </div>
          </div>
        </div>

        {/* Section B: Tabs Section */}
        <div className="pdp-tabs-container">
          <div className="pdp-tabs-header">
            <button
              className={`pdp-tab-trigger ${activeTab === 'desc' ? 'active' : ''}`}
              onClick={() => setActiveTab('desc')}
            >
              Description & Details
            </button>
            <button
              className={`pdp-tab-trigger ${activeTab === 'specs' ? 'active' : ''}`}
              onClick={() => setActiveTab('specs')}
            >
              Technical Specifications
            </button>
            <button
              className={`pdp-tab-trigger ${activeTab === 'install' ? 'active' : ''}`}
              onClick={() => setActiveTab('install')}
            >
              Installation Manual
            </button>
            <button
              className={`pdp-tab-trigger ${activeTab === 'shipping' ? 'active' : ''}`}
              onClick={() => setActiveTab('shipping')}
            >
              Shipping & Global Logistics
            </button>
          </div>

          <div className="pdp-tab-body">
            {activeTab === 'desc' && (
              <div className="pdp-desc-content">
                {product.cleaned_description ? (
                  <div dangerouslySetInnerHTML={{ __html: product.cleaned_description }} />
                ) : (
                  <>
                    <p>
                      <strong>{product.name}</strong> is precision-machined by MUYE INDUSTRY for demanding off-road conditions. Designed with strict attention to tolerance, structural strength, and seamless aesthetic integration with your vehicle's factory bodylines.
                    </p>
                    <p>
                      Constructed from high-grade CNC billet aluminum and autoclave-cured carbon fiber, this modification provides enhanced durability, trail readiness, and distinct mechanical styling.
                    </p>
                    <ul>
                      <li>Engineered for high stress resistance during overland expeditions.</li>
                      <li>Finished with UV-resistant anodized coating to withstand desert sun and trail debris.</li>
                      <li>Zero drilling or cutting required for standard vehicle models.</li>
                    </ul>
                  </>
                )}
              </div>
            )}

            {activeTab === 'specs' && (
              <table className="pdp-specs-table">
                <tbody>
                  <tr>
                    <th>Brand</th>
                    <td>MUYE INDUSTRY (MUYE CNC)</td>
                  </tr>
                  <tr>
                    <th>Series</th>
                    <td>{product.series}</td>
                  </tr>
                  <tr>
                    <th>Product SKU</th>
                    <td>{product.sku}</td>
                  </tr>
                  <tr>
                    <th>Compatible Vehicle</th>
                    <td>{product.compatibility}</td>
                  </tr>
                  <tr>
                    <th>Construction Material</th>
                    <td>{product.material}</td>
                  </tr>
                  <tr>
                    <th>Surface Finish</th>
                    <td>Type III Hard-Anodized Matte Black / UV-Protected Clear Coat</td>
                  </tr>
                  <tr>
                    <th>Mounting Provision</th>
                    <td>Direct OEM Factory Anchor Points (Lossless Installation)</td>
                  </tr>
                  <tr>
                    <th>Package Contents</th>
                    <td>1 × {product.name}, 1 × Complete Stainless Steel Hardware Pack, 1 × Protective Gasket Set</td>
                  </tr>
                  <tr>
                    <th>Manufacturer Warranty</th>
                    <td>2-Year Limited Global Warranty</td>
                  </tr>
                </tbody>
              </table>
            )}

            {activeTab === 'install' && (
              <div className="pdp-desc-content">
                <h3>Non-Destructive Installation Instructions</h3>
                <p>All MUYE INDUSTRY components are designed for 100% reversible, non-destructive installation:</p>
                <ol style={{ paddingLeft: 20 }}>
                  <li><strong>Preparation:</strong> Clean vehicle mounting area with isopropyl alcohol. Ensure no dust, grease or moisture remains.</li>
                  <li><strong>Hardware Alignment:</strong> Test fit the bracket or accessory against factory mounting holes without tightening screws completely.</li>
                  <li><strong>Gasket Placement:</strong> Place the included protective rubber gaskets between aluminum brackets and vehicle body paint to prevent scratches.</li>
                  <li><strong>Torque Down:</strong> Tighten stainless steel mounting hardware evenly using hand tools. Do not overtighten with impact wrenches.</li>
                  <li><strong>Inspection:</strong> Check tightness after the first 50 miles of off-road driving.</li>
                </ol>
              </div>
            )}

            {activeTab === 'shipping' && (
              <div className="pdp-desc-content">
                <h3>Worldwide Express Delivery</h3>
                <p>We ship worldwide directly from our Shenzhen manufacturing facility via DHL Express, FedEx, and UPS.</p>
                <ul>
                  <li><strong>Order Processing:</strong> Orders are verified and packaged within 24-48 business hours.</li>
                  <li><strong>Delivery Times:</strong> North America & Europe: 3–7 business days; Australia & Asia: 3–5 business days.</li>
                  <li><strong>Tracking:</strong> Complete real-time tracking number provided upon dispatch.</li>
                  <li><strong>Returns:</strong> 30-day money-back guarantee for unused items in original packaging.</li>
                </ul>
              </div>
            )}
          </div>
        </div>

        {/* Section C: Real Vehicle Installation Showcase Lookbook */}
        {lookbookImages.length > 0 && (
          <div className="pdp-lookbook-section">
            <div className="section-heading center">
              <p className="eyebrow">FIELD TESTED</p>
              <h2 className="section-title">Real Vehicle Installation Showcase</h2>
            </div>
            <div className="pdp-lookbook-grid">
              {lookbookImages.map((src, i) => (
                <div
                  key={i}
                  className="pdp-lookbook-item"
                  onClick={() => {
                    const idx = gallery.indexOf(src);
                    if (idx !== -1) setActiveImgIndex(idx);
                    setLightboxOpen(true);
                  }}
                >
                  <img src={src} alt={`${product.name} on vehicle ${i + 1}`} loading="lazy" />
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Section D: Related Products Section */}
        {relatedProducts.length > 0 && (
          <div style={{ marginTop: 80 }}>
            <div className="section-heading center">
              <p className="eyebrow">EXPLORE MORE</p>
              <h2 className="section-title">Related From {product.series}</h2>
            </div>
            <div className="product-grid-3">
              {relatedProducts.map((p) => (
                <ProductCard key={p.id} product={p} onAdd={onAdd} />
              ))}
            </div>
          </div>
        )}
      </div>
    </main>
  );
}

function BlogArticle({ post, path }) {
  const currentPost = post || postsCatalog.find(
    (p) => p.url === path || p.slug === path.replace(/^\//, '').replace(/\/$/, '') || `/blog/${p.slug}/` === path
  ) || postsCatalog[0];

  const related = useMemo(() => {
    return postsCatalog
      .filter((p) => p.id !== currentPost.id)
      .slice(0, 3);
  }, [currentPost]);

  const currentIndex = postsCatalog.findIndex((p) => p.id === currentPost.id);
  const prevPost = currentIndex > 0 ? postsCatalog[currentIndex - 1] : null;
  const nextPost = currentIndex < postsCatalog.length - 1 ? postsCatalog[currentIndex + 1] : null;

  return (
    <main className="article-page-wrap">
      {/* 1. Breadcrumbs */}
      <div className="article-breadcrumbs-wrap">
        <div className="article-container">
          <nav className="breadcrumbs" aria-label="Breadcrumbs">
            <a href="/" onClick={(e) => { e.preventDefault(); go('/'); }}>HOME</a>
            <span>/</span>
            <a href="/our-blog/" onClick={(e) => { e.preventDefault(); go('/our-blog/'); }}>JOURNAL</a>
            <span>/</span>
            <span className="current">{currentPost.title}</span>
          </nav>
        </div>
      </div>

      {/* 2. Article Header */}
      <header className="article-header">
        <div className="article-container article-container-narrow">
          <div className="article-badge-row">
            <span className="article-category-badge">{currentPost.category}</span>
            <span className="article-read-time">{currentPost.read_time}</span>
          </div>
          <h1 className="article-headline">{currentPost.title}</h1>
          <div className="article-meta-card">
            <div className="article-author-avatar">M</div>
            <div className="article-author-info">
              <span className="article-author-name">MUYE Industry Editorial</span>
              <span className="article-publish-date">Published on {currentPost.date}</span>
            </div>
          </div>
        </div>
      </header>

      {/* 3. Hero Feature Image */}
      {currentPost.image && (
        <div className="article-hero-media-wrap">
          <div className="article-container">
            <div className="article-hero-media-box">
              <img src={currentPost.image} alt={currentPost.title} />
            </div>
          </div>
        </div>
      )}

      {/* 4. Article Body Content */}
      <article className="article-main-body">
        <div className="article-container article-container-narrow">
          <div
            className="article-rendered-content"
            dangerouslySetInnerHTML={{ __html: currentPost.content }}
          />

          {/* Social Share Bar */}
          <div className="article-share-bar">
            <span className="article-share-label">Share this article:</span>
            <div className="article-share-btns">
              <a
                href={`https://wa.me/?text=${encodeURIComponent(currentPost.title + ' ' + window.location.href)}`}
                target="_blank"
                rel="noopener noreferrer"
                className="article-share-btn whatsapp"
                title="Share on WhatsApp"
              >
                WhatsApp
              </a>
              <a
                href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(window.location.href)}`}
                target="_blank"
                rel="noopener noreferrer"
                className="article-share-btn facebook"
                title="Share on Facebook"
              >
                Facebook
              </a>
              <button
                type="button"
                className="article-share-btn copy-btn"
                onClick={() => {
                  navigator.clipboard.writeText(window.location.href);
                  alert('Article link copied to clipboard!');
                }}
              >
                Copy Link
              </button>
            </div>
          </div>

          {/* Prev / Next Article Navigation */}
          <div className="article-nav-row">
            {prevPost ? (
              <a
                href={prevPost.url}
                className="article-nav-card prev"
                onClick={(e) => { e.preventDefault(); go(prevPost.url); }}
              >
                <span className="nav-dir">← Previous Story</span>
                <span className="nav-title">{prevPost.title}</span>
              </a>
            ) : <div className="article-nav-card-empty" />}

            {nextPost && (
              <a
                href={nextPost.url}
                className="article-nav-card next"
                onClick={(e) => { e.preventDefault(); go(nextPost.url); }}
              >
                <span className="nav-dir">Next Story →</span>
                <span className="nav-title">{nextPost.title}</span>
              </a>
            )}
          </div>
        </div>
      </article>

      {/* 5. Related Articles Grid */}
      {related.length > 0 && (
        <section className="article-related-section">
          <div className="article-container">
            <div className="section-heading center">
              <p className="eyebrow">KEEP EXPLORING</p>
              <h2 className="section-title">Related Stories</h2>
            </div>
            <div className="blog-grid">
              {related.map((post) => (
                <article
                  key={post.id}
                  className="blog-card"
                  onClick={() => go(post.url)}
                >
                  <div className="blog-card-img-wrap">
                    <img src={post.image} alt={post.title} loading="lazy" />
                    <span className="blog-tag-badge">{post.category}</span>
                  </div>
                  <div className="blog-card-body">
                    <div className="blog-meta-row">
                      <span className="blog-date">{post.date}</span>
                      <span className="blog-meta-dot">•</span>
                      <span className="blog-read-time">{post.read_time}</span>
                    </div>
                    <h3 className="blog-card-title">
                      <a href={post.url} onClick={(e) => { e.preventDefault(); go(post.url); }}>
                        {post.title}
                      </a>
                    </h3>
                    <p className="blog-card-excerpt">{post.excerpt}</p>
                    <div className="blog-card-footer">
                      <span className="blog-read-link">Read Story ↗</span>
                    </div>
                  </div>
                </article>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* 6. Bottom Call to Action */}
      <section className="article-shop-cta">
        <div className="article-container">
          <div className="article-cta-box">
            <div className="article-cta-content">
              <h2>Equip Your Rig with MUYE Precision Upgrades</h2>
              <p>Explore aviation-grade CNC aluminum and authentic carbon fiber accessories engineered specifically for severe off-road conditions.</p>
            </div>
            <a href="/shop-2/" className="article-cta-btn" onClick={(e) => { e.preventDefault(); go('/shop-2/'); }}>
              Explore Collection ↗
            </a>
          </div>
        </div>
      </section>
    </main>
  );
}

/* ===================================================
   PAYMENT & CART HELPERS
   =================================================== */
function normalizeCartItem(product) {
  if (Array.isArray(product)) {
    const priceNum = parseFloat(String(product[3]).replace(/[^0-9.]/g, '')) || 249;
    return {
      id: product[0],
      name: product[0],
      price: product[3],
      priceNum: priceNum,
      image: product[1],
      slug: product[0].toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''),
      quantity: 1,
    };
  }
  const priceNum = parseFloat(String(product.price || product.price_usd || '0').replace(/[^0-9.]/g, '')) || 199;
  return {
    id: product.id || product.slug || product.name,
    name: product.name,
    price: product.price || `$${priceNum.toFixed(2)}`,
    priceNum: priceNum,
    image: product.hero_white || product.image || (product.gallery && product.gallery[0]) || '/products/handle-1.jpg',
    slug: product.slug || (product.name ? product.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '') : ''),
    quantity: product.quantity || 1,
  };
}

function PayPalMonogram({ size = 20 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none" style={{ display: 'inline-block', verticalAlign: 'middle' }}>
      <path d="M7.076 21.337H2.47a.641.641 0 0 1-.633-.74L4.944 2.37A.96.96 0 0 1 5.894 1.6h7.452c3.743 0 6.435 1.572 6.012 5.066-.35 2.894-2.49 5.372-5.717 5.372H10.58l-1.536 8.52a.64.64 0 0 1-.632.545z" fill="#003087"/>
      <path d="M9.972 14.038l1.66-9.243a.96.96 0 0 1 .95-.769h6.398c3.21 0 5.518 1.348 5.155 4.343-.3 2.48-2.135 4.606-4.9 4.606h-2.627l-1.317 7.306a.64.64 0 0 1-.632.545H10.6a.641.641 0 0 1-.628-.788z" fill="#0079C1"/>
      <path d="M8.655 17.652l1.317-7.307h2.627c2.766 0 4.6 2.126 4.9 4.606.363 2.996-1.945 4.344-5.155 4.344H8.655v-1.643z" fill="#00457C"/>
    </svg>
  );
}

function PaymentBadges() {
  return (
    <div className="cart-payment-badges">
      <span className="badge-pill paypal-pill"><PayPalMonogram size={15} /> PayPal</span>
      <span className="badge-pill">VISA</span>
      <span className="badge-pill">Mastercard</span>
      <span className="badge-pill">AMEX</span>
      <span className="badge-pill">Apple Pay</span>
    </div>
  );
}

/* ===================================================
   OFF-CANVAS CART DRAWER COMPONENT
   =================================================== */
function CartDrawer({ isOpen, onClose, cart, onUpdateQty, onRemove, onClear }) {
  if (!isOpen) return null;

  const totalQuantity = cart.reduce((sum, item) => sum + (item.quantity || 1), 0);
  const subtotal = cart.reduce((sum, item) => sum + item.priceNum * (item.quantity || 1), 0);
  const freeShippingThreshold = 500;
  const progressPercent = Math.min(100, Math.round((subtotal / freeShippingThreshold) * 100));

  return (
    <div className="drawer-overlay" onClick={onClose}>
      <aside className="cart-drawer-modern" onClick={(e) => e.stopPropagation()}>
        {/* 1. Header */}
        <div className="cart-drawer-header">
          <div className="cart-drawer-title-row">
            <h3 className="cart-drawer-title">SHOPPING CART</h3>
            <span className="cart-drawer-count-badge">{totalQuantity}</span>
          </div>
          <button className="cart-drawer-close" onClick={onClose} aria-label="Close cart">
            ×
          </button>
        </div>

        {/* 2. Free Shipping Progress Meter */}
        <div className="cart-shipping-meter">
          <div className="shipping-meter-text">
            {subtotal >= freeShippingThreshold ? (
              <span>🎉 You unlocked <strong>FREE Worldwide Express Shipping</strong>!</span>
            ) : (
              <span>
                Add <strong>${(freeShippingThreshold - subtotal).toFixed(2)}</strong> more for <strong>FREE Shipping</strong>
              </span>
            )}
          </div>
          <div className="shipping-meter-bar-track">
            <div className="shipping-meter-bar-fill" style={{ width: `${progressPercent}%` }}></div>
          </div>
        </div>

        {/* 3. Items List or Empty View */}
        {cart.length === 0 ? (
          <div className="cart-drawer-empty">
            <div className="cart-empty-icon">🛍️</div>
            <h4 className="cart-empty-title">YOUR CART IS EMPTY</h4>
            <p className="cart-empty-desc">Discover high-performance CNC aluminum mods, roof racks, and armor.</p>
            <button
              className="cart-empty-btn"
              onClick={() => {
                onClose();
                go(pages.shop);
              }}
            >
              EXPLORE COLLECTION ↗
            </button>
          </div>
        ) : (
          <div className="cart-drawer-items-list">
            {cart.map((item) => (
              <div className="cart-drawer-item" key={item.id}>
                <div
                  className="cart-item-img-box"
                  onClick={() => {
                    onClose();
                    go(`/product/${item.slug}/`);
                  }}
                >
                  <img src={item.image} alt={item.name} />
                </div>
                <div className="cart-item-details">
                  <a
                    href={`/product/${item.slug}/`}
                    className="cart-item-title"
                    onClick={(e) => {
                      e.preventDefault();
                      onClose();
                      go(`/product/${item.slug}/`);
                    }}
                  >
                    {item.name}
                  </a>
                  <div className="cart-item-price-unit">${item.priceNum.toFixed(2)}</div>
                  <div className="cart-item-stepper-row">
                    <div className="cart-stepper">
                      <button
                        type="button"
                        onClick={() => onUpdateQty(item.id, (item.quantity || 1) - 1)}
                        disabled={item.quantity <= 1}
                      >
                        -
                      </button>
                      <span>{item.quantity}</span>
                      <button
                        type="button"
                        onClick={() => onUpdateQty(item.id, (item.quantity || 1) + 1)}
                      >
                        +
                      </button>
                    </div>
                    <button
                      type="button"
                      className="cart-item-remove-btn"
                      onClick={() => onRemove(item.id)}
                    >
                      Remove
                    </button>
                  </div>
                </div>
                <div className="cart-item-line-total">
                  ${(item.priceNum * (item.quantity || 1)).toFixed(2)}
                </div>
              </div>
            ))}
          </div>
        )}

        {/* 4. Footer */}
        {cart.length > 0 && (
          <div className="cart-drawer-footer">
            <div className="cart-drawer-subtotal-row">
              <span className="cart-subtotal-label">SUBTOTAL</span>
              <span className="cart-subtotal-val">${subtotal.toFixed(2)}</span>
            </div>
            <p className="cart-drawer-tax-note">Taxes and shipping calculated at checkout.</p>

            <div className="cart-drawer-actions">
              <button
                className="cart-btn-checkout"
                onClick={() => {
                  onClose();
                  go(pages.checkout);
                }}
              >
                <span>PROCEED TO CHECKOUT</span>
                <span>${subtotal.toFixed(2)} ↗</span>
              </button>
              <button
                className="cart-btn-view-cart"
                onClick={() => {
                  onClose();
                  go(pages.cart);
                }}
              >
                VIEW SHOPPING CART
              </button>
            </div>

            <div className="cart-drawer-trust-badges">
              <span>🔒 256-Bit SSL</span>
              <span>•</span>
              <span><PayPalMonogram size={14} /> PayPal</span>
              <span>•</span>
              <span>🛡️ 1-Yr Warranty</span>
            </div>
          </div>
        )}
      </aside>
    </div>
  );
}

/* ===================================================
   DEDICATED CART PAGE COMPONENT (/cart/)
   =================================================== */
function CartPage({ cart, onUpdateQty, onRemove, onClear }) {
  const [couponCode, setCouponCode] = useState('');
  const [appliedCoupon, setAppliedCoupon] = useState(null);
  const [couponError, setCouponError] = useState('');
  const [orderNote, setOrderNote] = useState('');

  const subtotal = cart.reduce((sum, item) => sum + item.priceNum * (item.quantity || 1), 0);
  const totalQty = cart.reduce((sum, item) => sum + (item.quantity || 1), 0);

  const discount = useMemo(() => {
    if (!appliedCoupon) return 0;
    if (appliedCoupon.type === 'percent') return (subtotal * appliedCoupon.val) / 100;
    if (appliedCoupon.type === 'fixed') return Math.min(subtotal, appliedCoupon.val);
    return 0;
  }, [appliedCoupon, subtotal]);

  const shipping = subtotal >= 500 ? 0 : (appliedCoupon?.freeShip ? 0 : (subtotal > 0 ? 25 : 0));
  const estimatedTotal = Math.max(0, subtotal - discount + shipping);

  const applyCoupon = (e) => {
    e.preventDefault();
    setCouponError('');
    const code = couponCode.trim().toUpperCase();
    if (!code) return;
    if (code === 'MUYE10') {
      setAppliedCoupon({ code: 'MUYE10', type: 'percent', val: 10, label: '10% OFF Special' });
      setCouponCode('');
    } else if (code === 'OFFROAD50') {
      if (subtotal < 200) {
        setCouponError('Minimum order of $200 required for OFFROAD50.');
        return;
      }
      setAppliedCoupon({ code: 'OFFROAD50', type: 'fixed', val: 50, label: '$50 Off' });
      setCouponCode('');
    } else if (code === 'FREESHIP') {
      setAppliedCoupon({ code: 'FREESHIP', type: 'fixed', val: 0, freeShip: true, label: 'Free Express Shipping' });
      setCouponCode('');
    } else {
      setCouponError('Invalid coupon code. Try MUYE10 for 10% off.');
    }
  };

  return (
    <main className="cart-page-wrap">
      <div className="cart-page-container">
        {/* Breadcrumbs */}
        <nav className="breadcrumbs" aria-label="Breadcrumbs" style={{ marginBottom: 24 }}>
          <a href="/" onClick={(e) => { e.preventDefault(); go('/'); }}>HOME</a>
          <span>/</span>
          <span className="current">SHOPPING CART</span>
        </nav>

        <div className="cart-page-header-row">
          <h1 className="cart-page-title">SHOPPING CART</h1>
          <span className="cart-header-count">{totalQty} item{totalQty > 1 ? 's' : ''}</span>
        </div>

        {cart.length === 0 ? (
          <div className="cart-empty-view-card">
            <div className="cart-empty-icon">🛒</div>
            <h2>YOUR SHOPPING CART IS EMPTY</h2>
            <p>You have no items in your cart. Explore our military-grade CNC parts and custom off-road equipment.</p>
            <button className="cart-shop-now-btn" onClick={() => go(pages.shop)}>
              Explore All Products <span>↗</span>
            </button>
          </div>
        ) : (
          <div className="cart-grid-layout">
            {/* Left Column: Items Table & Actions */}
            <div className="cart-table-column">
              <div className="cart-table-wrapper">
                <table className="cart-items-table">
                  <thead>
                    <tr>
                      <th className="th-product">PRODUCT</th>
                      <th className="th-price">PRICE</th>
                      <th className="th-qty">QUANTITY</th>
                      <th className="th-total">SUBTOTAL</th>
                      <th className="th-remove"></th>
                    </tr>
                  </thead>
                  <tbody>
                    {cart.map((item) => (
                      <tr key={item.id} className="cart-row-item">
                        <td className="td-product">
                          <div className="cart-table-product-cell">
                            <a href={`/product/${item.slug}/`} onClick={(e) => { e.preventDefault(); go(`/product/${item.slug}/`); }}>
                              <img src={item.image} alt={item.name} className="cart-table-img" />
                            </a>
                            <div className="cart-table-product-meta">
                              <a href={`/product/${item.slug}/`} className="cart-table-product-name" onClick={(e) => { e.preventDefault(); go(`/product/${item.slug}/`); }}>
                                {item.name}
                              </a>
                              <span className="cart-table-sku">Item ID: #{item.id}</span>
                            </div>
                          </div>
                        </td>
                        <td className="td-price">${item.priceNum.toFixed(2)}</td>
                        <td className="td-qty">
                          <div className="cart-stepper table-stepper">
                            <button type="button" onClick={() => onUpdateQty(item.id, (item.quantity || 1) - 1)} disabled={item.quantity <= 1}>-</button>
                            <span>{item.quantity}</span>
                            <button type="button" onClick={() => onUpdateQty(item.id, (item.quantity || 1) + 1)}>+</button>
                          </div>
                        </td>
                        <td className="td-total">
                          <strong>${(item.priceNum * (item.quantity || 1)).toFixed(2)}</strong>
                        </td>
                        <td className="td-remove">
                          <button
                            type="button"
                            className="cart-remove-cross"
                            onClick={() => onRemove(item.id)}
                            title="Remove item"
                          >
                            ×
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Bottom Row: Coupon & Order Note */}
              <div className="cart-sub-actions-row">
                <div className="cart-coupon-box">
                  <form onSubmit={applyCoupon} className="coupon-form">
                    <input
                      type="text"
                      placeholder="Coupon code (e.g. MUYE10)"
                      value={couponCode}
                      onChange={(e) => setCouponCode(e.target.value)}
                      className="coupon-input"
                    />
                    <button type="submit" className="coupon-apply-btn">Apply</button>
                  </form>
                  {appliedCoupon && (
                    <div className="coupon-success-pill">
                      <span>✓ {appliedCoupon.code} applied ({appliedCoupon.label})</span>
                      <button type="button" onClick={() => setAppliedCoupon(null)}>×</button>
                    </div>
                  )}
                  {couponError && <p className="coupon-error-msg">{couponError}</p>}
                </div>

                <div className="cart-links-row">
                  <button type="button" className="cart-clear-link" onClick={onClear}>Clear Cart</button>
                  <a href={pages.shop} className="cart-continue-link" onClick={(e) => { e.preventDefault(); go(pages.shop); }}>
                    ← Continue Shopping
                  </a>
                </div>
              </div>

              {/* Special Instructions */}
              <div className="cart-order-notes-accordion">
                <label htmlFor="order-note-input" className="order-notes-label">
                  📝 Order Instructions / Special Delivery Request (Optional)
                </label>
                <textarea
                  id="order-note-input"
                  rows={3}
                  placeholder="Special instructions for custom CNC fitting, vehicle model details, or delivery notes..."
                  value={orderNote}
                  onChange={(e) => setOrderNote(e.target.value)}
                  className="order-notes-textarea"
                />
              </div>
            </div>

            {/* Right Column: Order Summary Card */}
            <div className="cart-summary-column">
              <div className="cart-summary-card">
                <h3 className="summary-title">ORDER SUMMARY</h3>

                <div className="summary-row">
                  <span>Subtotal</span>
                  <span className="summary-val">${subtotal.toFixed(2)}</span>
                </div>

                <div className="summary-row">
                  <span>Shipping</span>
                  <span className="summary-val">
                    {shipping === 0 ? <span className="free-tag">FREE</span> : `$${shipping.toFixed(2)}`}
                  </span>
                </div>
                {subtotal < 500 && (
                  <p className="summary-shipping-hint">
                    Add ${(500 - subtotal).toFixed(2)} more to qualify for Free Worldwide Shipping.
                  </p>
                )}

                {discount > 0 && (
                  <div className="summary-row discount-row">
                    <span>Discount ({appliedCoupon.code})</span>
                    <span className="summary-val">-${discount.toFixed(2)}</span>
                  </div>
                )}

                <div className="summary-divider" />

                <div className="summary-total-row">
                  <span>Estimated Total</span>
                  <span className="summary-total-val">${estimatedTotal.toFixed(2)}</span>
                </div>

                <button
                  type="button"
                  className="summary-checkout-btn"
                  onClick={() => go(pages.checkout)}
                >
                  PROCEED TO CHECKOUT <span>↗</span>
                </button>

                {/* PayPal Express Button */}
                <div className="cart-express-paypal-wrap">
                  <div className="express-divider"><span>OR QUICK PAY WITH</span></div>
                  <button
                    type="button"
                    className="paypal-express-btn"
                    onClick={() => go(pages.checkout)}
                  >
                    <PayPalMonogram size={20} />
                    <span>Pay with <strong>PayPal</strong></span>
                  </button>
                </div>

                {/* Trust Badges */}
                <div className="summary-trust-perks">
                  <div className="perk-item">
                    <span className="perk-icon">🛡️</span>
                    <span>1-Year Muye Structural Warranty</span>
                  </div>
                  <div className="perk-item">
                    <span className="perk-icon">✈️</span>
                    <span>Global Express Air Freight with Tracking</span>
                  </div>
                  <div className="perk-item">
                    <span className="perk-icon">🔒</span>
                    <span>256-Bit SSL Encrypted Payment</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </main>
  );
}

/* ===================================================
   CHECKOUT PAGE COMPONENT (/checkout/)
   =================================================== */
function CheckoutPage({ cart, onClearCart }) {
  const [formData, setFormData] = useState({
    email: '',
    phone: '',
    newsletter: true,
    firstName: '',
    lastName: '',
    company: '',
    address: '',
    apartment: '',
    country: 'United States',
    state: '',
    city: '',
    zip: '',
    shippingMethod: 'standard',
    paymentMethod: 'paypal',
    // Card fields
    cardNumber: '',
    cardExp: '',
    cardCvc: '',
    cardName: '',
  });

  const [couponCode, setCouponCode] = useState('');
  const [appliedCoupon, setAppliedCoupon] = useState(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [orderError, setOrderError] = useState('');
  const [paypalSandboxMode, setPaypalSandboxMode] = useState(true);
  const [customPaypalClientId, setCustomPaypalClientId] = useState('');

  const subtotal = cart.reduce((sum, item) => sum + item.priceNum * (item.quantity || 1), 0);
  const totalQty = cart.reduce((sum, item) => sum + (item.quantity || 1), 0);

  const discount = useMemo(() => {
    if (!appliedCoupon) return 0;
    if (appliedCoupon.type === 'percent') return (subtotal * appliedCoupon.val) / 100;
    if (appliedCoupon.type === 'fixed') return Math.min(subtotal, appliedCoupon.val);
    return 0;
  }, [appliedCoupon, subtotal]);

  const shippingCost = formData.shippingMethod === 'express' ? 45 : (subtotal >= 500 ? 0 : 25);
  const grandTotal = Math.max(0, subtotal - discount + shippingCost);

  const applyCoupon = (e) => {
    e.preventDefault();
    const code = couponCode.trim().toUpperCase();
    if (code === 'MUYE10') {
      setAppliedCoupon({ code: 'MUYE10', type: 'percent', val: 10 });
      setCouponCode('');
    } else if (code === 'OFFROAD50') {
      setAppliedCoupon({ code: 'OFFROAD50', type: 'fixed', val: 50 });
      setCouponCode('');
    } else {
      alert('Invalid coupon. Try MUYE10 for 10% off.');
    }
  };

  const handlePlaceOrder = (paymentType = formData.paymentMethod) => {
    if (!formData.email || !formData.firstName || !formData.lastName || !formData.address || !formData.city || !formData.zip) {
      setOrderError('Please complete all required customer and shipping address fields.');
      window.scrollTo({ top: 300, behavior: 'smooth' });
      return;
    }

    setOrderError('');
    setIsProcessing(true);

    const orderId = `MUYE-${new Date().getFullYear()}-${Math.floor(10000 + Math.random() * 90000)}`;
    const transactionId = paymentType === 'paypal' ? `PAYID-${Math.random().toString(36).substring(2, 10).toUpperCase()}` : `CH-${Math.random().toString(36).substring(2, 10).toUpperCase()}`;

    const orderRecord = {
      orderId,
      date: new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }),
      customer: { ...formData },
      items: [...cart],
      subtotal,
      discount,
      shippingCost,
      grandTotal,
      paymentMethod: paymentType === 'paypal' ? 'PayPal Express' : 'Credit Card',
      transactionId,
      status: 'Paid & Processing',
    };

    setTimeout(() => {
      try {
        localStorage.setItem('muye_last_order', JSON.stringify(orderRecord));
        const history = JSON.parse(localStorage.getItem('muye_orders_history') || '[]');
        history.unshift(orderRecord);
        localStorage.setItem('muye_orders_history', JSON.stringify(history));
      } catch (e) {}

      onClearCart();
      setIsProcessing(false);
      go(`/checkout/order-received/?order=${orderId}`);
    }, 1200);
  };

  if (cart.length === 0) {
    return (
      <main className="checkout-empty-wrap">
        <div className="checkout-empty-card">
          <h2>No items in checkout</h2>
          <p>Your shopping cart is currently empty. Please add items before checking out.</p>
          <button className="cart-shop-now-btn" onClick={() => go(pages.shop)}>
            Browse Shop <span>↗</span>
          </button>
        </div>
      </main>
    );
  }

  return (
    <main className="checkout-page-wrap">
      <div className="checkout-container">
        {/* Checkout Header */}
        <header className="checkout-header-bar">
          <div className="checkout-brand-logo" onClick={() => go('/')}>
            <img src={images.logo} alt="MUYE INDUSTRY" />
          </div>
          <div className="checkout-secure-badge">
            <span className="lock-icon">🔒</span>
            <span>256-Bit SSL Encrypted Checkout</span>
          </div>
        </header>

        <div className="checkout-columns-layout">
          {/* Left Column: Form Steps */}
          <div className="checkout-form-col">
            {/* Express PayPal Button */}
            <div className="checkout-express-box">
              <div className="express-head">EXPRESS CHECKOUT</div>
              <button
                type="button"
                className="paypal-big-btn"
                onClick={() => handlePlaceOrder('paypal')}
                disabled={isProcessing}
              >
                <PayPalMonogram size={22} />
                <span>Pay with <strong>PayPal</strong></span>
              </button>
              <div className="checkout-or-divider">
                <span>OR PAY WITH CARD / ENTER ADDRESS BELOW</span>
              </div>
            </div>

            {orderError && <div className="checkout-error-banner">{orderError}</div>}

            {/* Step 1: Contact Information */}
            <section className="checkout-step-section">
              <div className="step-title-row">
                <span className="step-num">1</span>
                <h3>CONTACT INFORMATION</h3>
              </div>
              <div className="form-fields-grid">
                <div className="field-full">
                  <label>Email Address *</label>
                  <input
                    type="email"
                    placeholder="you@example.com"
                    required
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  />
                  <small>Order confirmation and shipping tracking will be sent here.</small>
                </div>
                <div className="field-full">
                  <label>Phone Number *</label>
                  <input
                    type="tel"
                    placeholder="+1 (555) 000-0000"
                    required
                    value={formData.phone}
                    onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                  />
                  <small>Required by international couriers for delivery clearance.</small>
                </div>
                <div className="field-checkbox">
                  <label>
                    <input
                      type="checkbox"
                      checked={formData.newsletter}
                      onChange={(e) => setFormData({ ...formData, newsletter: e.target.checked })}
                    />
                    Keep me updated on exclusive off-road build parts & technical dispatches
                  </label>
                </div>
              </div>
            </section>

            {/* Step 2: Shipping Address */}
            <section className="checkout-step-section">
              <div className="step-title-row">
                <span className="step-num">2</span>
                <h3>SHIPPING ADDRESS</h3>
              </div>
              <div className="form-fields-grid">
                <div className="field-half">
                  <label>First Name *</label>
                  <input
                    type="text"
                    placeholder="First Name"
                    required
                    value={formData.firstName}
                    onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
                  />
                </div>
                <div className="field-half">
                  <label>Last Name *</label>
                  <input
                    type="text"
                    placeholder="Last Name"
                    required
                    value={formData.lastName}
                    onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
                  />
                </div>
                <div className="field-full">
                  <label>Company / Garage (Optional)</label>
                  <input
                    type="text"
                    placeholder="Company name"
                    value={formData.company}
                    onChange={(e) => setFormData({ ...formData, company: e.target.value })}
                  />
                </div>
                <div className="field-full">
                  <label>Street Address *</label>
                  <input
                    type="text"
                    placeholder="123 Overland Trail"
                    required
                    value={formData.address}
                    onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                  />
                </div>
                <div className="field-full">
                  <label>Apartment, Suite, Unit (Optional)</label>
                  <input
                    type="text"
                    placeholder="Suite 4B"
                    value={formData.apartment}
                    onChange={(e) => setFormData({ ...formData, apartment: e.target.value })}
                  />
                </div>
                <div className="field-half">
                  <label>Country / Region *</label>
                  <select
                    value={formData.country}
                    onChange={(e) => setFormData({ ...formData, country: e.target.value })}
                  >
                    <option value="United States">United States</option>
                    <option value="Australia">Australia</option>
                    <option value="Canada">Canada</option>
                    <option value="United Kingdom">United Kingdom</option>
                    <option value="Germany">Germany</option>
                    <option value="United Arab Emirates">United Arab Emirates</option>
                    <option value="Saudi Arabia">Saudi Arabia</option>
                    <option value="China">China</option>
                    <option value="Japan">Japan</option>
                    <option value="Other">Other Country</option>
                  </select>
                </div>
                <div className="field-half">
                  <label>City *</label>
                  <input
                    type="text"
                    placeholder="City"
                    required
                    value={formData.city}
                    onChange={(e) => setFormData({ ...formData, city: e.target.value })}
                  />
                </div>
                <div className="field-half">
                  <label>State / Province *</label>
                  <input
                    type="text"
                    placeholder="State / Region"
                    value={formData.state}
                    onChange={(e) => setFormData({ ...formData, state: e.target.value })}
                  />
                </div>
                <div className="field-half">
                  <label>Postal / ZIP Code *</label>
                  <input
                    type="text"
                    placeholder="ZIP Code"
                    required
                    value={formData.zip}
                    onChange={(e) => setFormData({ ...formData, zip: e.target.value })}
                  />
                </div>
              </div>
            </section>

            {/* Step 3: Shipping Method */}
            <section className="checkout-step-section">
              <div className="step-title-row">
                <span className="step-num">3</span>
                <h3>SHIPPING METHOD</h3>
              </div>
              <div className="shipping-options-list">
                <label className={`shipping-option-card ${formData.shippingMethod === 'standard' ? 'selected' : ''}`}>
                  <input
                    type="radio"
                    name="shippingMethod"
                    value="standard"
                    checked={formData.shippingMethod === 'standard'}
                    onChange={() => setFormData({ ...formData, shippingMethod: 'standard' })}
                  />
                  <div className="shipping-option-info">
                    <strong>Standard Global Insured Freight (7-12 Business Days)</strong>
                    <span>Fully insured against freight damage, includes tracking number</span>
                  </div>
                  <div className="shipping-option-price">
                    {subtotal >= 500 ? <strong className="free-tag">FREE</strong> : '$25.00'}
                  </div>
                </label>

                <label className={`shipping-option-card ${formData.shippingMethod === 'express' ? 'selected' : ''}`}>
                  <input
                    type="radio"
                    name="shippingMethod"
                    value="express"
                    checked={formData.shippingMethod === 'express'}
                    onChange={() => setFormData({ ...formData, shippingMethod: 'express' })}
                  />
                  <div className="shipping-option-info">
                    <strong>DHL / FedEx Priority Air Freight (3-5 Business Days)</strong>
                    <span>Direct priority dispatch with expedited customs brokerage</span>
                  </div>
                  <div className="shipping-option-price">$45.00</div>
                </label>
              </div>
            </section>

            {/* Step 4: Payment Method */}
            <section className="checkout-step-section">
              <div className="step-title-row">
                <span className="step-num">4</span>
                <h3>PAYMENT METHOD</h3>
              </div>

              <div className="payment-method-tabs">
                {/* Tab 1: PayPal */}
                <div
                  className={`payment-tab-box ${formData.paymentMethod === 'paypal' ? 'selected' : ''}`}
                  onClick={() => setFormData({ ...formData, paymentMethod: 'paypal' })}
                >
                  <div className="payment-tab-header">
                    <label className="radio-label">
                      <input
                        type="radio"
                        name="paymentMethod"
                        value="paypal"
                        checked={formData.paymentMethod === 'paypal'}
                        onChange={() => setFormData({ ...formData, paymentMethod: 'paypal' })}
                      />
                      <span className="tab-name">
                        <PayPalMonogram size={18} /> PayPal
                      </span>
                    </label>
                    <span className="payment-badges-inline">
                      <span className="tab-pill">Pay in 4 Available</span>
                    </span>
                  </div>

                  {formData.paymentMethod === 'paypal' && (
                    <div className="payment-tab-body">
                      <p>
                        You will be securely routed through <strong>PayPal</strong> to finalize your purchase. You can pay with your PayPal balance, linked bank account, or any major credit/debit card without sharing financial details.
                      </p>
                      <div className="paypal-smart-button-container">
                        <button
                          type="button"
                          className="paypal-action-button"
                          onClick={() => handlePlaceOrder('paypal')}
                          disabled={isProcessing}
                        >
                          <PayPalMonogram size={20} />
                          <span>{isProcessing ? 'Processing with PayPal...' : `Pay $${grandTotal.toFixed(2)} with PayPal`}</span>
                        </button>
                      </div>

                      {/* Store Integration Details Drawer */}
                      <details className="paypal-dev-settings">
                        <summary>⚙️ PayPal Gateway Integration Settings</summary>
                        <div className="dev-settings-box">
                          <p>
                            <strong>Gateway Status:</strong> Active ({paypalSandboxMode ? 'PayPal Sandbox Mode' : 'Live PayPal Gateway'})
                          </p>
                          <label>
                            PayPal Merchant Client ID:
                            <input
                              type="text"
                              placeholder="sb (Default Sandbox) or Live Client ID"
                              value={customPaypalClientId}
                              onChange={(e) => setCustomPaypalClientId(e.target.value)}
                              className="client-id-input"
                            />
                          </label>
                          <label className="sandbox-toggle">
                            <input
                              type="checkbox"
                              checked={paypalSandboxMode}
                              onChange={(e) => setPaypalSandboxMode(e.target.checked)}
                            />
                            Test in Sandbox Environment
                          </label>
                        </div>
                      </details>
                    </div>
                  )}
                </div>

                {/* Tab 2: Credit Card */}
                <div
                  className={`payment-tab-box ${formData.paymentMethod === 'card' ? 'selected' : ''}`}
                  onClick={() => setFormData({ ...formData, paymentMethod: 'card' })}
                >
                  <div className="payment-tab-header">
                    <label className="radio-label">
                      <input
                        type="radio"
                        name="paymentMethod"
                        value="card"
                        checked={formData.paymentMethod === 'card'}
                        onChange={() => setFormData({ ...formData, paymentMethod: 'card' })}
                      />
                      <span className="tab-name">Credit or Debit Card</span>
                    </label>
                    <PaymentBadges />
                  </div>

                  {formData.paymentMethod === 'card' && (
                    <div className="payment-tab-body">
                      <div className="form-fields-grid">
                        <div className="field-full">
                          <label>Card Number</label>
                          <input
                            type="text"
                            placeholder="4000 1234 5678 9010"
                            maxLength={19}
                            value={formData.cardNumber}
                            onChange={(e) => setFormData({ ...formData, cardNumber: e.target.value })}
                          />
                        </div>
                        <div className="field-half">
                          <label>Expiration (MM/YY)</label>
                          <input
                            type="text"
                            placeholder="MM/YY"
                            maxLength={5}
                            value={formData.cardExp}
                            onChange={(e) => setFormData({ ...formData, cardExp: e.target.value })}
                          />
                        </div>
                        <div className="field-half">
                          <label>Security Code (CVC)</label>
                          <input
                            type="text"
                            placeholder="123"
                            maxLength={4}
                            value={formData.cardCvc}
                            onChange={(e) => setFormData({ ...formData, cardCvc: e.target.value })}
                          />
                        </div>
                        <div className="field-full">
                          <label>Name on Card</label>
                          <input
                            type="text"
                            placeholder="Full Name"
                            value={formData.cardName}
                            onChange={(e) => setFormData({ ...formData, cardName: e.target.value })}
                          />
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </section>

            {/* Submit Button */}
            <div className="checkout-submit-row">
              <button
                type="button"
                className={`checkout-final-btn ${formData.paymentMethod === 'paypal' ? 'btn-paypal-style' : 'btn-card-style'}`}
                onClick={() => handlePlaceOrder(formData.paymentMethod)}
                disabled={isProcessing}
              >
                {isProcessing ? (
                  <span>Processing Secure Order...</span>
                ) : formData.paymentMethod === 'paypal' ? (
                  <span><PayPalMonogram size={18} /> Pay with PayPal • ${grandTotal.toFixed(2)}</span>
                ) : (
                  <span>Complete Order • ${grandTotal.toFixed(2)} ↗</span>
                )}
              </button>
              <p className="checkout-guarantee-note">
                By placing your order, you agree to MUYE Industry's Terms of Service and Privacy Policy. All transactions are protected by 256-bit encryption.
              </p>
            </div>
          </div>

          {/* Right Column: Sticky Summary */}
          <div className="checkout-summary-col">
            <div className="checkout-order-summary-box">
              <h3 className="summary-box-title">ORDER SUMMARY ({totalQty})</h3>

              {/* Items List */}
              <div className="checkout-items-preview">
                {cart.map((item) => (
                  <div className="checkout-item-row" key={item.id}>
                    <div className="checkout-item-thumb-box">
                      <img src={item.image} alt={item.name} />
                      <span className="checkout-item-qty">{item.quantity}</span>
                    </div>
                    <div className="checkout-item-info">
                      <span className="item-name">{item.name}</span>
                      <span className="item-unit-cost">${item.priceNum.toFixed(2)} each</span>
                    </div>
                    <div className="checkout-item-line-total">
                      ${(item.priceNum * (item.quantity || 1)).toFixed(2)}
                    </div>
                  </div>
                ))}
              </div>

              {/* Coupon Row */}
              <form onSubmit={applyCoupon} className="checkout-coupon-row">
                <input
                  type="text"
                  placeholder="Discount code (e.g. MUYE10)"
                  value={couponCode}
                  onChange={(e) => setCouponCode(e.target.value)}
                  className="checkout-coupon-input"
                />
                <button type="submit" className="checkout-coupon-btn">Apply</button>
              </form>
              {appliedCoupon && (
                <div className="coupon-success-pill" style={{ margin: '8px 0' }}>
                  <span>✓ {appliedCoupon.code} applied</span>
                  <button type="button" onClick={() => setAppliedCoupon(null)}>×</button>
                </div>
              )}

              {/* Totals Breakdown */}
              <div className="checkout-totals-block">
                <div className="calc-row">
                  <span>Subtotal</span>
                  <span>${subtotal.toFixed(2)}</span>
                </div>
                {discount > 0 && (
                  <div className="calc-row discount-row">
                    <span>Discount</span>
                    <span>-${discount.toFixed(2)}</span>
                  </div>
                )}
                <div className="calc-row">
                  <span>Shipping</span>
                  <span>{shippingCost === 0 ? <strong className="free-tag">FREE</strong> : `$${shippingCost.toFixed(2)}`}</span>
                </div>
                <div className="calc-row">
                  <span>Estimated Taxes</span>
                  <span>$0.00</span>
                </div>

                <div className="calc-divider" />

                <div className="calc-grand-total">
                  <span>TOTAL DUE (USD)</span>
                  <span className="grand-val">${grandTotal.toFixed(2)}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  );
}

/* ===================================================
   ORDER RECEIVED / CONFIRMATION PAGE
   =================================================== */
function OrderReceivedPage() {
  const [order, setOrder] = useState(null);

  useEffect(() => {
    try {
      const saved = localStorage.getItem('muye_last_order');
      if (saved) {
        setOrder(JSON.parse(saved));
      }
    } catch (e) {}
  }, []);

  const queryParams = new URLSearchParams(window.location.search);
  const displayId = queryParams.get('order') || order?.orderId || 'MUYE-2026-92814';

  return (
    <main className="order-received-wrap">
      <div className="order-received-container">
        {/* Success Header */}
        <div className="order-success-card">
          <div className="success-badge-circle">✓</div>
          <p className="eyebrow">ORDER CONFIRMED</p>
          <h1 className="success-headline">THANK YOU FOR YOUR ORDER!</h1>
          <p className="success-sub">
            Your order <strong>#{displayId}</strong> has been placed and is currently being processed by the MUYE engineering team.
          </p>
          <p className="success-email-notice">
            A confirmation receipt, invoice, and tracking details have been sent to <strong>{order?.customer?.email || 'your email'}</strong>.
          </p>
        </div>

        {/* Order Details Breakdown */}
        <div className="order-details-grid">
          <div className="detail-panel">
            <h3>ORDER DETAILS</h3>
            <div className="detail-row">
              <span className="label">Order Number:</span>
              <strong className="val">#{displayId}</strong>
            </div>
            <div className="detail-row">
              <span className="label">Date:</span>
              <span className="val">{order?.date || new Date().toLocaleDateString()}</span>
            </div>
            <div className="detail-row">
              <span className="label">Payment Status:</span>
              <span className="val status-paid">PAID ({order?.paymentMethod || 'PayPal Express'})</span>
            </div>
            <div className="detail-row">
              <span className="label">Transaction ID:</span>
              <span className="val">{order?.transactionId || 'PAYID-M4589201'}</span>
            </div>
            <div className="detail-row">
              <span className="label">Total Amount:</span>
              <strong className="val total-amount">${(order?.grandTotal || 249.00).toFixed(2)} USD</strong>
            </div>
          </div>

          <div className="detail-panel">
            <h3>SHIPPING & DELIVERY</h3>
            <div className="detail-row">
              <span className="label">Recipient:</span>
              <span className="val">{order?.customer?.firstName} {order?.customer?.lastName}</span>
            </div>
            <div className="detail-row">
              <span className="label">Address:</span>
              <span className="val">
                {order?.customer?.address} {order?.customer?.apartment}, {order?.customer?.city}, {order?.customer?.state} {order?.customer?.zip}, {order?.customer?.country}
              </span>
            </div>
            <div className="detail-row">
              <span className="label">Shipping Method:</span>
              <span className="val">{order?.customer?.shippingMethod === 'express' ? 'DHL / FedEx Priority Express (3-5 Days)' : 'Standard Global Insured Freight (7-12 Days)'}</span>
            </div>
            <div className="detail-row">
              <span className="label">Contact Phone:</span>
              <span className="val">{order?.customer?.phone || '+86-17727960741'}</span>
            </div>
          </div>
        </div>

        {/* Purchased Items Table */}
        {order?.items && order.items.length > 0 && (
          <div className="order-items-card">
            <h3>ITEMS ORDERED</h3>
            <table className="order-receipt-table">
              <thead>
                <tr>
                  <th>Item</th>
                  <th>Quantity</th>
                  <th>Price</th>
                  <th>Total</th>
                </tr>
              </thead>
              <tbody>
                {order.items.map((item, i) => (
                  <tr key={i}>
                    <td>
                      <div className="receipt-item-cell">
                        <img src={item.image} alt={item.name} />
                        <span>{item.name}</span>
                      </div>
                    </td>
                    <td>{item.quantity}</td>
                    <td>${item.priceNum.toFixed(2)}</td>
                    <td>${(item.priceNum * (item.quantity || 1)).toFixed(2)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Action Buttons */}
        <div className="order-actions-bar">
          <button type="button" className="print-btn" onClick={() => window.print()}>
            🖨️ Print Invoice / Receipt
          </button>
          <button type="button" className="continue-shopping-btn" onClick={() => go(pages.shop)}>
            Continue Shopping <span>↗</span>
          </button>
        </div>
      </div>
    </main>
  );
}

/* ===================================================
   MAIN APP COMPONENT
   =================================================== */
function App() {
  const [path, setPath] = useState(window.location.pathname);
  const [cart, setCart] = useState(() => {
    try {
      const saved = localStorage.getItem('muye_cart');
      return saved ? JSON.parse(saved) : [];
    } catch (e) {
      return [];
    }
  });
  const [cartOpen, setCartOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    const listener = () => setPath(window.location.pathname);
    window.addEventListener('popstate', listener);
    return () => window.removeEventListener('popstate', listener);
  }, []);

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

  const add = (product, qty = 1) => {
    const item = normalizeCartItem(product);
    setCart((prev) => {
      const existingIndex = prev.findIndex((p) => p.name === item.name || p.id === item.id);
      if (existingIndex >= 0) {
        const next = [...prev];
        next[existingIndex] = {
          ...next[existingIndex],
          quantity: (next[existingIndex].quantity || 1) + qty,
        };
        return next;
      }
      return [...prev, { ...item, quantity: qty }];
    });
    setCartOpen(true);
  };

  const updateQuantity = (id, newQty) => {
    if (newQty <= 0) {
      removeFromCart(id);
      return;
    }
    setCart((prev) =>
      prev.map((item) => (item.id === id ? { ...item, quantity: newQty } : item))
    );
  };

  const removeFromCart = (id) => {
    setCart((prev) => prev.filter((item) => item.id !== id));
  };

  const clearCart = () => {
    setCart([]);
  };

  const cartTotalQty = useMemo(() => {
    return cart.reduce((sum, item) => sum + (item.quantity || 1), 0);
  }, [cart]);

  const handleSearch = (term, category) => {
    setSearchQuery(term);
    if (category === 'nept') go(pages.nept);
    else if (category === 'neptr') go(pages.neptr);
    else if (category === 'more') go(pages.more);
    else go(pages.shop);
  };

  // Find article match
  const matchedPost = postsCatalog.find(
    (p) => p.url === path || p.slug === path.replace(/^\//, '').replace(/\/$/, '') || `/blog/${p.slug}/` === path
  );

  let content;
  if (path === '/' || path === '') content = <Home onAdd={add} />;
  else if (path === pages.shop) content = <Listing kind="shop" onAdd={add} searchQuery={searchQuery} />;
  else if (path === pages.more) content = <Listing kind="more" onAdd={add} searchQuery={searchQuery} />;
  else if (path === pages.nept) content = <Listing kind="nept" onAdd={add} searchQuery={searchQuery} />;
  else if (path === pages.neptr) content = <Listing kind="neptr" onAdd={add} searchQuery={searchQuery} />;
  else if (path === pages.brand) content = <Brand />;
  else if (path === pages.blog) content = <Blog />;
  else if (path === pages.contact) content = <Contact />;
  else if (path === pages.supports) content = <GenericPage title="Supports Center" />;
  else if (path === pages.cart) content = <CartPage cart={cart} onUpdateQty={updateQuantity} onRemove={removeFromCart} onClear={clearCart} />;
  else if (path.startsWith('/checkout/order-received')) content = <OrderReceivedPage />;
  else if (path === pages.checkout) content = <CheckoutPage cart={cart} onClearCart={clearCart} />;
  else if (path.startsWith('/product/')) content = <ProductPage slug={path.replace('/product/', '').replace(/\/$/, '')} onAdd={add} />;
  else if (matchedPost) content = <BlogArticle post={matchedPost} path={path} />;
  else if (articleSlugs.includes(path)) content = <BlogArticle path={path} />;
  else if (path === '/shipping-delivery-policy/') content = <GenericPage title="Shipping & Delivery Policy" eyebrow="Policies"><p>Orders are prepared after payment confirmation.</p></GenericPage>;
  else if (path === '/refund_returns/') content = <GenericPage title="Refund and Returns Policy" eyebrow="Policies"><p>Contact our support team for assistance.</p></GenericPage>;
  else if (path === '/privacy-policy/') content = <GenericPage title="Privacy Policy" eyebrow="Policies"><p>Your privacy matters.</p></GenericPage>;
  else if (['/my-account-2/', '/wishlist/', '/page-404/'].includes(path)) content = <GenericPage title={prettySlug(path)} />;
  else content = <GenericPage title="Page not found" eyebrow="404" />;

  return (
    <>
      <Header
        currentPath={path}
        cartCount={cartTotalQty}
        onCart={() => setCartOpen(true)}
        onSearch={handleSearch}
      />
      {content}
      <Footer />

      {/* Modern Cart Drawer */}
      <CartDrawer
        isOpen={cartOpen}
        onClose={() => setCartOpen(false)}
        cart={cart}
        onUpdateQty={updateQuantity}
        onRemove={removeFromCart}
        onClear={clearCart}
      />
    </>
  );
}

createRoot(document.getElementById('root')).render(<App />);
