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

/* --------------------------------------------------------------------------
   Already signed in?  Go straight to the panel instead of showing the public
   landing page.  ?home=1 is the escape hatch so a logged-in user can still
   open the marketing page from the menu.
   -------------------------------------------------------------------------- */
if (isLoggedIn() && !isset($_GET['home'])) {
    $__to = 'dashboard.php';
    if (isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'admin')  { $__to = 'admin/index.php'; }
    if (isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'seller') { $__to = 'seller/index.php'; }
    header('Location: ' . $__to);
    exit;
}

require_once __DIR__ . '/header.php';

$hero_slides   = getHeroSlides('landing');   // home page banner only — never the after-login one
$statistics    = getStatistics();
$why_choose_us = getWhyChooseUs();
$team_members  = getTeamMembers();
$videos        = getVideos();

global $db;
$categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");

$dashboard_link = $is_authed ? userDashboardLink() : 'login.php';

/** translate helper */
$T = function ($key, $fallback = '') use ($lang) {
    $v = $lang->translate($key, $fallback);
    return ($v === $key && $fallback !== '') ? $fallback : $v;
};
/** translate + escape */
$E = function ($key, $fallback = '') use ($T) { return esc($T($key, $fallback)); };

/* --------------------------------------------------------------------------
   HERO TEXT — comes from the hero_slides row and from nowhere else, so what
   the admin types in Admin -> Website Settings -> Hero Slider is exactly what
   a visitor reads here. A blank Bengali / Hindi box falls back to English.
   -------------------------------------------------------------------------- */
$hero_sfx = ($current_lang === 'bn') ? '_bn' : (($current_lang === 'hi') ? '_hi' : '');
$H = function ($slide, $base) use ($hero_sfx) {
    $alt = [
        'title'        => 'title',
        'subtitle'     => 'subtitle',
        'badge_text'   => 'badge',
        'button_text'  => 'button',
        'button2_text' => 'button2',
    ];
    if ($hero_sfx !== '' && isset($alt[$base])) {
        $col = $alt[$base] . $hero_sfx;
        if (!empty($slide[$col])) { return (string)$slide[$col]; }
    }
    return (string)($slide[$base] ?? '');
};
?>

<!-- =========================================================================
     HERO  —  100% admin managed (Admin → Website Settings → Hero Slider)
     ========================================================================= -->
