<?php
// phpcs:ignoreFile
if (!defined('ABSPATH')) { exit; }

global $wpdb;
$services_table = $wpdb->prefix . 'yatoon_services';
$atts_filter    = $atts ?? array();
$category_filter = sanitize_text_field($atts_filter['category'] ?? '');
$limit           = max(1, min(100, intval($atts_filter['limit'] ?? 50)));
$cols            = max(2, min(5, intval($atts_filter['cols'] ?? 3)));

$where = "WHERE is_active = 1";
if ($category_filter) {
    $where .= $wpdb->prepare(" AND category = %s", $category_filter);
}

$services = $wpdb->get_results("SELECT * FROM $services_table $where ORDER BY is_featured DESC, sort_order ASC, name ASC LIMIT $limit");

$primary_color = get_option('yatoon_primary_color', '#C2185B');
$business_name = get_option('yatoon_business_name', get_bloginfo('name'));
$booking_page  = get_option('yatoon_booking_page_url', '');

if (empty($services)) {
    return '';
}

// Get unique categories for filter tabs
$categories = $wpdb->get_col("SELECT DISTINCT category FROM $services_table WHERE is_active = 1 AND category != '' ORDER BY category ASC");
?>

<div class="yatoon-catalog" id="yatoon-catalog-<?php echo esc_attr(uniqid()); ?>" data-cols="<?php echo esc_attr($cols); ?>">

<?php if (!empty($categories) && count($categories) > 1): ?>
<div class="ycat-filter-tabs">
    <button type="button" class="ycat-tab active" data-cat="all">All</button>
    <?php foreach ($categories as $cat): ?>
    <button type="button" class="ycat-tab" data-cat="<?php echo esc_attr(strtolower($cat)); ?>"><?php echo esc_html($cat); ?></button>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<div class="ycat-grid" style="--cols:<?php echo esc_attr($cols); ?>">
<?php foreach ($services as $svc):
    $price_label = $svc->price > 0 ? 'from $' . number_format($svc->price, 0) : 'Price varies';
    $duration    = $svc->duration_minutes ? $svc->duration_minutes . ' min' : '';
    $cat_slug    = strtolower($svc->category ?? '');
?>
<div class="ycat-card" data-cat="<?php echo esc_attr($cat_slug); ?>" data-service-id="<?php echo esc_attr($svc->id); ?>">
    <?php if ($svc->is_featured): ?>
    <span class="ycat-popular">Popular</span>
    <?php endif; ?>

    <div class="ycat-img-wrap">
        <?php if ($svc->image_url): ?>
        <img src="<?php echo esc_url($svc->image_url); ?>" alt="<?php echo esc_attr($svc->name); ?>" loading="lazy">
        <?php else: ?>
        <div class="ycat-img-placeholder">
            <svg width="40" height="40" viewBox="0 0 40 40" fill="none"><rect x="4" y="10" width="32" height="24" rx="4" fill="#f3f4f6" stroke="#e5e7eb" stroke-width="1.5"/><circle cx="14" cy="18" r="3" fill="#d1d5db"/><path d="M4 28l8-8 6 6 4-4 10 10" stroke="#e5e7eb" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
        </div>
        <?php endif; ?>
    </div>

    <div class="ycat-card-body">
        <h3 class="ycat-name"><?php echo esc_html($svc->name); ?></h3>
        <?php if ($svc->category): ?>
        <div class="ycat-category"><?php echo esc_html($svc->category); ?></div>
        <?php endif; ?>
        <?php if ($svc->description): ?>
        <p class="ycat-desc"><?php echo esc_html(mb_strimwidth($svc->description, 0, 90, '...')); ?></p>
        <?php endif; ?>
        <div class="ycat-footer">
            <div class="ycat-meta">
                <span class="ycat-price"><?php echo esc_html($price_label); ?></span>
                <?php if ($duration): ?>
                <span class="ycat-duration"><?php echo esc_html($duration); ?></span>
                <?php endif; ?>
            </div>
            <button type="button" class="ycat-book-btn" data-service-id="<?php echo esc_attr($svc->id); ?>" data-service-name="<?php echo esc_attr($svc->name); ?>">
                Book
            </button>
        </div>
    </div>
