@extends('layouts.app')

@section('title', "MJ's Bikes & Accessories Marketplace - Online Showroom")

@section('content')

<!-- HERO BANNER SECTION (CAROUSEL) -->
<section class="hero-section hero-carousel-section">
    @if($slides->count() > 0)
        <div id="heroCarousel" class="carousel slide carousel-fade" data-bs-ride="carousel" data-bs-interval="6000" data-bs-pause="hover" data-bs-touch="true">
            <div class="carousel-indicators hero-carousel-indicators">
                @foreach($slides as $index => $slide)
                    <button type="button" data-bs-target="#heroCarousel" data-bs-slide-to="{{ $index }}" class="{{ $index === 0 ? 'active' : '' }}" aria-current="{{ $index === 0 ? 'true' : 'false' }}" aria-label="Slide {{ $index + 1 }}: {{ strip_tags($slide->title) }}"></button>
                @endforeach
            </div>

            <div class="hero-slide-counter" aria-live="polite">
                <span id="heroSlideCurrent">1</span> / {{ $slides->count() }}
            </div>

            <div class="carousel-inner">
                @foreach($slides as $index => $slide)
                    @php
                        $isAd = $slide->isAdType();
                        $linkTarget = $slide->linkTarget();
                        $fallbackImg = asset('assets/images/hero-fallback.svg');
                    @endphp
                    <div class="carousel-item {{ $index === 0 ? 'active' : '' }} hero-slide-overlay" data-slide-id="{{ $slide->id }}" style="background-image: url('{{ $slide->imageUrl() }}');">
                        <div class="hero-overlay-gradient"></div>
                        <div class="container position-relative z-index-2">
                            <div class="row align-items-center hero-slide-row" style="min-height: 550px;">
                                <div class="col-lg-7 text-center text-lg-start py-5 py-lg-0 hero-slide-content">
                                    @if($slide->badge_text)
                                        <span class="badge {{ $isAd ? 'bg-warning text-dark' : 'bg-danger' }} rounded-pill px-3 py-2 mb-4 text-uppercase fw-semibold hero-slide-badge" style="letter-spacing: 1px;">
                                            @if($isAd)<i class="bi bi-megaphone-fill me-1"></i>@endif
                                            {{ $slide->badge_text }}
                                        </span>
                                    @endif
                                    <h1 class="display-3 fw-extrabold text-white mb-3 text-uppercase brand-font hero-slide-title" style="letter-spacing: 0.02em;">
                                        {!! $slide->title !!}
                                    </h1>
                                    @if($slide->subtitle)
                                        <p class="lead text-light mb-4 opacity-75 hero-slide-subtitle">
                                            {{ $slide->subtitle }}
                                        </p>
                                    @endif
                                    <div class="d-flex flex-column flex-sm-row justify-content-center justify-content-lg-start gap-3 hero-slide-actions position-relative z-index-3">
                                        @if($slide->button_text)
                                            <a href="{{ $slide->button_link ?? '#' }}"
                                               class="btn btn-primary-mj btn-lg rounded-pill px-4 py-3 text-uppercase fs-6"
                                               target="{{ $linkTarget }}"
                                               @if($slide->open_in_new_tab) rel="noopener noreferrer" @endif
                                               data-track-slide="{{ $slide->id }}">
                                                {{ $slide->button_text }} <i class="bi bi-arrow-right ms-2"></i>
                                            </a>
                                        @endif
                                        @if($slide->button2_text)
                                            <a href="{{ $slide->button2_link ?? '#' }}"
                                               class="btn btn-outline-light btn-lg rounded-pill px-4 py-3 text-uppercase fs-6"
                                               target="{{ $linkTarget }}"
                                               @if($slide->open_in_new_tab) rel="noopener noreferrer" @endif
                                               data-track-slide="{{ $slide->id }}">
                                                {{ $slide->button2_text }}
                                                @if(str_contains(strtolower($slide->button2_text), 'repair'))
                                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="ms-2" style="width: 20px; height: 20px; display: inline-block; vertical-align: text-bottom;">
                                                        <path stroke-linecap="round" stroke-linejoin="round" d="M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085m-1.745 1.437L5.909 7.5H4.5L2.25 3.75l1.5-1.5L7.5 4.5v1.409l4.26 4.26m-1.745 1.437l1.745-1.437m6.615 8.206L15.75 15.75M4.867 19.125h.008v.008h-.008v-.008z" />
                                                    </svg>
                                                @else
                                                    <i class="bi bi-arrow-right ms-2"></i>
                                                @endif
                                            </a>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>

            @if($slides->count() > 1)
                <!-- Controls repositioned and nested properly to avoid overlapping with buttons on mobile -->
                <button class="carousel-control-prev hero-carousel-control z-index-3" type="button" data-bs-target="#heroCarousel" data-bs-slide="prev" style="left: 10px; width: 40px; height: 40px; top: 50%; transform: translateY(-50%); opacity: 0.8; background: rgba(0,0,0,0.3); border-radius: 50%;">
                    <span class="hero-carousel-control-icon" aria-hidden="true"><i class="bi bi-chevron-left" style="font-size: 1.2rem;"></i></span>
                    <span class="visually-hidden">Previous</span>
                </button>
                <button class="carousel-control-next hero-carousel-control z-index-3" type="button" data-bs-target="#heroCarousel" data-bs-slide="next" style="right: 10px; width: 40px; height: 40px; top: 50%; transform: translateY(-50%); opacity: 0.8; background: rgba(0,0,0,0.3); border-radius: 50%;">
                    <span class="hero-carousel-control-icon" aria-hidden="true"><i class="bi bi-chevron-right" style="font-size: 1.2rem;"></i></span>
                    <span class="visually-hidden">Next</span>
                </button>
            @endif
        </div>
    @else
        <!-- FALLBACK TO STATIC HERO -->
        <div class="hero-slide-overlay" style="background-image: url('{{ mjs_image(\App\Models\Setting::get('hero_image'), 'hero-fallback') }}');">
            <div class="hero-overlay-gradient"></div>
            <div class="container position-relative z-index-2">
                <div class="row align-items-center hero-slide-row" style="min-height: 550px;">
                    <div class="col-lg-7 text-center text-lg-start py-5 py-lg-0 hero-slide-content">
                        <span class="badge bg-danger rounded-pill px-3 py-2 mb-4 text-uppercase fw-semibold" style="letter-spacing: 1px;">
                            {{ \App\Models\Setting::get('hero_badge', 'Discover Premium Rides') }}
                        </span>
                        <h1 class="display-3 fw-extrabold text-white mb-3 text-uppercase brand-font hero-slide-title" style="letter-spacing: 0.02em;">
                            {!! \App\Models\Setting::get('hero_title', 'MJ\'s Bikes & <br><span class="text-danger">Accessories</span>') !!}
                        </h1>
                        <p class="lead text-light mb-4 opacity-75 hero-slide-subtitle">
                            {{ \App\Models\Setting::get('hero_subtitle', 'Your ultimate digital bicycle showroom. Discover premium rides, top-tier spare parts, and book certified repair services instantly.') }}
                        </p>
                        <div class="d-flex flex-column flex-sm-row justify-content-center justify-content-lg-start gap-3 position-relative z-index-3">
                            <a href="{{ route('marketplace.index') }}" class="btn btn-primary-mj btn-lg rounded-pill px-4 py-3 text-uppercase fs-6">
                                Explore Showroom <i class="bi bi-arrow-right ms-2"></i>
                            </a>
                            <a href="{{ route('services.book') }}" class="btn btn-outline-light btn-lg rounded-pill px-4 py-3 text-uppercase fs-6">
                                Book Repair Service 
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="ms-2" style="width: 20px; height: 20px; display: inline-block; vertical-align: text-bottom;">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085m-1.745 1.437L5.909 7.5H4.5L2.25 3.75l1.5-1.5L7.5 4.5v1.409l4.26 4.26m-1.745 1.437l1.745-1.437m6.615 8.206L15.75 15.75M4.867 19.125h.008v.008h-.008v-.008z" />
                                </svg>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    @endif