<section class="hero">
    <div class="swiper heroSwiper">
        <div class="swiper-wrapper">
            <?php if (empty($hero_slides)): ?>
            <div class="swiper-slide">
                <div class="hero-veil-1"></div>
                <div class="grid-overlay"></div>
                <div class="hero-body"><div class="wrap"><div class="hero-inner">
                    <h1 class="hero-title"><?php echo esc($company_name); ?></h1>
                    <p class="hero-sub"><?php echo $E('digital_service_platform', 'Digital Service Platform'); ?></p>
                </div></div></div>
            </div>
            <?php endif; ?>

            <?php foreach ($hero_slides as $index => $slide):
                $h_badge = $H($slide, 'badge_text');
                $h_title = $H($slide, 'title');
                $h_sub   = $H($slide, 'subtitle');
                $h_b1    = $H($slide, 'button_text');
                $h_b2    = $H($slide, 'button2_text');
                $h_l1    = (string)($slide['button_link']  ?? '');
                $h_l2    = (string)($slide['button2_link'] ?? '');
                $h_ov    = isset($slide['overlay']) ? max(0, min(100, (int)$slide['overlay'])) : 70;
                $h_align = (($slide['text_align'] ?? 'left') === 'center') ? ' is-center' : '';
                $h_trust = !isset($slide['show_trust']) || (int)$slide['show_trust'] === 1;
                $h_img   = (string)($slide['image_path'] ?? '');
            ?>
            <div class="swiper-slide">
                <?php if ($h_img !== ''): ?>
                    <img src="<?php echo esc($h_img); ?>" alt="" class="hero-media">
                <?php endif; ?>
                <div class="hero-veil-1" style="opacity:<?php echo number_format($h_ov / 100, 2); ?>"></div>
                <div class="hero-veil-2"></div>
                <div class="grid-overlay"></div>

                <div class="hero-body">
                    <div class="wrap">
                        <div class="hero-inner<?php echo $h_align; ?>">
                            <?php if ($h_badge !== ''): ?>
                            <span class="badge-gold animate-fadeInUp">
                                <span class="badge-dot"></span><?php echo esc($h_badge); ?>
                            </span>
                            <?php endif; ?>

                            <?php if ($h_title !== ''): ?>
                            <h1 class="hero-title animate-fadeInUp delay-100"><?php echo esc($h_title); ?></h1>
                            <?php endif; ?>

                            <div class="gold-line animate-fadeInUp delay-100" style="margin-bottom:22px"></div>

                            <?php if ($h_sub !== ''): ?>
                            <p class="hero-sub animate-fadeInUp delay-200"><?php echo esc($h_sub); ?></p>
                            <?php endif; ?>

                            <?php if ($h_b1 !== '' || $h_b2 !== '' || $is_authed): ?>
                            <div class="hero-actions animate-fadeInUp delay-300">
                                <?php if ($is_authed): ?>
                                    <a href="<?php echo esc($dashboard_link); ?>" class="btn btn-gold btn-lg">
                                        <?php echo $E('go_to_dashboard', 'Go to Dashboard'); ?><i class="fas fa-arrow-right"></i>
                                    </a>
                                <?php else: ?>
                                    <?php if ($h_b1 !== ''): ?>
                                    <a href="<?php echo esc($h_l1 !== '' ? $h_l1 : 'register.php'); ?>" class="btn btn-gold btn-lg">
                                        <?php echo esc($h_b1); ?><i class="fas fa-arrow-right"></i>
                                    </a>
                                    <?php endif; ?>
                                    <?php if ($h_b2 !== ''): ?>
                                    <a href="<?php echo esc($h_l2 !== '' ? $h_l2 : '#services'); ?>" class="btn btn-ghost btn-lg">
                                        <?php echo esc($h_b2); ?>
                                    </a>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>

                            <?php if ($h_trust): ?>
                            <div class="hero-trust animate-fadeInUp delay-300">
                                <span><i class="fas fa-shield-halved"></i><?php echo $E('trust_secure', '100% Secure'); ?></span>
                                <span class="sep"></span>
                                <span><i class="fas fa-bolt"></i><?php echo $E('trust_instant', 'Instant Settlement'); ?></span>
                                <span class="sep"></span>
                                <span><i class="fas fa-headset"></i><?php echo $E('trust_support', '24x7 Support'); ?></span>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="swiper-button-next"></div>
        <div class="swiper-button-prev"></div>
        <div class="swiper-pagination hero-pagination"></div>
    </div>

    <a href="#services" class="hero-scroll">
        <span><?php echo $E('scroll', 'Scroll'); ?></span>
        <i class="fas fa-chevron-down floaty"></i>
    </a>
</section>

<!-- =========================================================================
     MARQUEE
     ========================================================================= -->
<section class="marquee">
    <div class="marquee__track">
        <?php
        /* The strip below is the same list as "Our Special Services" — it is
           built straight from the live service categories, so adding a
           category in the admin panel adds it here too. */
        $marq_cats = $categories;
        if (empty($marq_cats)) { $marq_cats = []; }
        for ($r = 0; $r < 2; $r++) {
            foreach ($marq_cats as $mc) {
                $mc_title = $lang->translate($mc['category_key'], $mc['title']);
                if ($mc_title === $mc['category_key']) { $mc_title = $mc['title']; }
                echo '<a class="marquee__item" href="category.php?id=' . (int)$mc['id'] . '">'
                   . '<i class="fas ' . esc($mc['icon_class'] ?: 'fa-star') . '"></i>'
                   . esc($mc_title) . '</a>';
            }
        }
        ?>
    </div>
</section>

<!-- =========================================================================
     SERVICES
     ========================================================================= -->
