<?php
include "config.php";

$filters = [
    'total_margin', 'active_trading', 'total_lots', 'stop_outs',
    'profitability_score', 'new_users',
    'spread_cost', 'rollover_cost', 'net_deposit',
    'net_withdrawal', 'active_funds'
];

function getBrokerLogo($name) {
    $logos = [
        'FBS' => '/uploads/fbs.png',
        'Exness' => '/uploads/exness.png',
        'IC Markets Global' => '/uploads/icmarketsglobal.png',
    ];
    return $logos[$name] ?? 'https://tradersafety.com/uploads/logo-grey.png';
}
?>

<style>
/* --- Main Wrapper for Centering & Margins --- */
.ranking-carousel-wrapper {
    max-width: 1400px;
    margin: 0 auto;
    padding: 20px;
    width: 100%;
    box-sizing: border-box;
}

/* --- Carousel Container --- */
.filter-row * {
    box-sizing: border-box;
}

.filter-row {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;
    gap: 16px;
    padding: 10px 6px 20px 6px; /* Bottom padding for scrollbar room */
    margin-bottom: 20px;
    scroll-snap-type: x mandatory;
    scroll-padding-inline: 6px;
    scroll-behavior: smooth;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: thin;
    scrollbar-color: #d1d1d1 #f5f5f5;
    scroll-behavior: smooth;
}

/* Custom Scrollbar */
.filter-row::-webkit-scrollbar {
    height: 8px;
}
.filter-row::-webkit-scrollbar-thumb {
    background: #d1d1d1;
    border-radius: 10px;
}
.filter-row::-webkit-scrollbar-track {
    background: #f5f5f5;
    border-radius: 10px;
}

/* --- Card List Design --- */
.list-l {
    flex: 0 0 calc((100% - 32px) / 3);
    width: calc((100% - 32px) / 3);
    max-width: calc((100% - 32px) / 3);
    display: block !important;
    list-style: none;
    padding: 0;
    margin: 0;
    background: #fff;
    border: 1px solid #eaeaea;
    border-radius: 12px;
    scroll-snap-align: start;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    overflow: hidden;
}

.list-l li {
    display: block !important;
    float: none !important;
    width: 100% !important;
    border-bottom: 1px solid #f0f0f0;
    transition: all 0.2s ease;
}

.list-l li:last-child {
    border-bottom: none;
}

.list-l li:hover {
    background-color: #fcfcfc;
    box-shadow: inset 4px 0 0 #fcd734; /* Subtle gold highlight on left side on hover */
}

.list-l a {
    text-decoration: none;
    color: inherit;
    display: block;
    width: 100%;
    padding: 16px 20px;
}

/* --- Typography & Elements --- */
.list-title {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 0 0 12px 0;
    width: 100%;
}

.list-title-1 {
    color: #fff;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    white-space: nowrap;
    flex-shrink: 0; /* Prevents badge from squishing */
}

.broker-logo-img {
    width: 28px;
    height: 28px;
    border-radius: 4px;
    object-fit: contain;
    background: #fff;
    border: 1px solid #eee;
    flex-shrink: 0; /* Prevents logo from squishing */
}

.list-title-2 {
    font-weight: 700;
    color: #2e3440;
    font-size: 15px;
    flex-grow: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis; /* Adds '...' if name is too long */
}

.list-text {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    margin: 0 0 6px 0;
}

.list-text-1 {
    font-size: 13px;
    color: #666;
    font-weight: 500;
}

.list-text-2 {
    color: #2CB250; 
    font-weight: 700;
    font-size: 15px;
}

.list-des {
    font-size: 13px;
    color: #888;
    margin: 0;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2; /* Forces text to max 2 lines */
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

@media (max-width: 900px) {
    .ranking-carousel-wrapper {
        padding: 16px 12px;
    }

    .filter-row {
        gap: 12px;
        padding-left: 4px;
        padding-right: 4px;
        scroll-padding-inline: 4px;
    }

    .list-l {
        flex-basis: calc((100% - 12px) / 2);
        width: calc((100% - 12px) / 2);
        max-width: calc((100% - 12px) / 2);
    }
}

@media (max-width: 600px) {
    .ranking-carousel-wrapper {
        padding: 12px 10px;
    }

    .filter-row {
        gap: 10px;
        padding-left: 2px;
        padding-right: 2px;
        scroll-padding-inline: 2px;
    }

    .list-l {
        flex-basis: calc(100vw - 28px);
        width: calc(100vw - 28px);
        max-width: calc(100vw - 28px);
    }
}
</style>

<div class="ranking-carousel-wrapper">
    <div class="filter-row">
    <?php foreach ($filters as $filter): ?>
        <?php
        $stmt = $dbh->prepare("SELECT * FROM broker_rankings ORDER BY $filter DESC LIMIT 5");
        $stmt->execute();
        $brokers = $stmt->fetchAll(PDO::FETCH_ASSOC);
        ?>
        <ul class="list-l" id="<?= htmlspecialchars($filter) ?>">
            <?php foreach ($brokers as $broker): ?>
                <li>
                    <a href="#" target="_blank">
                        <h3 class="list-title">
                            <span class="list-title-1" style="background-color:#<?= substr(md5($filter), 0, 6) ?>;">
                                <?= ucwords(str_replace('_', ' ', $filter)) ?>
                            </span>
                            <img src="<?= getBrokerLogo($broker['broker_name']) ?>" alt="Logo" class="broker-logo-img">
                            <span class="list-title-2"><?= htmlspecialchars($broker['broker_name']) ?></span>
                        </h3>
                        
                        <p class="list-text">
                            <span class="list-text-1">Value</span>
                            <span class="list-text-2"><?= number_format($broker[$filter], 2) ?></span>
                        </p>
                        
                        <p class="list-des">Placeholder strategy description for <?= htmlspecialchars($broker['broker_name']) ?>.</p>
                    </a>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php endforeach; ?>
    </div>
</div>

<script>
    const carousel = document.querySelector('.filter-row');

    function getCarouselStep() {
        const firstCard = carousel?.querySelector('.list-l');
        if (!carousel || !firstCard) return 0;
        const style = window.getComputedStyle(carousel);
        const gap = parseInt(style.columnGap || style.gap || '0', 10) || 0;
        return firstCard.offsetWidth + gap;
    }

    function startCarouselMotion() {
        if (!carousel) return;

        let timer = null;
        const stop = () => {
            if (timer) {
                clearInterval(timer);
                timer = null;
            }
        };

        const start = () => {
            stop();
            timer = setInterval(() => {
                const step = getCarouselStep();
                if (!step) return;
                const maxLeft = carousel.scrollWidth - carousel.clientWidth;
                if (carousel.scrollLeft >= maxLeft - 2) {
                    carousel.scrollTo({ left: 0, behavior: 'smooth' });
                } else {
                    carousel.scrollBy({ left: step, behavior: 'smooth' });
                }
            }, 2600);
        };

        carousel.addEventListener('mouseenter', stop);
        carousel.addEventListener('mouseleave', start);
        carousel.addEventListener('touchstart', stop, { passive: true });
        carousel.addEventListener('touchend', start, { passive: true });

        start();
    }

  function scrollToFilter(filterId) {
    const section = document.getElementById(filterId);
    if (section) {
      section.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
    }
  }

    document.addEventListener('DOMContentLoaded', startCarouselMotion);
</script>