</section>

<!-- CATEGORY HIGHLIGHTS (QUICK TABS) -->
<section class="py-5 bg-white border-bottom">
    <div class="container">
        <div class="row row-cols-2 row-cols-md-4 g-3 justify-content-center text-center">
            <div class="col">
                <a href="{{ route('marketplace.index', ['type' => 'bike']) }}" class="card border-0 shadow-sm rounded-4 p-3 text-decoration-none text-dark bg-light hover-shadow transition">
                    <div class="text-danger fs-1 mb-2"><i class="bi bi-bicycle"></i></div>
                    <h6 class="fw-bold mb-0">Bicycles</h6>
                </a>
            </div>
            <div class="col">
                <a href="{{ route('marketplace.index', ['type' => 'spare_part']) }}" class="card border-0 shadow-sm rounded-4 p-3 text-decoration-none text-dark bg-light hover-shadow transition">
                    <div class="text-danger fs-1 mb-2"><i class="bi bi-gear-fill"></i></div>
                    <h6 class="fw-bold mb-0">Spares</h6>
                </a>
            </div>
            <div class="col">
                <a href="{{ route('marketplace.index', ['type' => 'accessory']) }}" class="card border-0 shadow-sm rounded-4 p-3 text-decoration-none text-dark bg-light hover-shadow transition">
                    <div class="text-danger fs-1 mb-2"><i class="bi bi-shield-fill"></i></div>
                    <h6 class="fw-bold mb-0">Accessories</h6>
                </a>
            </div>
            <div class="col">
                <a href="{{ route('services.index') }}" class="card border-0 shadow-sm rounded-4 p-3 text-decoration-none text-dark bg-light hover-shadow transition">
                    <div class="text-danger fs-1 mb-2"><i class="bi bi-wrench-adjustable"></i></div>
                    <h6 class="fw-bold mb-0">Servicing</h6>
                </a>
            </div>
        </div>
    </div>