<section id="services" class="section section-white">
    <div class="aurora aurora-gold a1 drift" style="opacity:.14"></div>
    <div class="wrap">
        <div class="sec-head reveal">
            <span class="badge-gold dark"><?php echo $E('services', 'Services'); ?></span>
            <h2 class="sec-title"><?php echo $E('our_services', 'Our Special Services'); ?></h2>
            <div class="gold-line center" style="margin-bottom:20px"></div>
            <p class="sec-sub"><?php echo $E('join_us', 'Join us for easy and fast digital services'); ?></p>
        </div>

        <div class="grid grid-4">
            <?php foreach ($categories as $i => $cat): ?>
            <div class="card svc reveal" style="transition-delay:<?php echo min($i, 7) * 70; ?>ms">
                <div class="svc-body">
                    <div class="medallion lg svc-icon"><i class="fas <?php echo esc($cat['icon_class']); ?>"></i></div>
                    <h3 class="svc-title"><?php echo esc($lang->translate($cat['category_key'], $cat['title'])); ?></h3>

                    <?php
                        $dk = 'desc_' . $cat['category_key'];
                        $dv = $lang->translate($dk, $cat['description'] ?? '');
                        if ($dv === $dk) { $dv = $cat['description'] ?? ''; }
                    ?>
                    <?php if (!empty($dv)): ?>
                    <div>
                        <p class="svc-desc line-clamp-2" id="desc-<?php echo (int)$cat['id']; ?>"><?php echo esc($dv); ?></p>
                        <button type="button" class="read-more-btn" onclick="toggleDescription('desc-<?php echo (int)$cat['id']; ?>', this)">
                            <span class="btn-text"><?php echo $E('read_more', 'Read More'); ?></span>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                    </div>
                    <?php endif; ?>
                </div>

                <div class="svc-foot">
                    <a href="category.php?id=<?php echo (int)$cat['id']; ?>" class="svc-btn">
                        <?php echo $E('explore', 'Explore'); ?><i class="fas fa-arrow-right"></i>
                    </a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<!-- =========================================================================
     STATISTICS
     ========================================================================= -->
<section class="section section-dark">
    <div class="aurora aurora-blue a2 drift"></div>
    <div class="aurora aurora-gold a3 drift-slow"></div>
    <div class="grid-overlay"></div>

    <div class="wrap">
        <div class="sec-head reveal">
            <span class="badge-gold"><?php echo $E('our_numbers', 'Our Numbers'); ?></span>
            <h2 class="sec-title"><?php echo $E('numbers_title', 'Trusted by thousands across India'); ?></h2>
        </div>

        <div class="grid grid-stats">
            <?php foreach ($statistics as $i => $stat): ?>
            <div class="card-glass stat reveal-zoom" style="transition-delay:<?php echo min($i, 4) * 90; ?>ms">
                <div class="medallion md stat-icon"><i class="<?php echo esc($stat['icon_class']); ?>"></i></div>
                <?php
                    $raw = trim($stat['value']);
                    preg_match('/^([^0-9]*)([0-9,\.]+)(.*)$/u', $raw, $m);
                    $pre = $m[1] ?? '';
                    $num = isset($m[2]) ? str_replace(',', '', $m[2]) : '';
                    $suf = $m[3] ?? '';
                ?>
                <div class="stat-num gold-text">
                    <?php if ($num !== ''): ?>
                        <?php echo esc($pre); ?><span class="count-up" data-target="<?php echo esc($num); ?>">0</span><?php echo esc($suf); ?>
                    <?php else: ?>
                        <?php echo esc($raw); ?>
                    <?php endif; ?>
                </div>
                <div class="stat-label">
                    <?php
                    $sk = '';
                    if     ($stat['title'] == 'সক্রিয় মেম্বার'  || $stat['title'] == 'Active Members')  $sk = 'stats_members';
                    elseif ($stat['title'] == 'সন্তুষ্ট গ্রাহক' || $stat['title'] == 'Happy Customers') $sk = 'stats_customers';
                    elseif ($stat['title'] == 'সার্ভিস এরিয়া'  || $stat['title'] == 'Service Area')    $sk = 'stats_area';
                    elseif ($stat['title'] == 'সাপোর্ট সুবিধা' || $stat['title'] == '24/7 Support')    $sk = 'stats_support';
                    echo esc($sk ? $lang->translate($sk, $stat['title']) : $stat['title']);
                    ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<!-- =========================================================================
     WHY CHOOSE US
     ========================================================================= -->
