<?php
/**
 * Home Page — Premium with Dynamic Banner, Stats, Category Preview
 * Fade Up + Count-Up effects included on this page
 * Path: index.php
 */
include_once 'header.php';

$site_name    = get_site_setting('site_name');
$site_phone   = get_site_setting('site_phone');
$site_about   = get_site_setting('site_about');
$stat_years   = get_site_setting('stat_years') ?: '20+ Years';
$stat_units   = get_site_setting('stat_units') ?: '2,700+';
$stat_response= get_site_setting('stat_response') ?: '24/7/365';

$home_banners = get_device_banners('desktop');
$home_banners_mobile = get_device_banners('mobile');
if (empty($home_banners_mobile)) $home_banners_mobile = $home_banners;

$default_banner_img = 'https://images.unsplash.com/photo-1581092160607-ee22621dd758?w=1600';
$default_banner = [
    'image_url'    => $default_banner_img,
    'title'        => $site_name,
    'subtitle'     => 'Certified Elevator, Generator, Transformer & Solar Solutions in Bangladesh',
    'button_text'  => 'Explore Products',
    'button_link'  => 'products.php',
];
if (empty($home_banners)) $home_banners = [$default_banner];
if (empty($home_banners_mobile)) $home_banners_mobile = $home_banners;

$categories = get_categories();
$home_products = [];
foreach ($categories as $cat) {
    $items = get_products_filtered($cat['id'], null, 2);
    foreach ($items as $p) $home_products[] = $p;
}
$home_products = array_slice($home_products, 0, 6);
$testimonials = array_slice(get_testimonials(), 0, 3);
$blogs = array_slice(get_blogs(4), 0, 4);
$home_projects = get_projects(4);

function banner_img($url) {
    if (empty($url)) return 'https://images.unsplash.com/photo-1581092160607-ee22621dd758?w=1600';
    return $url;
}

/* Parse stats for count-up: number + suffix */
function parse_stat_for_count($text) {
    $text = trim($text);
    if (preg_match('/^([\d,.]+)\+(.*)$/u', $text, $m)) {
        return ['num' => (float) str_replace(',', '', $m[1]), 'suffix' => '+' . trim($m[2]), 'comma' => strpos($m[1], ',') !== false];
    }
    if (preg_match('/^([\d,.]+)\s+(.*)$/u', $text, $m)) {
        return ['num' => (float) str_replace(',', '', $m[1]), 'suffix' => ' ' . $m[2], 'comma' => strpos($m[1], ',') !== false];
    }
    if (preg_match('/^([\d,.]+)$/u', $text, $m)) {
        return ['num' => (float) str_replace(',', '', $m[1]), 'suffix' => '', 'comma' => strpos($m[1], ',') !== false];
    }
    return null; // e.g. 24/7/365 — no count
}
$years_parsed = parse_stat_for_count($stat_years);
$units_parsed = parse_stat_for_count($stat_units);
?>

<style>
    .fade-up {
        opacity: 0;
        transform: translateY(40px);
        transition: opacity 0.8s ease, transform 0.8s ease;
    }
    .fade-up.show {
        opacity: 1;
        transform: translateY(0);
    }
    .stagger-item {
        opacity: 0;
        transform: translateY(30px);
        transition: opacity 0.55s ease, transform 0.55s ease;
    }
    .stagger-item.show {
        opacity: 1;
        transform: translateY(0);
    }
</style>