</section>

<!-- FEATURED BICYCLES GRID -->
<section class="py-5">
    <div class="container">
        <div class="d-flex justify-content-between align-items-end mb-4">
            <div>
                <h2 class="text-uppercase brand-font mb-1 text-secondary">Featured <span class="text-danger">Bicycles</span></h2>
                <p class="text-muted mb-0">Premium road, trail, and stunt models selected for you.</p>
            </div>
            <a href="{{ route('marketplace.index', ['type' => 'bike']) }}" class="btn btn-outline-mj btn-sm rounded-pill d-none d-md-inline-block">View All Bikes</a>
        </div>

        <!-- Desktop Grid / Mobile Grid Container -->
        <div class="row row-cols-1 row-cols-md-3 g-4 d-none d-md-flex">
            @foreach($featuredBikes as $bike)
                <div class="col">
                    @include('marketplace.partials.product_card', ['product' => $bike])
                </div>
            @endforeach
        </div>

        <!-- Mobile Grid -->
        <div class="d-md-none" style="display: grid !important; grid-template-columns: repeat(2, 1fr) !important; gap: 10px !important; width: 100% !important; max-width: 100% !important;">
            @foreach($featuredBikes as $bike)
                <div style="width: 100% !important; min-width: 0 !important; max-width: 100% !important;">
                    @include('marketplace.partials.product_card', ['product' => $bike])
                </div>
            @endforeach
        </div>

        <div class="text-center mt-4 d-md-none">
            <a href="{{ route('marketplace.index', ['type' => 'bike']) }}" class="btn btn-outline-mj btn-sm rounded-pill">View All Bicycles</a>
        </div>
    </div>
</section>

<!-- WHY CHOOSE MJ'S BIKES -->
<section class="py-4 py-md-5 bg-dark text-white position-relative overflow-hidden">
    <div class="container">
        <div class="text-center mb-4 mb-md-5">
            <h2 class="text-uppercase brand-font text-white mb-2 fs-3 fs-md-2">Why Choose <span class="text-danger">MJ's Bikes</span></h2>
            <p class="text-secondary" style="max-width: 600px; margin: 0 auto;">We stand for quality craftsmanship, excellent client support, and seamless payments.</p>
        </div>

        <div class="row g-3 g-md-4">
            <div class="col-md-4">
                <div class="card bg-secondary bg-opacity-25 border-0 text-white rounded-4 p-3 p-md-4 h-100">
                    <div class="text-danger fs-2 fs-md-1 mb-2 mb-md-3"><i class="bi bi-award-fill"></i></div>
                    <h5 class="fw-bold mb-2 fs-6 fs-md-5">Quality Showroom Models</h5>
                    <p class="text-secondary mb-0 small">Every bicycle in our catalog represents top-tier brands and has been fully inspected by our staff for quality and build assurance.</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card bg-secondary bg-opacity-25 border-0 text-white rounded-4 p-3 p-md-4 h-100">
                    <div class="text-danger fs-2 fs-md-1 mb-2 mb-md-3"><i class="bi bi-tools"></i></div>
                    <h5 class="fw-bold mb-2 fs-6 fs-md-5">Professional Bike Mechanics</h5>
                    <p class="text-secondary mb-0 small">Our service workshop employs highly certified mechanics specializing in hydraulic systems, gear alignment, and frame assembly.</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card bg-secondary bg-opacity-25 border-0 text-white rounded-4 p-3 p-md-4 h-100">
                    <div class="text-danger fs-2 fs-md-1 mb-2 mb-md-3"><i class="bi bi-phone-vibrate-fill"></i></div>
                    <h5 class="fw-bold mb-2 fs-6 fs-md-5">Instant M-Pesa Checkout</h5>
                    <p class="text-secondary mb-0 small">Order parts or bikes easily using automated STK Push checkout. Cash on delivery options are also available across Nairobi.</p>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- FEATURED SPARE PARTS & ACCESSORIES -->