<section id="about" class="section section-soft">
    <div class="wrap">
        <div class="sec-head reveal">
            <span class="badge-gold dark"><?php echo $E('about', 'About Us'); ?></span>
            <h2 class="sec-title"><?php echo $E('why_choose_us', 'Why Choose Us?'); ?></h2>
            <div class="gold-line center" style="margin-bottom:20px"></div>
            <p class="sec-sub"><?php echo $E('why_desc', 'We are the best for superior service and reliability'); ?></p>
        </div>

        <div class="grid grid-3">
            <?php foreach ($why_choose_us as $i => $item): ?>
            <?php
                $wk = $wd = '';
                if     ($item['title'] == 'দ্রুততম পরিষেবা'  || $item['title'] == 'Fastest Service')  { $wk = 'fast_service'; $wd = 'fast_desc'; }
                elseif ($item['title'] == 'সম্পূর্ণ সুরক্ষিত' || $item['title'] == 'Fully Secure')     { $wk = 'secure';       $wd = 'secure_desc'; }
                elseif ($item['title'] == 'সেরা কমিশন'      || $item['title'] == 'Best Commission')  { $wk = 'commission';   $wd = 'commission_desc'; }
            ?>
            <div class="card why reveal" style="transition-delay:<?php echo $i * 110; ?>ms">
                <span class="why-num">0<?php echo $i + 1; ?></span>
                <div class="medallion xl why-icon"><i class="<?php echo esc($item['icon_class']); ?>"></i></div>
                <h3 class="why-title"><?php echo esc($wk ? $lang->translate($wk, $item['title']) : $item['title']); ?></h3>
                <p class="why-desc"><?php echo esc($wd ? $lang->translate($wd, $item['description']) : $item['description']); ?></p>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<!-- =========================================================================
     TEAM
     ========================================================================= -->
<section id="team" class="section section-white">
    <div class="wrap">
        <div class="sec-head reveal">
            <span class="badge-gold dark"><?php echo $E('team', 'Management Team'); ?></span>
            <h2 class="sec-title"><?php echo $E('team_title', 'The People Behind The Platform'); ?></h2>
            <div class="gold-line center" style="margin-bottom:20px"></div>
            <p class="sec-sub"><?php echo $E('team_desc', 'Meet our experienced team'); ?></p>
        </div>

        <div class="swiper teamSwiper reveal">
            <div class="swiper-wrapper">
                <?php foreach ($team_members as $member): ?>
                <div class="swiper-slide">
                    <div class="card">
                        <div class="team-photo">
                            <img src="<?php echo esc($member['photo_path']); ?>" alt="<?php echo esc($member['name']); ?>">
                            <div class="team-overlay">
                                <p><i class="fas fa-envelope"></i><?php echo esc($member['email']); ?></p>
                            </div>
                        </div>
                        <div class="team-info">
                            <h3 class="team-name"><?php echo esc($lang->translate('team_name_' . $member['id'], $member['name'])); ?></h3>
                            <p class="team-role"><?php echo esc($lang->translate('team_desig_' . $member['id'], $member['designation'])); ?></p>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <div class="swiper-pagination team-pagination"></div>
        </div>
    </div>
</section>

<!-- =========================================================================
     VIDEOS
     ========================================================================= -->
