<?php
require_once __DIR__ . '/includes/config.php';

// ── Filters ─────────────────────────────────────────────────────────────────────
$selectedYear  = $_GET['year']  ?? '';
$selectedMake  = $_GET['make']  ?? '';
$selectedModel = $_GET['model'] ?? '';

$filters = [];
if ($selectedYear && $selectedMake && $selectedModel) {
    $filters = ['year' => $selectedYear, 'make' => $selectedMake, 'model' => $selectedModel];
}
$products   = getProducts($filters);
$years      = getAllYears();
$makes      = getAllBrands();
$models     = getAllModels();
$totalCount = count($products);

// ── SEO ─────────────────────────────────────────────────────────────────────────
$pageTitle       = SITE_NAME . ' | Premium Aftermarket Dirt Bike Parts, Engine Rebuilds & Race Components';
$metaDescription = 'Shop premium aftermarket dirt bike parts at ' . SITE_NAME . '. Exact year-make-model fitment for Honda, Yamaha, KTM, Kawasaki, Suzuki, and Husqvarna. Free shipping on orders over $99.';
$canonicalUrl    = siteUrl('/');

// ── Schema ──────────────────────────────────────────────────────────────────────
ob_start(); ?>
<script type="application/ld+json">
{
  "@context": "https://schema.org/",
  "@type": "ItemList",
  "name": "<?= SITE_NAME ?> Premium Dirt Bike Parts Catalog",
  "description": "Browse our complete catalog of premium aftermarket dirt bike parts with exact year-make-model fitment.",
  "numberOfItems": <?= $totalCount ?>,
  "itemListElement": [
    <?php foreach ($products as $i => $p): ?>
    {
      "@type": "ListItem",
      "position": <?= $i + 1 ?>,
      "item": {
        "@type": "Product",
        "name": "<?= e($p['name']) ?>",
        "image": "<?= siteUrl($p['image_url'] ?? '') ?>",
        "description": "<?= e(substr($p['description'] ?? '', 0, 200)) ?>",
        "sku": "<?= e($p['sku']) ?>",
        "brand": {"@type": "Brand", "name": "<?= e($p['brand_name']) ?>"},
        "offers": {
          "@type": "Offer",
          "priceCurrency": "USD",
          "price": "<?= number_format($p['discount_price'], 2, '.', '') ?>",
          "itemCondition": "https://schema.org/NewCondition",
          "availability": "<?= $p['stock'] > 0 ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock' ?>",
          "url": "<?= siteUrl('product.php?slug=' . urlencode($p['slug'])) ?>"
        }
      }
    }<?= $i < $totalCount - 1 ? ',' : '' ?>
    <?php endforeach; ?>
  ]
}
</script>
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {"@type": "Question", "name": "What dirt bike brands does <?= SITE_NAME ?> carry parts for?", "acceptedAnswer": {"@type": "Answer", "text": "<?= SITE_NAME ?> stocks premium aftermarket parts for all major motocross and off-road brands including Honda CRF, Yamaha YZ, KTM SX/EXC, Kawasaki KX, Suzuki RM-Z, and Husqvarna FC/FE. Every part is cross-referenced against OEM specifications to guarantee exact bolt-on fitment."}},
    {"@type": "Question", "name": "How does <?= SITE_NAME ?> guarantee exact fitment for dirt bike parts?", "acceptedAnswer": {"@type": "Answer", "text": "<?= SITE_NAME ?> uses a proprietary Year-Make-Model (YMM) fitment database that cross-references every aftermarket part against original equipment manufacturer tolerances."}},
    {"@type": "Question", "name": "Does <?= SITE_NAME ?> offer free shipping on dirt bike parts?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. <?= SITE_NAME ?> offers free ground shipping on all orders over $99 within the continental United States. Most orders placed before 2PM PST ship same-day."}},
    {"@type": "Question", "name": "What types of dirt bike parts does <?= SITE_NAME ?> sell?", "acceptedAnswer": {"@type": "Answer", "text": "<?= SITE_NAME ?> specializes in premium aftermarket dirt bike components including high-compression pistons, complete engine rebuild kits, FMF and Pro Circuit exhaust systems, ProTaper and Renthal handlebars, titanium sprocket kits, heavy-duty chains, radiator hose kits, clutch assemblies, suspension components, and Acerbis plastic body kits."}}
  ]
}
</script>
<?php $schemaMarkup = ob_get_clean();