<section class="py-5 bg-light">
    <div class="container">
        <div class="d-flex justify-content-between align-items-end mb-4">
            <div>
                <h2 class="text-uppercase brand-font mb-1 text-secondary">Spares & <span class="text-danger">Accessories</span></h2>
                <p class="text-muted mb-0">High quality chains, tires, brake pads, lights, and protective gear.</p>
            </div>
            <a href="{{ route('marketplace.index', ['type' => 'spare_part']) }}" class="btn btn-outline-mj btn-sm rounded-pill d-none d-md-inline-block">View All Spares</a>
        </div>

        <!-- Desktop Grid / Mobile Grid Container -->
        <div class="row row-cols-1 row-cols-md-3 g-4 d-none d-md-flex">
            @foreach($featuredParts as $part)
                <div class="col">
                    @include('marketplace.partials.product_card', ['product' => $part])
                </div>
            @endforeach
        </div>

        <!-- Mobile Grid -->
        <div class="mobile-grid-2 d-md-none" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; width: 100%;">
            @foreach($featuredParts as $part)
                <div style="width: 100%;">
                    @include('marketplace.partials.product_card', ['product' => $part])
                </div>
            @endforeach
        </div>

        <div class="text-center mt-4 d-md-none">
            <a href="{{ route('marketplace.index', ['type' => 'spare_part']) }}" class="btn btn-outline-mj btn-sm rounded-pill">View All Spares</a>
        </div>
    </div>
</section>

<!-- REPAIR BOOKING BANNER (CTA) -->
<section class="py-5 bg-danger text-white">
    <div class="container">
        <div class="row align-items-center text-center text-md-start">
            <div class="col-md-8 mb-4 mb-md-0">
                <h2 class="brand-font text-uppercase mb-2 text-white">Is your bike acting up?</h2>
                <p class="lead mb-0 text-light opacity-90">Book a quick repairs or checkup appointment online. We offer home pickup and assembly services.</p>
            </div>
            <div class="col-md-4 text-md-end">
                <a href="{{ route('services.book') }}" class="btn btn-light btn-lg rounded-pill px-4 text-danger fw-bold text-uppercase fs-6">
                    Book Service Now <i class="bi bi-calendar-check ms-1"></i>
                </a>
            </div>
        </div>
    </div>
</section>

<!-- BLOG / ADVICE ARTICLES -->
<section class="py-4 py-md-5">
    <div class="container">
        <div class="text-center mb-4 mb-md-5">
            <h2 class="text-uppercase brand-font text-secondary mb-2 fs-3 fs-md-2">Cycling <span class="text-danger">News & Guides</span></h2>
            <p class="text-muted">Stay updated with professional maintenance guides and cycling safety advice.</p>
        </div>

        <div class="row g-3 g-md-4">
            @foreach($blogPosts as $post)
                <div class="col-md-4">
                    <div class="card h-100 blog-card">
                        <img src="{{ mjs_image($post->image_path, $post->id) }}" class="card-img-top" alt="{{ $post->title }}" style="max-height: 180px; object-fit: cover;">
                        <div class="card-body">
                            <small class="text-danger fw-semibold d-block mb-2">{{ $post->published_at->format('M d, Y') }}</small>
                            <h5 class="card-title fw-bold mb-3"><a href="{{ route('blog.show', $post->slug) }}" class="text-decoration-none text-dark hover-text-danger">{{ $post->title }}</a></h5>
                            <p class="card-text text-muted fs-6">{{ Str::words($post->content, 18) }}</p>
                        </div>
                        <div class="card-footer bg-white border-0 pb-3">
                            <a href="{{ route('blog.show', $post->slug) }}" class="text-danger text-decoration-none fw-bold small">Read Full Article <i class="bi bi-arrow-right ms-1"></i></a>
                        </div>
                    </div>
                </div>
            @endforeach
        </div>
    </div>