<section class="section section-dark">
    <div class="aurora aurora-blue a2 drift-slow"></div>
    <div class="wrap">
        <div class="sec-head reveal">
            <span class="badge-gold"><?php echo $E('videos', 'Videos'); ?></span>
            <h2 class="sec-title"><?php echo $E('video_title', 'Business Promotional Videos'); ?></h2>
            <div class="gold-line center" style="margin-bottom:20px"></div>
            <p class="sec-sub"><?php echo $E('video_desc', 'Increase your income by joining us'); ?></p>
        </div>

        <div class="swiper videoSwiper reveal">
            <div class="swiper-wrapper">
                <?php foreach ($videos as $video): ?>
                <div class="swiper-slide">
                    <div class="video-card">
                        <div class="video-ratio">
                            <iframe class="yt-frame"
                                    src="https://www.youtube.com/embed/<?php echo esc($video['youtube_id']); ?>?enablejsapi=1&amp;rel=0&amp;playsinline=1"
                                    title="<?php echo esc($video['title']); ?>"
                                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                    allowfullscreen></iframe>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <div class="swiper-pagination video-pagination"></div>
        </div>
    </div>
</section>

<!-- =========================================================================
     CTA
     ========================================================================= -->
<section class="section section-navy">
    <div class="aurora aurora-gold a1 drift"></div>
    <div class="aurora aurora-gold a2 drift-slow"></div>
    <div class="grid-overlay"></div>

    <div class="wrap">
        <div class="sec-head reveal" style="max-width:760px;margin-bottom:0">
            <span class="badge-gold"><i class="fas fa-crown"></i><?php echo $E('premium_partner', 'Premium Partnership'); ?></span>
            <h2 class="sec-title"><?php echo $E('cta_title', 'Your Trusted Digital Partner'); ?></h2>
            <p class="sec-sub" style="margin-bottom:34px"><?php echo $E('cta_desc', 'Start working with us and earn every month. Register today!'); ?></p>

            <div class="hero-actions" style="justify-content:center">
                <?php if ($is_authed): ?>
                    <a href="<?php echo esc($dashboard_link); ?>" class="btn btn-gold btn-lg pulse-gold">
                        <?php echo $E('go_to_dashboard', 'Go to Dashboard'); ?><i class="fas fa-arrow-right"></i>
                    </a>
                <?php else: ?>
                    <a href="register.php" class="btn btn-gold btn-lg pulse-gold"><?php echo $E('join_now', 'Join Now'); ?><i class="fas fa-rocket"></i></a>
                    <a href="seller-register.php" class="btn btn-ghost btn-lg"><i class="fas fa-store"></i><?php echo $E('become_seller', 'Become a Seller'); ?></a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<!-- =========================================================================
     CONTACT
     ========================================================================= -->