require_once __DIR__ . '/includes/header.php';
?>

<!-- Hero Section -->
<section class="relative overflow-hidden bg-brand-dark pt-16 pb-32" aria-label="Hero Banner">
    <div class="absolute inset-0 z-0 opacity-20 bg-[url('https://images.unsplash.com/photo-1557999865-c32f3c051fe8?q=80&w=2000&auto=format&fit=crop')] bg-cover bg-center"></div>
    <div class="absolute inset-0 bg-gradient-to-b from-brand-dark/50 via-brand-dark to-[#0B0C10] z-10"></div>
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-20 text-center">
        <h1 class="text-5xl md:text-7xl font-black text-white tracking-tight uppercase italic drop-shadow-2xl mb-4">
            Dominate The <span class="text-brand-orange text-transparent bg-clip-text bg-gradient-to-r from-brand-orange to-[#ff7b00]">Track.</span>
        </h1>
        <p class="mt-4 max-w-2xl text-xl text-gray-300 mx-auto font-semibold">
            Premium aftermarket dirt bike parts with exact year-make-model fitment. Real-time inventory. Get your machine race-ready with bolt-on upgrades from top brands like FMF, ProTaper, Renthal, and Vertex.
        </p>
    </div>
</section>

<!-- YMM Selector -->
<section class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 relative z-30 -mt-16 mb-16" aria-label="Find Parts by Year, Make, and Model">
    <div class="bg-gray-900 border border-gray-800 rounded-xl p-6 shadow-2xl backdrop-blur-xl bg-opacity-80">
        <form action="/" method="GET" class="flex flex-col md:flex-row gap-4 items-end" aria-label="Vehicle Fitment Selector">
            <div class="w-full md:w-1/4">
                <label for="ymm-year" class="block text-sm font-bold text-gray-400 uppercase tracking-widest mb-2">Year</label>
                <select id="ymm-year" name="year" class="w-full bg-black border border-gray-700 text-white rounded-lg px-4 py-3 focus:outline-none focus:border-brand-orange focus:ring-1 focus:ring-brand-orange appearance-none transition-colors font-semibold">
                    <option value="">Any Year</option>
                    <?php foreach ($years as $y): ?>
                        <option value="<?= e($y['year']) ?>" <?= $selectedYear == $y['year'] ? 'selected' : '' ?>><?= e($y['year']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="w-full md:w-1/4">
                <label for="ymm-make" class="block text-sm font-bold text-gray-400 uppercase tracking-widest mb-2">Make</label>
                <select id="ymm-make" name="make" class="w-full bg-black border border-gray-700 text-white rounded-lg px-4 py-3 focus:outline-none focus:border-brand-orange focus:ring-1 focus:ring-brand-orange appearance-none transition-colors font-semibold">
                    <option value="">Any Make</option>
                    <?php foreach ($makes as $m): ?>
                        <option value="<?= e($m['slug']) ?>" <?= $selectedMake == $m['slug'] ? 'selected' : '' ?>><?= e($m['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="w-full md:w-1/4">
                <label for="ymm-model" class="block text-sm font-bold text-gray-400 uppercase tracking-widest mb-2">Model</label>
                <select id="ymm-model" name="model" class="w-full bg-black border border-gray-700 text-white rounded-lg px-4 py-3 focus:outline-none focus:border-brand-orange focus:ring-1 focus:ring-brand-orange appearance-none transition-colors font-semibold">
                    <option value="">Any Model</option>
                    <?php foreach ($models as $mod): ?>
                        <option value="<?= e($mod['slug']) ?>" <?= $selectedModel == $mod['slug'] ? 'selected' : '' ?>><?= e($mod['brand_name'] . ' ' . $mod['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="w-full md:w-1/4">
                <button type="submit" class="w-full bg-brand-orange hover:bg-[#ff5511] text-white font-bold py-3 px-6 rounded-lg transition-all shadow-[0_0_15px_rgba(255,69,0,0.4)] hover:shadow-[0_0_25px_rgba(255,69,0,0.6)] uppercase tracking-wider">Find Parts</button>
            </div>
        </form>
        <?php if ($selectedYear || $selectedMake || $selectedModel): ?>
        <div class="mt-4 text-center">
            <a href="/" class="text-sm text-gray-500 hover:text-white transition-colors underline decoration-gray-700 hover:decoration-white">Clear Filters</a>
        </div>
        <?php endif; ?>
    </div>
</section>

<!-- Product Grid -->
<section class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mb-24" aria-label="Product Catalog">
    <div class="flex items-center justify-between mb-8">
        <h2 class="text-3xl font-bold text-white tracking-tight">Available Upgrades</h2>
        <span class="bg-gray-800 text-gray-300 text-sm font-semibold px-3 py-1 rounded-full border border-gray-700"><?= $totalCount ?> Results</span>
    </div>

    <?php if (empty($products)): ?>
        <div class="text-center py-20 bg-gray-900/50 rounded-2xl border border-gray-800 border-dashed">
            <svg class="h-16 w-16 text-gray-600 mx-auto mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
            <h3 class="text-xl font-bold text-white mb-2">No Parts Found</h3>
            <p class="text-gray-400">We couldn't find any specific parts matching your exact dirt bike configuration.</p>
        </div>
    <?php else: ?>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8 w-full">
            <?php foreach ($products as $product): ?>
            <article class="group bg-gray-900 rounded-xl border border-gray-800 overflow-hidden hover:border-gray-600 transition-all duration-300 shadow-lg hover:shadow-2xl flex flex-col h-full">
                <a href="/product.php?slug=<?= urlencode($product['slug']) ?>" class="relative h-64 overflow-hidden bg-black flex items-center justify-center p-4 block">
                    <img src="<?= e($product['image_url'] ?: 'https://placehold.co/600x400/111/333?text=No+Image') ?>" alt="<?= e($product['name']) ?> - <?= e($product['brand_name']) ?> aftermarket dirt bike part" class="transform group-hover:scale-105 transition-transform duration-500 max-h-full object-contain filter drop-shadow-[0_10px_10px_rgba(0,0,0,0.8)]" loading="lazy" width="600" height="400">
                    <div class="absolute top-4 right-4 bg-brand-orange text-white text-xs font-black px-2 py-1 rounded uppercase tracking-widest shadow-md z-10 transform -rotate-2">20% OFF</div>
                </a>
                <div class="p-6 flex flex-col flex-grow">
                    <div class="text-xs font-bold text-gray-500 uppercase tracking-widest mb-1"><?= e($product['category_name']) ?></div>
                    <a href="/product.php?slug=<?= urlencode($product['slug']) ?>" class="hover:text-brand-orange transition-colors">
                        <h3 class="text-lg font-bold text-white leading-tight mb-2"><?= e($product['name']) ?></h3>
                    </a>
                    <p class="text-sm text-gray-400 line-clamp-2 mb-4 flex-grow"><?= e($product['description'] ?? '') ?></p>
                    <div class="flex items-end justify-between mt-auto pt-4 border-t border-gray-800">
                        <div>
                            <span class="block text-sm text-gray-500 line-through mb-1">MSRP: $<?= number_format($product['msrp_price'], 2) ?></span>
                            <span class="block text-2xl font-black text-white">$<?= number_format($product['discount_price'], 2) ?></span>
                        </div>
                        <form action="/cart-action.php" method="POST">
                            <input type="hidden" name="action" value="add">
                            <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                            <button type="submit" class="bg-white/10 hover:bg-white text-white hover:text-black font-bold p-3 rounded-lg transition-all group-hover:shadow-[0_0_15px_rgba(255,255,255,0.2)]" aria-label="Add <?= e($product['name']) ?> to cart">
                                <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" /></svg>
                            </button>
                        </form>
                    </div>
                </div>
            </article>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</section>

<!-- Authority Content Section -->
<section class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mb-24" aria-label="About <?= SITE_NAME ?>">
    <div class="bg-gray-900/50 border border-gray-800 rounded-2xl p-8 md:p-12">
        <h2 class="text-3xl font-bold text-white tracking-tight mb-6">Why Riders Choose <?= SITE_NAME ?> for Aftermarket Dirt Bike Parts</h2>
        <div class="prose prose-invert prose-lg max-w-none text-gray-400">
            <p><?= SITE_NAME ?> is the premier online destination for <strong>premium aftermarket dirt bike parts</strong> engineered for competitive motocross, enduro, and trail riding. Unlike generic parts distributors, every component in our catalog has been cross-referenced against original equipment manufacturer (OEM) specifications using our proprietary <strong>Year-Make-Model (YMM) fitment database</strong>, guaranteeing bolt-on compatibility on the first try.</p>
            <p>We source directly from industry-leading manufacturers including <strong>FMF Racing</strong>, <strong>ProTaper</strong>, <strong>Renthal</strong>, <strong>Vertex Pistons</strong>, <strong>Acerbis</strong>, <strong>Pro Circuit</strong>, and <strong>Wiseco</strong>. Our inventory spans high-compression pistons, complete engine rebuild kits, exhaust systems, handlebars, sprocket and chain kits, radiator hose assemblies, clutch components, suspension upgrades, and full plastic body kits.</p>
            <p>Whether you are rebuilding a <strong>Honda CRF250R</strong> top-end, upgrading your <strong>KTM 450 SX-F</strong> exhaust, or fitting new bars on a <strong>Yamaha YZ125</strong>, <?= SITE_NAME ?> eliminates the guesswork with exact fitment data for every product we sell. All orders over $99 ship free within the continental United States, and most orders placed before 2PM PST ship same-day.</p>
        </div>
    </div>
</section>

<!-- FAQ Section -->
<section class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mb-24" aria-label="Frequently Asked Questions">
    <h2 class="text-3xl font-bold text-white tracking-tight mb-8">Frequently Asked Questions</h2>
    <div class="space-y-4">
        <?php
        $faqs = [
            ['What dirt bike brands does ' . SITE_NAME . ' carry parts for?', SITE_NAME . ' stocks premium aftermarket parts for all major motocross and off-road brands including Honda CRF, Yamaha YZ, KTM SX/EXC, Kawasaki KX, Suzuki RM-Z, and Husqvarna FC/FE. Every part is cross-referenced against OEM specifications to guarantee exact bolt-on fitment.'],
            ['How does ' . SITE_NAME . ' guarantee exact fitment?', SITE_NAME . ' uses a proprietary Year-Make-Model (YMM) fitment database that cross-references every aftermarket part against original equipment manufacturer tolerances. Each product listing specifies exact compatible models down to the production year, eliminating guesswork.'],
            ['Does ' . SITE_NAME . ' offer free shipping?', 'Yes. ' . SITE_NAME . ' offers free ground shipping on all orders over $99 within the continental United States. Most orders placed before 2PM PST ship same-day from our warehouse, with typical delivery in 3-5 business days.'],
            ['What types of dirt bike parts does ' . SITE_NAME . ' sell?', SITE_NAME . ' specializes in premium aftermarket dirt bike components including high-compression pistons, complete engine rebuild kits, FMF and Pro Circuit exhaust systems, ProTaper and Renthal handlebars, titanium sprocket kits, heavy-duty chains, radiator hose kits, clutch assemblies, suspension components, and Acerbis plastic body kits.'],
        ];
        foreach ($faqs as $idx => $faq): ?>
        <details class="group bg-gray-900 border border-gray-800 rounded-xl overflow-hidden" <?= $idx === 0 ? 'open' : '' ?>>
            <summary class="flex items-center justify-between p-6 cursor-pointer font-bold text-white text-lg hover:text-brand-orange transition-colors">
                <?= e($faq[0]) ?>
                <svg class="w-5 h-5 text-gray-500 group-open:rotate-180 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
            </summary>
            <div class="px-6 pb-6 text-gray-400 leading-relaxed"><?= e($faq[1]) ?></div>
        </details>
        <?php endforeach; ?>
    </div>
</section>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