</div>
<?php endforeach; ?>
</div>

<!-- Popup overlay -->
<div class="ycat-popup-overlay" id="ycat-popup" style="display:none;" role="dialog" aria-modal="true" aria-label="Book appointment">
    <div class="ycat-popup-inner">
        <button type="button" class="ycat-popup-close" aria-label="Close">&times;</button>
        <div class="ycat-popup-content">
            <?php if ($booking_page): ?>
            <div class="ycat-popup-loading">
                <div class="ycat-spinner"></div>
                <p>Loading booking form...</p>
            </div>
            <iframe class="ycat-popup-iframe" src="" frameborder="0" scrolling="yes" style="display:none;"></iframe>
            <?php else: ?>
            <div style="padding:32px;text-align:center;">
                <?php do_shortcode('[yatoon_booking]'); ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

</div><!-- /yatoon-catalog -->

<style>
.yatoon-catalog { font-family: inherit; }

.ycat-filter-tabs {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    margin-bottom: 20px;
}

.ycat-tab {
    padding: 7px 16px;
    border-radius: 20px;
    border: 1.5px solid #e5e7eb;
    background: #fff;
    font-size: 13px;
    font-weight: 500;
    color: #374151;
    cursor: pointer;
    transition: all .15s;
}

.ycat-tab.active,
.ycat-tab:hover {
    background: <?php echo esc_attr($primary_color); ?>;
    border-color: <?php echo esc_attr($primary_color); ?>;
    color: #fff;
}

.ycat-grid {
    display: grid;
    grid-template-columns: repeat(var(--cols, 3), 1fr);
    gap: 16px;
}

@media (max-width: 768px) {
    .ycat-grid { grid-template-columns: repeat(2, 1fr); gap: 12px; }
}
@media (max-width: 480px) {
    .ycat-grid { grid-template-columns: 1fr; }
}

.ycat-card {
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 14px;
    overflow: hidden;
    transition: box-shadow .2s ease, transform .2s ease;
    position: relative;
    display: flex;
    flex-direction: column;
}

.ycat-card:hover {
    box-shadow: 0 8px 28px rgba(0,0,0,.1);
    transform: translateY(-2px);
}

.ycat-popular {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 2;
    font-size: 11px;
    font-weight: 700;
    padding: 2px 9px;
    border-radius: 20px;
    background: #fdf2f8;
    color: #9d174d;
    border: 1px solid #fbcfe8;
    text-transform: uppercase;
    letter-spacing: .03em;
}

.ycat-img-wrap {
    width: 100%;
    aspect-ratio: 4/3;
    overflow: hidden;
    background: #f9fafb;
    display: flex;
    align-items: center;
    justify-content: center;
}

.ycat-img-wrap img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform .3s ease;
}

.ycat-card:hover .ycat-img-wrap img {
    transform: scale(1.04);
}

.ycat-img-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    min-height: 120px;
}

.ycat-card-body {
    padding: 14px 16px 16px;
    display: flex;
    flex-direction: column;
    flex: 1;
}

.ycat-name {
    font-size: 15px;
    font-weight: 700;
    color: #111827;
    margin: 0 0 3px;
    line-height: 1.3;
}

.ycat-category {
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: .05em;
    color: <?php echo esc_attr($primary_color); ?>;
    margin-bottom: 6px;
}

.ycat-desc {
    font-size: 13px;
    color: #6b7280;
    line-height: 1.5;
    margin: 0 0 10px;
    flex: 1;
}

.ycat-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    margin-top: auto;
}

.ycat-meta {
    display: flex;
    flex-direction: column;
    gap: 1px;
}