<section id="contact" class="section section-soft">
    <div class="wrap">
        <div class="sec-head reveal">
            <span class="badge-gold dark"><?php echo $E('contact', 'Contact'); ?></span>
            <h2 class="sec-title"><?php echo $E('contact_us', 'Contact Us'); ?></h2>
            <div class="gold-line center" style="margin-bottom:20px"></div>
            <p class="sec-sub"><?php echo $E('contact_desc', 'Fill out the form below and our team will reach out'); ?></p>
        </div>

        <div class="contact-card reveal">
            <div class="contact-info">
                <div class="aurora aurora-gold a1 drift" style="width:220px;height:220px"></div>
                <div class="grid-overlay"></div>
                <div class="contact-info-in">
                    <h3><?php echo $E('get_in_touch', 'Get in Touch'); ?></h3>
                    <div class="gold-line"></div>
                    <p class="lead"><?php echo $E('get_in_touch_desc', 'Fill up the form and our team will get back to you within 24 hours.'); ?></p>

                    <a href="tel:<?php echo esc(preg_replace('/\s+/', '', $company_phone)); ?>" class="contact-row">
                        <span class="medallion sm"><i class="fas fa-phone-alt"></i></span>
                        <span class="txt"><?php echo esc($company_phone); ?></span>
                    </a>
                    <a href="mailto:<?php echo esc($company_email); ?>" class="contact-row">
                        <span class="medallion sm"><i class="fas fa-envelope"></i></span>
                        <span class="txt"><?php echo esc($company_email); ?></span>
                    </a>
                    <div class="contact-row">
                        <span class="medallion sm"><i class="fas fa-location-dot"></i></span>
                        <span class="txt"><?php echo esc($company_address); ?></span>
                    </div>
                    <div class="contact-row">
                        <span class="medallion sm"><i class="fas fa-clock"></i></span>
                        <span class="txt"><?php echo esc($office_time); ?></span>
                    </div>
                </div>
            </div>

            <div class="contact-form">
                <form id="contactForm" method="POST" action="contact-process.php" data-no-lock novalidate>
                    <div class="field">
                        <label for="cf-name"><?php echo $E('name', 'Your Name'); ?></label>
                        <input id="cf-name" type="text" name="name" required class="input-premium" placeholder="<?php echo $E('name_placeholder', 'Enter your full name'); ?>">
                    </div>

                    <div class="grid grid-2" style="gap:18px">
                        <div class="field">
                            <label for="cf-mobile"><?php echo $E('mobile', 'Mobile Number'); ?></label>
                            <input id="cf-mobile" type="tel" name="mobile" required class="input-premium" placeholder="<?php echo $E('mobile_placeholder', 'Enter 10 digit number'); ?>">
                        </div>
                        <div class="field">
                            <label for="cf-role"><?php echo $E('select_role', 'Role'); ?></label>
                            <select id="cf-role" name="service" required class="input-premium">
                                <option value=""><?php echo $E('select_role_placeholder', 'Select role...'); ?></option>
                                <option value="User"><?php echo $E('role_user', 'User'); ?></option>
                                <option value="Seller"><?php echo $E('role_seller', 'Seller'); ?></option>
                                <option value="Employee"><?php echo $E('role_employee', 'Employee'); ?></option>
                                <option value="Admin"><?php echo $E('role_admin', 'Admin'); ?></option>
                            </select>
                        </div>
                    </div>

                    <div class="field">
                        <label for="cf-msg"><?php echo $E('message', 'Message'); ?></label>
                        <textarea id="cf-msg" name="message" rows="4" required class="input-premium" placeholder="<?php echo $E('message_placeholder', 'Write your question here...'); ?>"></textarea>
                    </div>

                    <button type="submit" id="contactSubmit" class="btn btn-gold btn-block btn-lg">
                        <i class="fas fa-paper-plane"></i><span class="label"><?php echo $E('send_message', 'Send Message'); ?></span>
                    </button>

                    <p id="contactStatus" class="form-note hidden"></p>
                </form>
            </div>
        </div>
    </div>
</section>

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

<script src="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.js"></script>
<script>
/* ---------------------------------------------------------------- reveal */
(function () {
    var items = document.querySelectorAll('.reveal, .reveal-zoom');
    if (!items.length) return;
    if (!('IntersectionObserver' in window)) {
        Array.prototype.forEach.call(items, function (el) { el.classList.add('in'); });
        return;
    }
    var io = new IntersectionObserver(function (entries) {
        entries.forEach(function (e) {
            if (!e.isIntersecting) return;
            var el = e.target;
            el.classList.add('in');
            io.unobserve(el);
            if (el.style.transitionDelay) {
                setTimeout(function () { el.style.transitionDelay = ''; }, 1400);
            }
        });
    }, { threshold: 0.08, rootMargin: '0px 0px -50px 0px' });
    Array.prototype.forEach.call(items, function (el) { io.observe(el); });
    // Anything already on screen at load reveals immediately.
    setTimeout(function () {
        Array.prototype.forEach.call(items, function (el) {
            var r = el.getBoundingClientRect();
            if (r.top < window.innerHeight && r.bottom > 0) el.classList.add('in');
        });
    }, 60);
})();