<!-- ===== HERO / BANNER SLIDER ===== -->
<section class="relative overflow-hidden bg-slate-950 w-full" id="home-banner-slider">
    <style>
        .banner-track { position: relative; width: 100%; }
        .banner-slide {
            position: absolute;
            inset: 0;
            opacity: 0;
            visibility: hidden;
            transform: scale(1.04);
            transition: opacity 1s ease, transform 1.1s ease, visibility 1s;
            z-index: 1;
            pointer-events: none;
        }
        .banner-slide.is-active {
            position: relative;
            inset: auto;
            opacity: 1;
            visibility: visible;
            transform: scale(1);
            z-index: 2;
            pointer-events: auto;
        }
        /* Keep outgoing slide visible during fade (absolute over relative active) */
        .banner-slide.is-leaving {
            position: absolute;
            inset: 0;
            opacity: 0;
            visibility: visible;
            transform: scale(1);
            z-index: 3;
            pointer-events: none;
            transition: opacity 1s ease, transform 1.1s ease;
        }
        .banner-dot { width: 8px; height: 8px; border-radius: 9999px; background: rgba(255,255,255,0.4); transition: all 0.25s; }
        .banner-dot.is-active { width: 22px; background: #0284c7; }
    </style>

    <!-- Desktop slides -->
    <div class="hidden md:block relative w-full bg-slate-950">
        <div class="banner-track">
        <?php foreach ($home_banners as $i => $db):
            $desk_img = banner_img($db['image_url'] ?? '');
            $has_text = !empty($db['title']) || !empty($db['subtitle']) || !empty($db['button_text']);
        ?>
        <div class="banner-slide banner-slide-desk <?php echo $i === 0 ? 'is-active' : ''; ?>" data-slide="<?php echo $i; ?>">
            <div class="relative w-full flex items-center justify-center">
                <img src="<?php echo htmlspecialchars($desk_img); ?>" class="block w-full h-auto" alt="Banner <?php echo $i + 1; ?>">
                <?php if ($has_text): ?>
                <div class="absolute inset-0 bg-gradient-to-r from-black/50 via-black/15 to-transparent flex items-center pointer-events-none">
                    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full relative z-10 pointer-events-auto">
                        <div class="max-w-xl space-y-4 text-white">
                            <span class="inline-flex items-center gap-1.5 py-1.5 px-3 rounded-full text-xs font-semibold bg-secondary/90 uppercase tracking-wider">
                                <span class="w-1.5 h-1.5 bg-green-400 rounded-full animate-ping"></span> Engineering Excellence
                            </span>
                            <?php if (!empty($db['title'])): ?>
                            <h1 class="text-3xl lg:text-5xl font-black uppercase tracking-tight leading-tight drop-shadow-lg"><?php echo htmlspecialchars($db['title']); ?></h1>
                            <?php endif; ?>
                            <?php if (!empty($db['subtitle'])): ?>
                            <p class="text-base lg:text-lg text-gray-200 font-medium leading-relaxed drop-shadow"><?php echo htmlspecialchars($db['subtitle']); ?></p>
                            <?php endif; ?>
                            <div class="flex flex-wrap gap-3 pt-1">
                                <?php if (!empty($db['button_text'])): ?>
                                <a href="<?php echo htmlspecialchars($db['button_link'] ?: 'products.php'); ?>" class="bg-primary hover:bg-secondary text-white px-7 py-3.5 rounded-xl font-bold shadow-lg transition-all">
                                    <?php echo htmlspecialchars($db['button_text']); ?>
                                </a>
                                <?php endif; ?>
                                <a href="tel:<?php echo htmlspecialchars($site_phone); ?>" class="bg-white/10 hover:bg-white/20 backdrop-blur border border-white/25 text-white px-7 py-3.5 rounded-xl font-bold transition-all flex items-center">
                                    <i class="fa-solid fa-phone mr-2"></i> Call Now
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
        </div>

        <?php if (count($home_banners) > 1): ?>
        <div class="absolute bottom-5 left-1/2 -translate-x-1/2 z-20 flex items-center gap-2">
            <?php foreach ($home_banners as $i => $_): ?>
            <button type="button" class="banner-dot banner-dot-desk <?php echo $i === 0 ? 'is-active' : ''; ?>" data-go="<?php echo $i; ?>" aria-label="Slide <?php echo $i + 1; ?>"></button>
            <?php endforeach; ?>
        </div>
        <button type="button" class="banner-prev absolute left-3 top-1/2 -translate-y-1/2 z-20 w-10 h-10 rounded-full bg-black/35 hover:bg-black/55 text-white hidden lg:flex items-center justify-center" data-dir="-1" aria-label="Previous">
            <i class="fa-solid fa-chevron-left"></i>
        </button>
        <button type="button" class="banner-next absolute right-3 top-1/2 -translate-y-1/2 z-20 w-10 h-10 rounded-full bg-black/35 hover:bg-black/55 text-white hidden lg:flex items-center justify-center" data-dir="1" aria-label="Next">
            <i class="fa-solid fa-chevron-right"></i>
        </button>
        <?php endif; ?>
    </div>

    <!-- Mobile slides -->
    <div class="md:hidden relative w-full bg-slate-950">
        <div class="banner-track">
        <?php foreach ($home_banners_mobile as $i => $mb):
            $mob_img = banner_img($mb['image_url'] ?? '');
            $has_mob_text = !empty($mb['title']) || !empty($mb['subtitle']) || !empty($mb['button_text']);
        ?>
        <div class="banner-slide banner-slide-mob <?php echo $i === 0 ? 'is-active' : ''; ?>" data-slide="<?php echo $i; ?>">
            <div class="relative w-full flex items-center justify-center">
                <img src="<?php echo htmlspecialchars($mob_img); ?>" class="block w-full h-auto" alt="Banner <?php echo $i + 1; ?>">
                <?php if ($has_mob_text): ?>
                <div class="absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-transparent flex items-end">
                    <div class="p-5 space-y-2 text-white w-full">
                        <?php if (!empty($mb['title'])): ?>
                        <h1 class="text-xl font-black uppercase leading-tight drop-shadow-lg"><?php echo htmlspecialchars($mb['title']); ?></h1>
                        <?php endif; ?>
                        <?php if (!empty($mb['subtitle'])): ?>
                        <p class="text-sm text-gray-200 line-clamp-2"><?php echo htmlspecialchars($mb['subtitle']); ?></p>
                        <?php endif; ?>
                        <div class="flex gap-3 pt-1">
                            <?php if (!empty($mb['button_text'])): ?>
                            <a href="<?php echo htmlspecialchars($mb['button_link'] ?: 'products.php'); ?>" class="bg-primary text-white px-5 py-2.5 rounded-lg font-bold text-sm"><?php echo htmlspecialchars($mb['button_text']); ?></a>
                            <?php endif; ?>
                            <a href="tel:<?php echo htmlspecialchars($site_phone); ?>" class="bg-white/15 border border-white/20 text-white px-5 py-2.5 rounded-lg font-bold text-sm"><i class="fa-solid fa-phone"></i></a>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
        </div>

        <?php if (count($home_banners_mobile) > 1): ?>
        <div class="absolute bottom-4 left-1/2 -translate-x-1/2 z-20 flex items-center gap-2">
            <?php foreach ($home_banners_mobile as $i => $_): ?>
            <button type="button" class="banner-dot banner-dot-mob <?php echo $i === 0 ? 'is-active' : ''; ?>" data-go="<?php echo $i; ?>" aria-label="Slide <?php echo $i + 1; ?>"></button>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</section>

<script>
(function () {
    function makeSlider(slideSel, dotSel, opts) {
        opts = opts || {};
        var slides = Array.prototype.slice.call(document.querySelectorAll(slideSel));
        var dots = Array.prototype.slice.call(document.querySelectorAll(dotSel));
        if (slides.length < 2) return null;
        var i = 0, timer = null, locking = false;

        function go(n) {
            if (locking) return;
            var nextIdx = (n + slides.length) % slides.length;
            if (nextIdx === i) return;
            locking = true;

            var current = slides[i];
            var incoming = slides[nextIdx];

            current.classList.remove('is-active');
            current.classList.add('is-leaving');
            incoming.classList.add('is-active');

            dots.forEach(function (d, idx) { d.classList.toggle('is-active', idx === nextIdx); });
            i = nextIdx;

            setTimeout(function () {
                current.classList.remove('is-leaving');
                locking = false;
            }, 1000);
        }
        function next(dir) { go(i + (dir || 1)); }
        function start() {
            stop();
            timer = setInterval(function () { next(1); }, 3000);
        }
        function stop() { if (timer) clearInterval(timer); }

        dots.forEach(function (d) {
            d.addEventListener('click', function () {
                go(parseInt(d.getAttribute('data-go'), 10) || 0);
                start();
            });
        });
        if (opts.prevSel) {
            document.querySelectorAll(opts.prevSel).forEach(function (btn) {
                btn.addEventListener('click', function () { next(-1); start(); });
            });
        }
        if (opts.nextSel) {
            document.querySelectorAll(opts.nextSel).forEach(function (btn) {
                btn.addEventListener('click', function () { next(1); start(); });
            });
        }
        start();
        return { start: start, stop: stop };
    }

    var desk = makeSlider('.banner-slide-desk', '.banner-dot-desk', {
        prevSel: '#home-banner-slider .banner-prev',
        nextSel: '#home-banner-slider .banner-next'
    });
    makeSlider('.banner-slide-mob', '.banner-dot-mob');

    var section = document.getElementById('home-banner-slider');
    if (section && desk) {
        section.addEventListener('mouseenter', desk.stop);
        section.addEventListener('mouseleave', desk.start);
    }
})();
</script>

<!-- ===== STATS BAR (Count-Up) ===== -->
<div class="bg-primary text-white py-6 shadow-lg relative z-10 fade-up" id="home-stats">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="grid grid-cols-3 gap-4 text-center divide-x divide-white/15">
            <div>
                <?php if ($years_parsed): ?>
                <span class="block text-xl md:text-4xl font-black text-secondary count-up"
                      data-target="<?php echo $years_parsed['num']; ?>"
                      data-suffix="<?php echo htmlspecialchars($years_parsed['suffix']); ?>"
                      data-comma="<?php echo $years_parsed['comma'] ? '1' : '0'; ?>">0</span>
                <?php else: ?>
                <span class="block text-xl md:text-4xl font-black text-secondary"><?php echo htmlspecialchars($stat_years); ?></span>
                <?php endif; ?>
                <span class="text-[10px] md:text-xs text-gray-300 uppercase">Experience</span>
            </div>
            <div>
                <?php if ($units_parsed): ?>
                <span class="block text-xl md:text-4xl font-black text-secondary count-up"
                      data-target="<?php echo $units_parsed['num']; ?>"
                      data-suffix="<?php echo htmlspecialchars($units_parsed['suffix']); ?>"
                      data-comma="<?php echo $units_parsed['comma'] ? '1' : '0'; ?>">0</span>
                <?php else: ?>
                <span class="block text-xl md:text-4xl font-black text-secondary"><?php echo htmlspecialchars($stat_units); ?></span>
                <?php endif; ?>
                <span class="text-[10px] md:text-xs text-gray-300 uppercase">Projects</span>
            </div>
            <div>
                <span class="block text-xl md:text-4xl font-black text-secondary"><?php echo htmlspecialchars($stat_response); ?></span>
                <span class="text-[10px] md:text-xs text-gray-300 uppercase">Support</span>
            </div>
        </div>
    </div>
</div>

<!-- ===== CATEGORIES ===== -->
<section class="py-16 bg-white fade-up">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="text-center mb-12 space-y-3">
            <h2 class="text-2xl md:text-4xl font-black text-primary uppercase">Our Product Categories</h2>
            <div class="w-16 h-1 bg-secondary mx-auto"></div>
        </div>
        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
            <?php foreach ($categories as $i => $cat): ?>
            <a href="products.php?cat=<?php echo $cat['id']; ?>"
               class="stagger-item group bg-gray-50 hover:bg-primary border border-gray-100 hover:border-primary rounded-2xl p-5 text-center transition-all duration-300 hover:shadow-xl hover:-translate-y-1"
               style="transition-delay: <?php echo ($i * 0.08); ?>s">
                <div class="w-14 h-14 mx-auto mb-3 rounded-2xl bg-blue-50 group-hover:bg-white/20 text-primary group-hover:text-white flex items-center justify-center text-2xl transition-all">
                    <i class="fa-solid <?php echo htmlspecialchars($cat['icon'] ?? 'fa-box'); ?>"></i>
                </div>
                <h3 class="font-bold text-sm text-gray-800 group-hover:text-white uppercase leading-tight transition-colors"><?php echo htmlspecialchars($cat['name']); ?></h3>
            </a>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<!-- ===== FEATURED PRODUCTS ===== -->
<section class="py-16 bg-gray-50 fade-up">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex flex-col md:flex-row justify-between items-start md:items-end gap-4 mb-10">
            <div>
                <h2 class="text-2xl md:text-4xl font-black text-primary uppercase">Featured Products</h2>
                <p class="text-gray-500 text-sm mt-2">Premium engineered solutions from trusted brands</p>
            </div>
            <a href="products.php" class="text-secondary hover:text-primary font-bold text-sm uppercase tracking-wider flex items-center">
                View All <i class="fa-solid fa-arrow-right ml-2"></i>
            </a>
        </div>
        <?php if (!empty($home_products)): ?>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php foreach ($home_products as $i => $p):
                $img = $p['image_url'] ?: 'https://images.unsplash.com/photo-1581092160607-ee22621dd758?w=600';
            ?>
            <div class="stagger-item bg-white rounded-2xl overflow-hidden border border-gray-100 hover:shadow-xl hover:-translate-y-1 transition-all group"
                 style="transition-delay: <?php echo ($i * 0.1); ?>s">
                <div class="h-52 overflow-hidden bg-gray-200">
                    <img src="<?php echo htmlspecialchars($img); ?>" class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" alt="">
                </div>
                <div class="p-5 space-y-3">
                    <?php if (!empty($p['category_name'])): ?>
                    <span class="text-[10px] font-bold uppercase bg-blue-50 text-primary px-2 py-0.5 rounded-full"><?php echo htmlspecialchars($p['category_name']); ?></span>
                    <?php endif; ?>
                    <h3 class="font-black text-primary uppercase text-sm group-hover:text-secondary transition-colors"><?php echo htmlspecialchars($p['title']); ?></h3>
                    <a href="products-details.php?slug=<?php echo urlencode($p['slug']); ?>" class="text-secondary font-bold text-xs uppercase inline-flex items-center">
                        View Details <i class="fa-solid fa-arrow-right ml-2"></i>
                    </a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</section>

<!-- ===== ABOUT PREVIEW ===== -->
<section class="py-16 bg-white fade-up">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
            <div class="space-y-5">
                <span class="text-secondary font-bold uppercase text-xs tracking-wider">About Us</span>
                <h2 class="text-3xl font-black text-primary uppercase">Reliable. Certified. Local.</h2>
                <p class="text-gray-600 leading-relaxed"><?php echo htmlspecialchars(mb_substr($site_about, 0, 280)); ?>...</p>
                <a href="about.php" class="inline-flex items-center bg-primary hover:bg-secondary text-white px-6 py-3 rounded-xl font-bold text-sm transition-all">
                    Learn More <i class="fa-solid fa-arrow-right ml-2"></i>
                </a>
            </div>
            <div class="grid grid-cols-2 gap-4">
                <?php
                $features = [
                    ['fa-shield-halved','ISO Certified','International safety standards'],
                    ['fa-user-tie','Expert Team','Certified engineers'],
                    ['fa-headset','24/7 Support','Emergency response'],
                    ['fa-wallet','Fair Pricing','Transparent quotes'],
                ];
                foreach ($features as $f): ?>
                <div class="bg-gray-50 p-5 rounded-2xl border border-gray-100">
                    <i class="fa-solid <?php echo $f[0]; ?> text-primary text-xl mb-3"></i>
                    <h4 class="font-bold text-gray-900 text-sm mb-1"><?php echo $f[1]; ?></h4>
                    <p class="text-xs text-gray-500"><?php echo $f[2]; ?></p>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</section>

<!-- ===== PROJECTS (latest 4) ===== -->
<?php if (!empty($home_projects)): ?>
<section class="py-16 bg-gray-50 fade-up">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="text-center mb-10 space-y-3">
            <h2 class="text-2xl md:text-4xl font-black text-primary uppercase">Our Projects</h2>
            <p class="text-gray-500 text-sm">Recent work delivered for leading companies</p>
            <div class="w-16 h-1 bg-secondary mx-auto"></div>
        </div>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-5">
            <?php foreach ($home_projects as $i => $proj):
                $cover = project_cover($proj);
            ?>
            <a href="projects-details.php?id=<?php echo intval($proj['id']); ?>"
               class="stagger-item group bg-white rounded-2xl overflow-hidden border border-gray-100 hover:shadow-xl hover:-translate-y-1 transition-all"
               style="transition-delay: <?php echo ($i * 0.08); ?>s">
                <div class="aspect-[4/3] overflow-hidden bg-gray-200">
                    <img src="<?php echo htmlspecialchars($cover); ?>"
                         class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" alt="">
                </div>
                <div class="p-3 md:p-4 space-y-1">
                    <?php if (!empty($proj['category_name'])): ?>
                    <span class="text-[10px] font-bold uppercase text-secondary"><?php echo htmlspecialchars($proj['category_name']); ?></span>
                    <?php endif; ?>
                    <h3 class="font-black text-primary text-xs md:text-sm uppercase leading-snug group-hover:text-secondary transition-colors line-clamp-2">
                        <?php echo htmlspecialchars($proj['company_name']); ?>
                    </h3>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
        <div class="text-center mt-8">
            <a href="projects.php" class="inline-flex items-center text-secondary hover:text-primary font-bold text-sm uppercase tracking-wider">
                View All <i class="fa-solid fa-arrow-right ml-2"></i>
            </a>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- ===== NEWS & UPDATES (latest) ===== -->
<?php if (!empty($blogs)): ?>
<section class="py-16 bg-white fade-up">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="text-center mb-10 space-y-3">
            <h2 class="text-2xl md:text-4xl font-black text-primary uppercase">News & Updates</h2>
            <p class="text-gray-500 text-sm">Latest articles and advisory posts</p>
            <div class="w-16 h-1 bg-secondary mx-auto"></div>
        </div>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-5">
            <?php foreach ($blogs as $i => $post):
                $thumb = !empty($post['thumbnail_url']) ? $post['thumbnail_url'] : 'https://images.unsplash.com/photo-1581092160607-ee22621dd758?w=600';
                $detail = !empty($post['id']) ? 'news-details.php?id=' . intval($post['id']) : 'news.php';
            ?>
            <a href="<?php echo $detail; ?>"
               class="stagger-item group bg-gray-50 rounded-2xl overflow-hidden border border-gray-100 hover:shadow-xl hover:-translate-y-1 transition-all"
               style="transition-delay: <?php echo ($i * 0.08); ?>s">
                <div class="aspect-[4/3] overflow-hidden bg-gray-200">
                    <img src="<?php echo htmlspecialchars($thumb); ?>"
                         class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" alt="">
                </div>
                <div class="p-3 md:p-4">
                    <h3 class="font-black text-primary text-xs md:text-sm uppercase leading-snug group-hover:text-secondary transition-colors line-clamp-2">
                        <?php echo htmlspecialchars($post['title']); ?>
                    </h3>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
        <div class="text-center mt-8">
            <a href="news.php" class="inline-flex items-center text-secondary hover:text-primary font-bold text-sm uppercase tracking-wider">
                View All <i class="fa-solid fa-arrow-right ml-2"></i>
            </a>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- ===== REVIEWS PREVIEW (Slider) ===== -->
<?php if (!empty($testimonials)): ?>
<section class="py-16 bg-gray-50 overflow-hidden fade-up">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mb-8 flex justify-between items-end">
        <div>
            <h2 class="text-2xl md:text-3xl font-black text-primary uppercase">Client Reviews</h2>
            <div class="w-12 h-1 bg-secondary mt-2"></div>
        </div>
        <a href="reviews.php" class="text-secondary font-bold text-sm hover:underline">All Reviews →</a>
    </div>
    <div class="review-slider-home overflow-hidden">
        <div class="review-track-home flex gap-6 animate-slide-left">
            <?php foreach (array_merge($testimonials, $testimonials) as $t): ?>
            <div class="flex-shrink-0 w-80 bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
                <div class="flex text-amber-400 text-xs mb-3">
                    <?php for ($i=0;$i<intval($t['rating']);$i++): ?><i class="fa-solid fa-star"></i><?php endfor; ?>
                </div>
                <p class="text-sm text-gray-600 italic leading-relaxed line-clamp-3">"<?php echo htmlspecialchars($t['review_text']); ?>"</p>
                <p class="font-bold text-gray-900 text-sm mt-4"><?php echo htmlspecialchars($t['client_name']); ?></p>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<style>
    @keyframes slideLeft { 0%{transform:translateX(0)} 100%{transform:translateX(-50%)} }
    .animate-slide-left { animation: slideLeft 25s linear infinite; width: max-content; }
    .review-slider-home:hover .animate-slide-left { animation-play-state: paused; }
</style>
<?php endif; ?>

<!-- ===== CTA ===== -->
<section class="py-16 bg-gradient-to-br from-primary to-blue-900 text-white text-center fade-up">
    <div class="max-w-3xl mx-auto px-4 space-y-6">
        <h2 class="text-3xl font-black uppercase">Need Engineering Support?</h2>
        <p class="text-gray-300">Elevator, Generator, Transformer or Solar — our team is ready 24/7.</p>
        <div class="flex flex-col sm:flex-row gap-4 justify-center">
            <a href="contact.php" class="bg-white text-primary hover:bg-secondary hover:text-white px-8 py-4 rounded-xl font-bold transition-all">Request a Quote</a>
            <a href="tel:<?php echo htmlspecialchars($site_phone); ?>" class="border border-white/30 hover:bg-white/10 px-8 py-4 rounded-xl font-bold transition-all">
                <i class="fa-solid fa-phone mr-2"></i><?php echo htmlspecialchars($site_phone); ?>
            </a>
        </div>
    </div>
</section>

<script>
(function () {
    /* Fade Up + Stagger */
    var observer = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
            if (!entry.isIntersecting) return;
            entry.target.classList.add('show');
            observer.unobserve(entry.target);
        });
    }, { threshold: 0.15, rootMargin: '0px 0px -30px 0px' });

    document.querySelectorAll('.fade-up, .stagger-item').forEach(function (el) {
        observer.observe(el);
    });

    /* Count-Up */
    function runCount(el) {
        if (el.dataset.done) return;
        el.dataset.done = '1';
        var target = parseFloat(el.getAttribute('data-target')) || 0;
        var suffix = el.getAttribute('data-suffix') || '';
        var useComma = el.getAttribute('data-comma') === '1';
        var duration = 1600;
        var start = null;

        function fmt(n) {
            var s = Math.round(n).toString();
            if (useComma) s = s.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            return s + suffix;
        }

        function step(ts) {
            if (!start) start = ts;
            var p = Math.min(1, (ts - start) / duration);
            var eased = 1 - Math.pow(1 - p, 3);
            el.textContent = fmt(target * eased);
            if (p < 1) requestAnimationFrame(step);
            else el.textContent = fmt(target);
        }
        requestAnimationFrame(step);
    }

    var countObs = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
            if (!entry.isIntersecting) return;
            entry.target.querySelectorAll('.count-up').forEach(runCount);
            countObs.unobserve(entry.target);
        });
    }, { threshold: 0.4 });

    var stats = document.getElementById('home-stats');
    if (stats) countObs.observe(stats);
})();
</script>

<?php include_once 'footer.php'; ?>