.ycat-price {
    font-size: 15px;
    font-weight: 700;
    color: #111827;
}

.ycat-duration {
    font-size: 12px;
    color: #9ca3af;
}

.ycat-book-btn {
    padding: 8px 20px;
    background: <?php echo esc_attr($primary_color); ?>;
    color: #fff;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    white-space: nowrap;
    transition: opacity .15s;
    flex-shrink: 0;
}

.ycat-book-btn:hover { opacity: .88; }

/* Popup */
.ycat-popup-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,.5);
    z-index: 99999;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16px;
    backdrop-filter: blur(4px);
}

.ycat-popup-inner {
    background: #fff;
    border-radius: 16px;
    width: 100%;
    max-width: 900px;
    max-height: 90vh;
    overflow: hidden;
    position: relative;
    display: flex;
    flex-direction: column;
    box-shadow: 0 20px 60px rgba(0,0,0,.25);
}

.ycat-popup-close {
    position: absolute;
    top: 12px;
    right: 14px;
    z-index: 10;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    border: 1px solid #e5e7eb;
    background: #fff;
    font-size: 18px;
    line-height: 1;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #6b7280;
    transition: all .15s;
}

.ycat-popup-close:hover {
    background: #f3f4f6;
    color: #111827;
}

.ycat-popup-content {
    overflow-y: auto;
    flex: 1;
}

.ycat-popup-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px;
    gap: 16px;
    color: #6b7280;
    font-size: 14px;
}

.ycat-spinner {
    width: 36px;
    height: 36px;
    border: 3px solid #f3f4f6;
    border-top-color: <?php echo esc_attr($primary_color); ?>;
    border-radius: 50%;
    animation: ycat-spin .7s linear infinite;
}

@keyframes ycat-spin { to { transform: rotate(360deg); } }

.ycat-popup-iframe {
    width: 100%;
    height: 80vh;
    border: none;
}

.ycat-card.ycat-hidden { display: none; }
</style>

<script>
(function() {
    document.addEventListener('DOMContentLoaded', function() {
        // Category filter tabs
        document.querySelectorAll('.ycat-tab').forEach(function(tab) {
            tab.addEventListener('click', function() {
                const cat = this.dataset.cat;
                document.querySelectorAll('.ycat-tab').forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                document.querySelectorAll('.ycat-card').forEach(function(card) {
                    if (cat === 'all' || card.dataset.cat === cat) {
                        card.classList.remove('ycat-hidden');
                    } else {
                        card.classList.add('ycat-hidden');
                    }
                });
            });
        });

        // Book button -> open popup
        const bookingPage = <?php echo json_encode($booking_page ?: ''); ?>;
        document.querySelectorAll('.ycat-book-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                const serviceId = this.dataset.serviceId;
                const popup = document.getElementById('ycat-popup');
                popup.style.display = 'flex';
                document.body.style.overflow = 'hidden';

                if (bookingPage) {
                    const sep = bookingPage.includes('?') ? '&' : '?';
                    const url = bookingPage + sep + 'service_id=' + serviceId;
                    const iframe = popup.querySelector('.ycat-popup-iframe');
                    const loading = popup.querySelector('.ycat-popup-loading');
                    loading.style.display = 'flex';
                    iframe.style.display = 'none';
                    iframe.src = url;
                    iframe.onload = function() {
                        loading.style.display = 'none';
                        iframe.style.display = 'block';
                    };
                }
            });
        });

        // Close popup
        function closePopup() {
            const popup = document.getElementById('ycat-popup');
            popup.style.display = 'none';
            document.body.style.overflow = '';
            const iframe = popup ? popup.querySelector('.ycat-popup-iframe') : null;
            if (iframe) iframe.src = '';
        }

        document.querySelectorAll('.ycat-popup-close, .ycat-popup-overlay').forEach(function(el) {
            el.addEventListener('click', function(e) {
                if (e.target === this) closePopup();
            });
        });

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') closePopup();
        });
    });
})();
</script>