/* ------------------------------------------------------------- count up */
(function () {
    var els = document.querySelectorAll('.count-up');
    if (!els.length) return;

    function run(el) {
        if (el.dataset.done === '1') return;
        el.dataset.done = '1';
        var target = parseFloat(el.dataset.target) || 0;
        var decimals = (el.dataset.target.split('.')[1] || '').length;
        var duration = 1900, start = null;
        function step(ts) {
            if (!start) start = ts;
            var p = Math.min((ts - start) / duration, 1);
            var val = target * (1 - Math.pow(1 - p, 3));
            el.textContent = decimals ? val.toFixed(decimals) : Math.floor(val).toLocaleString('en-IN');
            if (p < 1) requestAnimationFrame(step);
            else el.textContent = decimals ? target.toFixed(decimals) : target.toLocaleString('en-IN');
        }
        requestAnimationFrame(step);
    }

    if ('IntersectionObserver' in window) {
        var io = new IntersectionObserver(function (entries) {
            entries.forEach(function (e) { if (e.isIntersecting) { run(e.target); io.unobserve(e.target); } });
        }, { threshold: 0.3 });
        Array.prototype.forEach.call(els, function (el) { io.observe(el); });
    } else {
        Array.prototype.forEach.call(els, run);
    }
})();

/* --------------------------------------------------- read more / less */
var TXT_MORE = <?php echo json_encode($T('read_more', 'Read More'), JSON_UNESCAPED_UNICODE); ?>;
var TXT_LESS = <?php echo json_encode($T('read_less', 'Read Less'), JSON_UNESCAPED_UNICODE); ?>;

document.addEventListener('DOMContentLoaded', function () {
    Array.prototype.forEach.call(document.querySelectorAll('.svc-desc'), function (desc) {
        if (desc.scrollHeight > desc.clientHeight + 1) {
            var btn = desc.nextElementSibling;
            if (btn && btn.classList.contains('read-more-btn')) btn.classList.add('show');
        }
    });
});

function toggleDescription(id, btn) {
    var el   = document.getElementById(id);
    var text = btn.querySelector('.btn-text');
    var icon = btn.querySelector('i');
    var clamped = el.classList.toggle('line-clamp-2');
    text.textContent = clamped ? TXT_MORE : TXT_LESS;
    icon.style.transform = clamped ? '' : 'rotate(180deg)';
}

/* ------------------------------------------------------------- sliders */
if (window.Swiper) {
    new Swiper('.heroSwiper', {
        loop: <?php echo count($hero_slides) > 1 ? 'true' : 'false'; ?>,
        effect: 'fade',
        fadeEffect: { crossFade: true },
        speed: 900,
        autoplay: { delay: 6000, disableOnInteraction: false },
        pagination: { el: '.hero-pagination', clickable: true },
        navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
        on: {
            init: function () { var s = this.slides[this.activeIndex]; if (s) { var i = s.querySelector('.hero-media'); if (i) i.classList.add('kenburns'); } },
            slideChangeTransitionStart: function () {
                Array.prototype.forEach.call(this.slides, function (s) { var i = s.querySelector('.hero-media'); if (i) i.classList.remove('kenburns'); });
                var a = this.slides[this.activeIndex];
                if (a) { var img = a.querySelector('.hero-media'); if (img) { void img.offsetWidth; img.classList.add('kenburns'); } }
            }
        }
    });

    new Swiper('.teamSwiper', {
        slidesPerView: 1.15, spaceBetween: 18,
        loop: <?php echo count($team_members) > 4 ? 'true' : 'false'; ?>,
        autoplay: { delay: 3500, disableOnInteraction: false },
        pagination: { el: '.team-pagination', clickable: true },
        breakpoints: { 640:{slidesPerView:2,spaceBetween:22}, 1024:{slidesPerView:3,spaceBetween:26}, 1280:{slidesPerView:4,spaceBetween:26} }
    });

    window.wbVideoSwiper = new Swiper('.videoSwiper', {
        slidesPerView: 1.08, spaceBetween: 18,
        loop: <?php echo count($videos) > 3 ? 'true' : 'false'; ?>,
        autoplay: { delay: 5000, disableOnInteraction: false },
        pagination: { el: '.video-pagination', clickable: true },
        breakpoints: { 768:{slidesPerView:2,spaceBetween:22}, 1024:{slidesPerView:3,spaceBetween:26} }
    });
}

/* -------------------------------------------------------------------------
   VIDEO SLIDER — freeze while a video is playing
   -------------------------------------------------------------------------
   While any YouTube video in the slider is playing the carousel stops
   auto-sliding (and dragging is disabled) so the clip can run to the end.
   As soon as the video ends – or the visitor pauses it – the carousel
   starts moving again.  Playing one video pauses any other one.
   ------------------------------------------------------------------------- */