</section>

<!-- TESTIMONIALS CAROUSEL -->
<section class="py-5 bg-light border-top">
    <div class="container">
        <div class="text-center mb-5">
            <h2 class="text-uppercase brand-font text-secondary mb-2">Happy <span class="text-danger">Riders</span></h2>
            <p class="text-muted">What our customers are saying about our bikes and repair workshop.</p>
        </div>

        <div class="row justify-content-center">
            <div class="col-lg-8">
                <!-- Bootstrap Carousel -->
                <div id="testimonialCarousel" class="carousel slide" data-bs-ride="carousel">
                    <div class="carousel-inner">
                        @foreach($testimonials as $index => $testi)
                            <div class="carousel-item {{ $index === 0 ? 'active' : '' }}">
                                <div class="card testimonial-card text-center p-4">
                                    <div class="fs-4 text-warning mb-3">
                                        @for($i = 0; $i < $testi->rating; $i++)
                                            <i class="bi bi-star-fill"></i>
                                        @endfor
                                        @for($i = $testi->rating; $i < 5; $i++)
                                            <i class="bi bi-star"></i>
                                        @endfor
                                    </div>
                                    <p class="lead text-muted mb-4">"{{ $testi->review_text }}"</p>
                                    <h6 class="fw-bold mb-0 text-secondary">{{ $testi->customer_name }}</h6>
                                    <small class="text-muted">Verified Customer</small>
                                </div>
                            </div>
                        @endforeach
                    </div>
                    <button class="carousel-control-prev" type="button" data-bs-target="#testimonialCarousel" data-bs-slide="prev">
                        <span class="carousel-control-prev-icon bg-danger rounded-circle p-2" aria-hidden="true" style="background-size: 50% 50%;"></span>
                        <span class="visually-hidden">Previous</span>
                    </button>
                    <button class="carousel-control-next" type="button" data-bs-target="#testimonialCarousel" data-bs-slide="next">
                        <span class="carousel-control-next-icon bg-danger rounded-circle p-2" aria-hidden="true" style="background-size: 50% 50%;"></span>
                        <span class="visually-hidden">Next</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</section>

@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const heroCarousel = document.getElementById('heroCarousel');
    if (!heroCarousel) return;

    const trackUrl = @json(route('hero-slides.track', ['id' => '__ID__']));
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
    const counterEl = document.getElementById('heroSlideCurrent');
    const trackedImpressions = new Set();

    function trackSlide(slideId, type) {
        if (!slideId || !csrfToken) return;
        fetch(trackUrl.replace('__ID__', slideId), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
                'Accept': 'application/json',
            },
            body: JSON.stringify({ type: type }),
        }).catch(function () {});
    }

    function getActiveSlide() {
        return heroCarousel.querySelector('.carousel-item.active');
    }

    function trackActiveImpression() {
        const active = getActiveSlide();
        if (!active) return;
        const slideId = active.dataset.slideId;
        if (!slideId || trackedImpressions.has(slideId)) return;
        trackedImpressions.add(slideId);
        trackSlide(slideId, 'impression');
    }

    function updateCounter() {
        const items = heroCarousel.querySelectorAll('.carousel-item');
        const active = getActiveSlide();
        if (!counterEl || !active) return;
        counterEl.textContent = Array.from(items).indexOf(active) + 1;
    }

    function replayAnimations() {
        const active = getActiveSlide();
        if (!active) return;
        active.querySelectorAll('.hero-slide-badge, .hero-slide-title, .hero-slide-subtitle, .hero-slide-actions').forEach(function (el) {
            el.style.animation = 'none';
            el.offsetHeight;
            el.style.animation = '';
        });
    }

    heroCarousel.addEventListener('slid.bs.carousel', function () {
        updateCounter();
        replayAnimations();
        trackActiveImpression();
    });

    heroCarousel.querySelectorAll('[data-track-slide]').forEach(function (el) {
        el.addEventListener('click', function () {
            trackSlide(el.dataset.trackSlide, 'click');
        });
    });

    updateCounter();
    trackActiveImpression();
});
</script>
@endsection