(function () {
    var wrap = document.querySelector('.videoSwiper');
    if (!wrap || !window.wbVideoSwiper) return;

    var frames = wrap.querySelectorAll('iframe.yt-frame');
    if (!frames.length) return;

    var sw      = window.wbVideoSwiper;
    var players = [];
    var locked  = false;

    function freeze() {
        if (locked) return;
        locked = true;
        wrap.classList.add('is-playing');
        if (sw.autoplay && sw.autoplay.stop) sw.autoplay.stop();
        sw.allowTouchMove = false;
    }

    /* Only release the carousel when NOTHING is playing or buffering. */
    function release() {
        for (var i = 0; i < players.length; i++) {
            try {
                var st = players[i].getPlayerState();
                if (st === 1 || st === 3) return;   // 1 = playing, 3 = buffering
            } catch (e) {}
        }
        if (!locked) return;
        locked = false;
        wrap.classList.remove('is-playing');
        sw.allowTouchMove = true;
        if (sw.autoplay && sw.autoplay.start) sw.autoplay.start();
    }

    function onState(e) {
        if (e.data === 1) {                 // PLAYING
            freeze();
            players.forEach(function (p) {
                try { if (p !== e.target && p.getPlayerState() === 1) p.pauseVideo(); } catch (err) {}
            });
        } else if (e.data === 0 || e.data === 2) {   // ENDED / PAUSED
            setTimeout(release, 200);
        }
    }

    function build() {
        Array.prototype.forEach.call(frames, function (f, i) {
            if (!f.id) f.id = 'wbYtFrame' + i;
            try { players.push(new YT.Player(f.id, { events: { onStateChange: onState } })); } catch (e) {}
        });
    }

    if (window.YT && window.YT.Player) {
        build();
    } else {
        var prev = window.onYouTubeIframeAPIReady;
        window.onYouTubeIframeAPIReady = function () {
            if (typeof prev === 'function') { try { prev(); } catch (e) {} }
            build();
        };
        if (!document.getElementById('wbYtApi')) {
            var s = document.createElement('script');
            s.id  = 'wbYtApi';
            s.src = 'https://www.youtube.com/iframe_api';
            document.head.appendChild(s);
        }
    }
})();

/* -------------------------------------------------------- contact form */
(function () {
    var form = document.getElementById('contactForm');
    if (!form) return;
    var btn    = document.getElementById('contactSubmit');
    var label  = btn.querySelector('.label');
    var status = document.getElementById('contactStatus');
    var orig   = label.textContent;

    var MSG_OK  = <?php echo json_encode($T('message_sent',  'Your message has been sent successfully!'), JSON_UNESCAPED_UNICODE); ?>;
    var MSG_ERR = <?php echo json_encode($T('message_error', 'Sorry, message could not be sent. Please try again.'), JSON_UNESCAPED_UNICODE); ?>;
    var MSG_GEN = <?php echo json_encode($T('error',         'An error occurred. Please try again.'), JSON_UNESCAPED_UNICODE); ?>;
    var SENDING = <?php echo json_encode($T('sending',       'Sending...'), JSON_UNESCAPED_UNICODE); ?>;

    function show(msg, ok) {
        status.textContent = msg;
        status.className = 'form-note ' + (ok ? 'ok' : 'err');
    }
    function reset() { btn.disabled = false; label.textContent = orig; }

    form.addEventListener('submit', function (e) {
        e.preventDefault();
        if (!form.checkValidity()) { form.reportValidity(); return; }
        btn.disabled = true;
        label.textContent = SENDING;

        fetch('contact-process.php', { method: 'POST', body: new FormData(form) })
            .then(function (r) { return r.json(); })
            .then(function (d) {
                if (d && d.success) { show(MSG_OK, true); form.reset(); }
                else { show(MSG_ERR, false); }
                reset();
            })
            .catch(function () { show(MSG_GEN, false); reset(); });
    });
})();
</script>
