<?php
// /htdocs/pages/properties.php — ADVANCED LISTING PAGE + ACTIVITIES SHOWCASE
// Revenda brand: dark violet · gradient accents · system font
// Preserves original getProperties() contract and full filter surface.
// Adds: live activities showcase from global `activities` table, destination-aware.

if (!defined('APP_START')) { define('APP_START', 1); }

// ============================================
// HELPERS
// ============================================
if (!function_exists('getPropertyImageUrl')) {
    function getPropertyImageUrl($property) {
        if (!empty($property['image'])) {
            if (strpos($property['image'], 'http') === 0) return $property['image'];
            return '/uploads/' . ltrim($property['image'], '/');
        }
        if (!empty($property['featured_image'])) {
            $f = $property['featured_image'];
            return strpos($f, 'http') === 0 ? $f : '/uploads/' . ltrim($f, '/');
        }
        if (!empty($property['id']) && function_exists('getPropertyImages')) {
            $images = getPropertyImages($property['id']);
            if (!empty($images) && !empty($images[0]['file_path'])) {
                return '/uploads/' . ltrim($images[0]['file_path'], '/');
            }
        }
        return 'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=800&h=600&fit=crop';
    }
}

if (!function_exists('getAmenityIconSafe')) {
    function getAmenityIconSafe($amenity) {
        $icons = [
            'wifi' => 'fa-wifi', 'pool' => 'fa-swimming-pool', 'parking' => 'fa-parking',
            'air_conditioning' => 'fa-snowflake', 'breakfast' => 'fa-utensils', 'gym' => 'fa-dumbbell',
            'spa' => 'fa-spa', 'restaurant' => 'fa-utensils', 'bar' => 'fa-glass-martini-alt',
            'room_service' => 'fa-concierge-bell', 'laundry' => 'fa-tshirt', 'pet_friendly' => 'fa-dog',
            'family_rooms' => 'fa-users', 'non_smoking' => 'fa-smoking-ban', '24h_front_desk' => 'fa-clock',
            'luggage_storage' => 'fa-suitcase', 'concierge' => 'fa-handshake', 'free_shuttle' => 'fa-shuttle-van',
            'airport_transfer' => 'fa-plane', 'tour_desk' => 'fa-map', 'business_center' => 'fa-briefcase',
            'meeting_rooms' => 'fa-users-cog', 'wheelchair_accessible' => 'fa-wheelchair',
            'beach_access' => 'fa-umbrella-beach', 'water_sports' => 'fa-water'
        ];
        return $icons[$amenity] ?? 'fa-check-circle';
    }
}

if (!function_exists('safeStarRating')) {
    function safeStarRating($rating) {
        $rating = floatval($rating);
        $html = '';
        for ($i = 1; $i <= 5; $i++) {
            if ($i <= $rating) $html .= '<i class="fas fa-star"></i>';
            elseif ($i - 0.5 <= $rating) $html .= '<i class="fas fa-star-half-alt"></i>';
            else $html .= '<i class="far fa-star"></i>';
        }
        return $html;
    }
}

if (!function_exists('ppxSafe')) {
    function ppxSafe($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('ppxActiveFilterCount')) {
    function ppxActiveFilterCount($f) {
        $n = 0;
        if (!empty($f['search'])) $n++;
        if (!empty($f['category'])) $n++;
        if (!empty($f['country'])) $n++;
        if (!empty($f['city'])) $n++;
        if (!empty($f['star_rating'])) $n++;
        if (!empty($f['instant_book'])) $n++;
        if (!empty($f['amenities']) && is_array($f['amenities'])) $n += count($f['amenities']);
        if (!empty($f['min_price'])) $n++;
        if (!empty($f['max_price']) && $f['max_price'] < 5000) $n++;
        return $n;
    }
}

// ============================================
// ACTIVITY HELPERS (inline — no external include)
// ============================================
if (!function_exists('ppxActivityIcon')) {
    function ppxActivityIcon($type, $category = '', $subcategory = '') {
        $t = strtolower($type ?: 'attraction');
        $c = strtolower($category ?: '');
        $s = strtolower($subcategory ?: '');

        $map = [
            'attraction'    => 'fa-landmark',
            'restaurant'    => 'fa-utensils',
            'cafe'          => 'fa-mug-hot',
            'bar'           => 'fa-glass-martini-alt',
            'nightlife'     => 'fa-music',
            'museum'        => 'fa-landmark-dome',
            'gallery'       => 'fa-palette',
            'park'          => 'fa-tree',
            'beach'         => 'fa-umbrella-beach',
            'nature'        => 'fa-leaf',
            'hiking'        => 'fa-mountain',
            'adventure'     => 'fa-hiking',
            'experience'    => 'fa-star',
            'tour'          => 'fa-route',
            'shopping'      => 'fa-shopping-bag',
            'market'        => 'fa-store',
            'spa'           => 'fa-spa',
            'wellness'      => 'fa-heart',
            'entertainment' => 'fa-ticket',
            'theater'       => 'fa-masks-theater',
            'sports'        => 'fa-futbol',
            'water_sports'  => 'fa-water',
            'landmark'      => 'fa-monument',
            'religious'     => 'fa-place-of-worship',
            'viewpoint'     => 'fa-binoculars',
            'zoo'           => 'fa-paw',
            'aquarium'      => 'fa-fish',
            'theme_park'    => 'fa-roller-coaster',
            'transport'     => 'fa-bus',
        ];
        if (isset($map[$t])) return $map[$t];
        if (isset($map[$c])) return $map[$c];
        if (isset($map[$s])) return $map[$s];

        $hay = $t . ' ' . $c . ' ' . $s;
        if (strpos($hay, 'food') !== false || strpos($hay, 'din') !== false) return 'fa-utensils';
        if (strpos($hay, 'art') !== false)   return 'fa-palette';
        if (strpos($hay, 'water') !== false) return 'fa-water';
        if (strpos($hay, 'shop') !== false)  return 'fa-shopping-bag';
        if (strpos($hay, 'park') !== false)  return 'fa-tree';
        return 'fa-map-pin';
    }
}
if (!function_exists('ppxFormatActivityPrice')) {
    function ppxFormatActivityPrice($price, $currency = 'USD') {
        $price = (float)$price;
        if ($price <= 0) return 'Free';
        $symbols = ['USD' => '$', 'EUR' => '€', 'GBP' => '£', 'JPY' => '¥', 'AUD' => 'A$', 'CAD' => 'C$'];
        $sym = $symbols[strtoupper($currency)] ?? (strtoupper($currency) . ' ');
        return $sym . number_format($price, 0);
    }
}
if (!function_exists('ppxFormatActivityDuration')) {
    function ppxFormatActivityDuration($mins) {
        $mins = (int)$mins;
        if ($mins <= 0) return '';
        if ($mins < 60) return $mins . ' min';
        $h = floor($mins / 60);
        $m = $mins % 60;
        return $h . 'h' . ($m > 0 ? ' ' . $m . 'm' : '');
    }
}

// ============================================
// FETCH FILTERS (original contract preserved)
// ============================================
$search         = $_GET['search'] ?? '';
$categoryId     = (int)($_GET['category'] ?? 0);
$countryId      = (int)($_GET['country'] ?? 0);
$cityId         = (int)($_GET['city'] ?? 0);
$checkIn        = $_GET['check_in'] ?? '';
$checkOut       = $_GET['check_out'] ?? '';
$guests         = (int)($_GET['guests'] ?? 2);
$rooms          = (int)($_GET['rooms'] ?? 1);
$minPrice       = (float)($_GET['min_price'] ?? 0);
$maxPrice       = (float)($_GET['max_price'] ?? 5000);
$starRating     = (int)($_GET['star_rating'] ?? 0);
$sort           = $_GET['sort'] ?? 'relevance';
$instantBook    = isset($_GET['instant_book']);
$amenitiesFilter = $_GET['amenities'] ?? [];
if (!is_array($amenitiesFilter)) $amenitiesFilter = [];

$viewMode = $_GET['view'] ?? 'grid';
if (!in_array($viewMode, ['grid', 'list'], true)) $viewMode = 'grid';

$filters = [
    'search'       => $search,
    'category'     => $categoryId,
    'country'      => $countryId,
    'city'         => $cityId,
    'min_price'    => $minPrice,
    'max_price'    => $maxPrice,
    'star_rating'  => $starRating,
    'instant_book' => $instantBook,
    'amenities'    => $amenitiesFilter,
    'sort'         => $sort,
    'limit'        => 60,
];

$properties = [];
try {
    if (function_exists('getProperties')) {
        $properties = getProperties($filters);
    }
    if (!is_array($properties)) $properties = [];
} catch (Throwable $e) {
    $properties = [];
}

$categories = function_exists('getCategories') ? getCategories() : [];
if (!is_array($categories)) $categories = [];

$countries = function_exists('getCountries') ? getCountries() : [];
if (!is_array($countries)) $countries = [];

$cities = function_exists('getCities') ? getCities($countryId) : [];
if (!is_array($cities)) $cities = [];

$allAmenities = [
    'wifi','pool','parking','air_conditioning','breakfast','gym','spa','restaurant','bar',
    'room_service','laundry','pet_friendly','family_rooms','non_smoking','24h_front_desk',
    'beach_access','water_sports'
];

$catName = '';
foreach ($categories as $c) {
    if (($c['id'] ?? 0) == $categoryId) { $catName = $c['name'] ?? ''; break; }
}

$activeFilterCount = ppxActiveFilterCount($_GET);
$totalResults      = count($properties);

// ============================================
// ACTIVITIES SHOWCASE — DESTINATION-AWARE
// ============================================
$showcaseDestination   = null;       // destination row when known
$showcaseActivities    = [];         // top activities to display
$showcaseStats         = null;       // aggregated stats
$showcaseHeadingLoc    = '';         // "Bali", "France", "your area"
$showcaseHeadingType   = 'destination'; // 'destination' | 'country' | 'city' | 'search' | 'global'

// Priority order:
// 1. If ?city= is set → get that destination (city row in destinations)
// 2. If ?country= is set → get country
// 3. If ?search= is set → try matching destination by name
// 4. Otherwise → dominant destination among displayed properties
// 5. Otherwise → global top activities

$resolveDestId = 0;

try {
    // 1. Explicit city
    if ($cityId > 0) {
        $row = db()->fetchOne("SELECT id, name, flag_emoji, type FROM destinations WHERE id = ? LIMIT 1", [$cityId]);
        if ($row) {
            $showcaseDestination = $row;
            $resolveDestId = (int)$row['id'];
            $showcaseHeadingLoc = $row['name'];
            $showcaseHeadingType = 'city';
        }
    }

    // 2. Explicit country → pick top activities within that country
    if (!$showcaseDestination && $countryId > 0) {
        $row = db()->fetchOne("SELECT id, name, flag_emoji, type FROM destinations WHERE id = ? LIMIT 1", [$countryId]);
        if ($row) {
            $showcaseDestination = $row;
            $showcaseHeadingLoc = $row['name'];
            $showcaseHeadingType = 'country';
            // Fetch activities linked to any city inside this country
            $showcaseActivities = db()->fetchAll(
                "SELECT a.* FROM activities a
                 JOIN destinations d ON a.destination_id = d.id
                 WHERE (d.id = ? OR d.parent_id = ? OR d.country_name = ?)
                   AND a.is_active = 1
                 ORDER BY a.popularity_score DESC, a.rating DESC
                 LIMIT 12",
                [$countryId, $countryId, $row['name']]
            );
        }
    }

    // 3. Free-text search — try to match a destination
    if (!$showcaseDestination && $search !== '') {
        $like = '%' . $search . '%';
        $row = db()->fetchOne(
            "SELECT id, name, flag_emoji, type FROM destinations
             WHERE name LIKE ? AND is_active = 1
             ORDER BY popularity_score DESC LIMIT 1",
            [$like]
        );
        if ($row) {
            $showcaseDestination = $row;
            $resolveDestId = (int)$row['id'];
            $showcaseHeadingLoc = $row['name'];
            $showcaseHeadingType = 'search';
        }
    }

    // 4. Dominant destination among displayed properties
    if (!$showcaseDestination && !empty($properties)) {
        $destCounts = [];
        foreach ($properties as $p) {
            $d = (int)($p['destination_id'] ?? 0);
            if ($d > 0) $destCounts[$d] = ($destCounts[$d] ?? 0) + 1;
        }
        if (!empty($destCounts)) {
            arsort($destCounts);
            $dominantId = (int)array_key_first($destCounts);
            $row = db()->fetchOne("SELECT id, name, flag_emoji, type FROM destinations WHERE id = ? LIMIT 1", [$dominantId]);
            if ($row) {
                $showcaseDestination = $row;
                $resolveDestId = $dominantId;
                $showcaseHeadingLoc = $row['name'];
                $showcaseHeadingType = 'destination';
            }
        }
    }

    // If we have a resolved destination and no activities yet, fetch them
    if ($resolveDestId > 0 && empty($showcaseActivities)) {
        $showcaseActivities = db()->fetchAll(
            "SELECT * FROM activities
             WHERE destination_id = ? AND is_active = 1
             ORDER BY popularity_score DESC, rating DESC
             LIMIT 12",
            [$resolveDestId]
        );
    }

    // 5. Global fallback
    if (empty($showcaseActivities)) {
        $showcaseActivities = db()->fetchAll(
            "SELECT * FROM activities WHERE is_active = 1
             ORDER BY popularity_score DESC, rating DESC LIMIT 12"
        );
        if (!empty($showcaseActivities) && !$showcaseHeadingLoc) {
            $showcaseHeadingLoc = 'around the world';
            $showcaseHeadingType = 'global';
        }
    }
} catch (Throwable $e) {
    error_log('properties.php activities showcase: ' . $e->getMessage());
}

// Compute stats
if (!empty($showcaseActivities)) {
    $showcaseStats = [
        'total' => count($showcaseActivities),
        'free' => 0,
        'top_rated' => 0,
        'categories' => [],
    ];
    foreach ($showcaseActivities as $a) {
        if ((float)($a['price_from'] ?? 0) <= 0) $showcaseStats['free']++;
        if ((float)($a['rating'] ?? 0) >= 4.5) $showcaseStats['top_rated']++;
        $cat = $a['category'] ?: ($a['type'] ?: 'Other');
        $showcaseStats['categories'][$cat] = ($showcaseStats['categories'][$cat] ?? 0) + 1;
    }
    arsort($showcaseStats['categories']);
}

$headerPath = __DIR__ . '/../includes/header.php';
if (is_file($headerPath)) require_once $headerPath;
?>
<style>
:root {
    --grad: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    --glass: rgba(255,255,255,0.04);
    --border: rgba(255,255,255,0.08);
    --text: #ffffff;
    --text-dim: #a0aec0;
    --text-hi: #a3bffa;
    --green: #00b894;
    --red: #f5576c;
    --orange: #f6ad55;
    --blue: #00d4ff;
    --purple: #b794f4;
    --pink: #f093fb;
    --gold: #ffd700;
    --bg: #0f0c29;
}

.listing-page {
    background: var(--bg);
    background-image:
        radial-gradient(circle at 20% 0%, rgba(102,126,234,0.15), transparent 50%),
        radial-gradient(circle at 80% 100%, rgba(118,75,162,0.12), transparent 50%);
    background-attachment: fixed;
    min-height: 100vh;
    padding: 100px 0 60px;
    color: white;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
    -webkit-font-smoothing: antialiased;
    line-height: 1.55;
}
.listing-page .container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 20px;
}

/* HEADER */
.listing-header { margin-bottom: 26px; }
.listing-header .eyebrow {
    display: inline-flex; align-items: center; gap: 8px;
    padding: 6px 14px; border-radius: 50px;
    background: rgba(102,126,234,0.12);
    border: 1px solid rgba(102,126,234,0.3);
    color: var(--text-hi);
    font-size: 11px; font-weight: 800;
    text-transform: uppercase; letter-spacing: 0.08em;
    margin-bottom: 14px;
}
.listing-header h1 {
    font-size: 34px; font-weight: 800;
    line-height: 1.1; color: white;
    margin: 0 0 8px; letter-spacing: -0.02em;
}
.listing-header h1 .grad {
    background: var(--grad);
    -webkit-background-clip: text; -webkit-text-fill-color: transparent;
}
.listing-header .meta {
    color: var(--text-dim); font-size: 14px;
    display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
}
.listing-header .meta strong {
    color: var(--text-hi); font-weight: 800;
    font-family: 'SF Mono', Monaco, monospace;
}
.listing-header .meta .sep { color: var(--border); }

/* LAYOUT */
.listing-layout {
    display: grid; grid-template-columns: 300px 1fr;
    gap: 26px; align-items: start;
}

/* FILTERS SIDEBAR */
.filters-sidebar {
    background: var(--glass); border: 1px solid var(--border);
    border-radius: 18px; padding: 22px;
    position: sticky; top: 90px;
    max-height: calc(100vh - 110px);
    overflow-y: auto;
    backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
    scrollbar-width: thin;
}
.filters-sidebar::-webkit-scrollbar { width: 6px; }
.filters-sidebar::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 50px; }

.filters-head {
    display: flex; justify-content: space-between; align-items: center;
    margin-bottom: 18px; padding-bottom: 14px;
    border-bottom: 1px solid var(--border);
}
.filters-head h3 {
    font-size: 14px; font-weight: 800; color: white;
    margin: 0; display: flex; align-items: center; gap: 8px;
}
.filters-head h3 i { color: var(--text-hi); font-size: 13px; }
.filters-head .badge {
    background: var(--grad); color: white;
    font-size: 10px; font-weight: 800;
    padding: 3px 9px; border-radius: 50px;
    font-family: 'SF Mono', Monaco, monospace;
}

.filter-section {
    padding-bottom: 18px; margin-bottom: 18px;
    border-bottom: 1px solid var(--border);
}
.filter-section:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; }
.filter-section h4 {
    font-size: 11px; font-weight: 800;
    text-transform: uppercase; letter-spacing: 0.08em;
    color: var(--text-hi); margin: 0 0 12px;
    display: flex; align-items: center; gap: 8px;
}
.filter-section h4 i { font-size: 11px; }

.filter-input {
    width: 100%; padding: 10px 12px;
    background: rgba(255,255,255,0.05);
    border: 1px solid var(--border); border-radius: 10px;
    color: white; font-size: 13.5px; font-family: inherit;
    outline: none; transition: all 0.2s; box-sizing: border-box;
    -webkit-appearance: none;
}
.filter-input::placeholder { color: rgba(160,174,192,0.5); }
.filter-input:focus {
    border-color: #667eea; background: rgba(255,255,255,0.07);
    box-shadow: 0 0 0 3px rgba(102,126,234,0.15);
}
select.filter-input option { background: #1a1a2e; color: white; }

.filter-opt {
    display: flex; align-items: center; gap: 10px;
    padding: 7px 8px; margin: 0 -8px; border-radius: 8px;
    cursor: pointer; font-size: 13.5px; color: #cbd5e0;
    transition: all 0.15s;
}
.filter-opt:hover { background: rgba(255,255,255,0.03); color: white; }
.filter-opt input[type="radio"], .filter-opt input[type="checkbox"] {
    accent-color: #667eea; width: 15px; height: 15px;
    cursor: pointer; flex-shrink: 0;
}
.filter-opt span { flex: 1; }
.filter-opt .count { font-size: 10px; color: var(--text-dim); font-family: 'SF Mono', Monaco, monospace; }

.price-range-inputs { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 6px; }
.amenity-grid { display: flex; flex-direction: column; gap: 2px; }

.btn-apply-filters {
    width: 100%; padding: 13px; background: var(--grad);
    color: white; border: none; border-radius: 12px;
    font-weight: 800; font-size: 13px; cursor: pointer;
    margin-top: 14px; transition: all 0.2s; font-family: inherit;
    display: inline-flex; align-items: center; justify-content: center; gap: 8px;
    box-shadow: 0 6px 18px rgba(102,126,234,0.3);
}
.btn-apply-filters:hover { transform: translateY(-2px); box-shadow: 0 10px 26px rgba(102,126,234,0.42); }
.btn-clear-filters {
    display: block; width: 100%; padding: 11px;
    background: rgba(255,255,255,0.04); color: #cbd5e0;
    border: 1px solid var(--border); border-radius: 12px;
    font-weight: 700; font-size: 12.5px; cursor: pointer;
    margin-top: 8px; text-align: center; text-decoration: none;
    transition: all 0.2s; box-sizing: border-box;
}
.btn-clear-filters:hover {
    background: rgba(255,255,255,0.08); color: white;
    border-color: rgba(102,126,234,0.4);
}

/* MAIN */
.listing-main { min-width: 0; }

.active-chips {
    display: flex; gap: 6px; flex-wrap: wrap;
    margin-bottom: 16px; align-items: center;
}
.active-chips .label {
    font-size: 11px; color: var(--text-dim);
    text-transform: uppercase; font-weight: 800;
    letter-spacing: 0.06em; margin-right: 4px;
}
.chip-active {
    display: inline-flex; align-items: center; gap: 6px;
    padding: 5px 12px; border-radius: 50px;
    background: rgba(102,126,234,0.15);
    border: 1px solid rgba(102,126,234,0.35);
    color: var(--text-hi); font-size: 11.5px; font-weight: 700;
}
.chip-active .x { color: var(--text-dim); cursor: pointer; font-size: 10px; transition: color 0.2s; }
.chip-active .x:hover { color: white; }

.listing-toolbar {
    display: flex; justify-content: space-between;
    align-items: center; gap: 14px;
    margin-bottom: 20px; flex-wrap: wrap;
}
.toolbar-left { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.result-count { font-size: 13.5px; color: var(--text-dim); }
.result-count strong {
    color: var(--text-hi); font-weight: 800;
    font-family: 'SF Mono', Monaco, monospace;
}

.view-toggle {
    display: flex; gap: 0;
    background: rgba(255,255,255,0.04);
    border: 1px solid var(--border); border-radius: 10px;
    overflow: hidden;
}
.view-toggle a {
    padding: 8px 13px; color: var(--text-dim);
    text-decoration: none; font-size: 13px;
    transition: all 0.15s; display: flex; align-items: center;
}
.view-toggle a:hover { color: white; background: rgba(255,255,255,0.04); }
.view-toggle a.active {
    background: var(--grad); color: white;
    box-shadow: 0 2px 10px rgba(102,126,234,0.35);
}

.sort-dropdown select {
    padding: 9px 34px 9px 16px;
    background: rgba(255,255,255,0.05);
    border: 1px solid var(--border); border-radius: 10px;
    color: white; font-size: 13px; font-weight: 700;
    outline: none; cursor: pointer; font-family: inherit;
    appearance: none; -webkit-appearance: none;
    background-image:
        linear-gradient(45deg, transparent 50%, #a3bffa 50%),
        linear-gradient(135deg, #a3bffa 50%, transparent 50%);
    background-position: calc(100% - 18px) 50%, calc(100% - 13px) 50%;
    background-size: 5px 5px, 5px 5px;
    background-repeat: no-repeat;
    transition: all 0.2s;
}
.sort-dropdown select:hover { border-color: rgba(102,126,234,0.4); }
.sort-dropdown select:focus { border-color: #667eea; box-shadow: 0 0 0 3px rgba(102,126,234,0.15); }
.sort-dropdown select option { background: #1a1a2e; color: white; }

/* PROPERTY GRID */
.property-grid-listing {
    display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 18px;
}
.property-grid-listing.list-view { grid-template-columns: 1fr; }

.property-card-listing {
    background: var(--glass); border: 1px solid var(--border);
    border-radius: 18px; overflow: hidden;
    transition: all 0.25s; position: relative;
    display: flex; flex-direction: column;
    backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
}
.property-card-listing:hover {
    transform: translateY(-4px);
    border-color: rgba(102,126,234,0.4);
    box-shadow: 0 20px 50px rgba(0,0,0,0.4);
}

.property-grid-listing.list-view .property-card-listing {
    display: grid; grid-template-columns: 320px 1fr;
    grid-template-rows: auto 1fr auto;
}
.property-grid-listing.list-view .card-image-listing { grid-row: 1 / 4; height: 100%; }
.property-grid-listing.list-view .card-body-listing { padding: 22px 24px 12px; }
.property-grid-listing.list-view .card-footer-listing { padding: 12px 24px 22px; }

.card-image-listing {
    height: 200px; position: relative; overflow: hidden;
    background: #1a1a2e; flex-shrink: 0;
}
.card-image-listing img {
    width: 100%; height: 100%; object-fit: cover;
    transition: transform 0.5s; display: block;
}
.property-card-listing:hover .card-image-listing img { transform: scale(1.05); }
.card-image-listing::after {
    content: ''; position: absolute; inset: 0;
    background: linear-gradient(180deg, transparent 50%, rgba(15,12,41,0.5));
    pointer-events: none;
}

.badge-featured {
    position: absolute; top: 12px; left: 12px; z-index: 2;
    padding: 5px 12px;
    background: linear-gradient(135deg, #f093fb, #f5576c);
    color: white; border-radius: 50px;
    font-size: 10.5px; font-weight: 800;
    text-transform: uppercase; letter-spacing: 0.06em;
    box-shadow: 0 4px 12px rgba(240,147,251,0.4);
    display: inline-flex; align-items: center; gap: 5px;
}
.badge-heart {
    position: absolute; top: 12px; right: 12px; z-index: 2;
    width: 34px; height: 34px; border-radius: 50%;
    background: rgba(0,0,0,0.5);
    border: 1px solid rgba(255,255,255,0.15);
    color: white; display: flex; align-items: center; justify-content: center;
    cursor: pointer; font-size: 13px; transition: all 0.2s;
    backdrop-filter: blur(6px);
}
.badge-heart:hover {
    background: rgba(245,87,108,0.3);
    border-color: rgba(245,87,108,0.5);
    color: var(--red); transform: scale(1.1);
}
.badge-heart.liked { background: var(--red); border-color: var(--red); color: white; }

.card-body-listing {
    padding: 18px 20px 12px; flex: 1;
    display: flex; flex-direction: column;
}
.card-body-listing h3 {
    font-size: 16.5px; font-weight: 800;
    margin: 0 0 6px; line-height: 1.3;
}
.card-body-listing h3 a { color: white; text-decoration: none; transition: color 0.2s; }
.card-body-listing h3 a:hover { color: var(--text-hi); }

.card-location {
    font-size: 12.5px; color: var(--text-dim);
    display: flex; align-items: center; gap: 5px; margin-bottom: 10px;
}
.card-location i { color: var(--text-hi); font-size: 11px; }

.card-rating {
    display: flex; align-items: center; gap: 7px;
    font-size: 12.5px; margin-bottom: 10px;
}
.card-rating .stars { color: var(--gold); font-size: 11px; letter-spacing: 1px; }
.card-rating .count { color: var(--text-dim); font-family: 'SF Mono', Monaco, monospace; }

.card-amenities {
    display: flex; gap: 5px; flex-wrap: wrap;
    margin-top: auto; padding-top: 8px;
}
.amenity-chip {
    display: inline-flex; align-items: center; gap: 5px;
    font-size: 10.5px; font-weight: 700;
    padding: 4px 9px; border-radius: 50px;
    background: rgba(102,126,234,0.1);
    border: 1px solid rgba(102,126,234,0.2);
    color: var(--text-hi);
}
.amenity-chip i { font-size: 9px; }

.card-footer-listing {
    padding: 14px 20px 18px;
    border-top: 1px solid var(--border);
    display: flex; justify-content: space-between; align-items: center;
    gap: 12px; margin-top: auto;
}

.price-listing {
    font-family: 'SF Mono', Monaco, monospace;
    font-size: 19px; font-weight: 800;
    color: var(--text-hi); line-height: 1.1;
}
.price-listing small {
    font-family: inherit; font-size: 11px;
    color: var(--text-dim); font-weight: 500;
}

.btn-view {
    padding: 9px 16px; background: var(--grad);
    color: white; border-radius: 10px;
    text-decoration: none; font-weight: 800;
    font-size: 12px; transition: all 0.2s; white-space: nowrap;
    display: inline-flex; align-items: center; gap: 6px;
    box-shadow: 0 4px 12px rgba(102,126,234,0.3);
}
.btn-view:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 22px rgba(102,126,234,0.45);
    color: white;
}

/* EMPTY STATE */
.empty-state {
    text-align: center; padding: 80px 30px;
    background: var(--glass); border: 1px solid var(--border);
    border-radius: 20px;
    backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
}
.empty-state .ico-wrap {
    width: 80px; height: 80px; border-radius: 50%;
    background: rgba(102,126,234,0.12);
    border: 1px solid rgba(102,126,234,0.3);
    display: flex; align-items: center; justify-content: center;
    font-size: 30px; color: var(--text-hi);
    margin: 0 auto 20px;
}
.empty-state h3 { color: white; font-size: 20px; font-weight: 800; margin: 0 0 8px; }
.empty-state p {
    color: var(--text-dim); font-size: 14px;
    max-width: 420px; margin: 0 auto 24px; line-height: 1.65;
}

/* ============================================
   ACTIVITIES SHOWCASE
   ============================================ */
.activities-showcase {
    margin-top: 70px;
    padding-top: 50px;
    border-top: 1px solid var(--border);
    position: relative;
}
.activities-showcase::before {
    content: '';
    position: absolute; top: -1px; left: 50%; transform: translateX(-50%);
    width: 80px; height: 3px; border-radius: 50px;
    background: linear-gradient(90deg, #f093fb, #667eea, #00d4ff);
}

.act-head {
    text-align: center; margin-bottom: 34px;
}
.act-head .eyebrow {
    display: inline-flex; align-items: center; gap: 8px;
    padding: 6px 14px; border-radius: 50px;
    background: rgba(240,147,251,0.12);
    border: 1px solid rgba(240,147,251,0.3);
    color: var(--pink);
    font-size: 11px; font-weight: 800;
    text-transform: uppercase; letter-spacing: 0.08em;
    margin-bottom: 14px;
}
.act-head h2 {
    font-size: 30px; font-weight: 800;
    line-height: 1.15; margin: 0 0 10px;
    letter-spacing: -0.02em;
}
.act-head h2 .grad {
    background: linear-gradient(135deg, #f093fb, #f5576c, #ffd700);
    -webkit-background-clip: text; -webkit-text-fill-color: transparent;
    background-clip: text;
}
.act-head .sub {
    color: var(--text-dim); font-size: 14.5px;
    max-width: 640px; margin: 0 auto; line-height: 1.6;
}
.act-head .sub strong { color: var(--text-hi); font-weight: 800; }

/* Stats strip */
.act-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 12px;
    margin-bottom: 28px;
    max-width: 900px; margin-left: auto; margin-right: auto;
}
.act-stat {
    background: var(--glass);
    border: 1px solid var(--border);
    border-radius: 14px;
    padding: 16px 18px;
    display: flex; align-items: center; gap: 14px;
    backdrop-filter: blur(8px);
    transition: all 0.2s;
}
.act-stat:hover {
    border-color: rgba(102,126,234,0.3);
    transform: translateY(-2px);
}
.act-stat .ico {
    width: 42px; height: 42px; border-radius: 12px;
    display: flex; align-items: center; justify-content: center;
    font-size: 16px; flex-shrink: 0;
}
.act-stat .ico.purple { background: rgba(183,148,244,0.15); color: var(--purple); }
.act-stat .ico.green  { background: rgba(0,184,148,0.15);  color: var(--green); }
.act-stat .ico.orange { background: rgba(246,173,85,0.15); color: var(--orange); }
.act-stat .ico.blue   { background: rgba(0,212,255,0.15);  color: var(--blue); }
.act-stat .v {
    font-size: 20px; font-weight: 800; color: white;
    font-family: 'SF Mono', Monaco, monospace; line-height: 1.1;
}
.act-stat .l {
    font-size: 10px; color: var(--text-dim);
    text-transform: uppercase; letter-spacing: 0.06em; font-weight: 800;
    margin-top: 2px;
}

/* Category filter chips */
.act-filters {
    display: flex; gap: 8px; flex-wrap: wrap; justify-content: center;
    margin-bottom: 26px;
}
.act-chip {
    padding: 8px 15px; border-radius: 50px;
    background: rgba(255,255,255,0.03);
    border: 1px solid var(--border);
    color: var(--text-dim);
    font-size: 12px; font-weight: 700;
    cursor: pointer; transition: all 0.2s;
    font-family: inherit;
    display: inline-flex; align-items: center; gap: 6px;
}
.act-chip:hover { color: white; background: rgba(255,255,255,0.06); }
.act-chip.active {
    background: rgba(240,147,251,0.18);
    border-color: rgba(240,147,251,0.4);
    color: white;
}
.act-chip .count {
    background: rgba(0,0,0,0.3); padding: 1px 7px; border-radius: 50px;
    font-size: 10px; font-family: monospace;
}

/* Activity grid */
.act-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 18px;
}

.act-card {
    background: rgba(255,255,255,0.03);
    border: 1px solid var(--border);
    border-radius: 16px;
    overflow: hidden;
    transition: all 0.25s;
    display: flex; flex-direction: column;
    position: relative;
    backdrop-filter: blur(10px);
}
.act-card:hover {
    border-color: rgba(240,147,251,0.4);
    transform: translateY(-4px);
    box-shadow: 0 16px 42px rgba(0,0,0,0.35);
    background: rgba(255,255,255,0.05);
}
.act-card.hidden { display: none; }

.act-img {
    width: 100%; height: 170px; overflow: hidden;
    position: relative;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.act-img img {
    width: 100%; height: 100%; object-fit: cover; display: block;
    transition: transform 0.4s;
}
.act-card:hover .act-img img { transform: scale(1.06); }
.act-img .placeholder {
    width: 100%; height: 100%;
    display: flex; align-items: center; justify-content: center;
    font-size: 44px; color: rgba(255,255,255,0.55);
}
.act-img .badge-verified {
    position: absolute; top: 12px; left: 12px;
    background: rgba(0,184,148,0.92);
    backdrop-filter: blur(6px);
    color: white; padding: 4px 11px; border-radius: 50px;
    font-size: 10px; font-weight: 800;
    text-transform: uppercase; letter-spacing: 0.05em;
    display: inline-flex; align-items: center; gap: 4px;
    box-shadow: 0 4px 12px rgba(0,184,148,0.3);
}
.act-img .badge-type {
    position: absolute; bottom: 12px; left: 12px;
    background: rgba(0,0,0,0.75);
    backdrop-filter: blur(8px);
    color: white; padding: 5px 11px; border-radius: 50px;
    font-size: 10px; font-weight: 700;
    text-transform: capitalize; letter-spacing: 0.03em;
    display: inline-flex; align-items: center; gap: 5px;
    border: 1px solid rgba(255,255,255,0.1);
}
.act-img .badge-type i { color: var(--text-hi); font-size: 10px; }

.act-body { padding: 16px 18px 18px; flex: 1; display: flex; flex-direction: column; }
.act-name {
    font-size: 16px; font-weight: 800;
    color: white; margin-bottom: 3px;
    line-height: 1.3;
    display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
    overflow: hidden;
    min-height: 42px;
}
.act-name-local {
    font-size: 11.5px; color: var(--text-dim);
    font-style: italic; margin-bottom: 8px;
}
.act-desc {
    font-size: 12.5px; color: #cbd5e0;
    line-height: 1.55; margin-bottom: 12px;
    display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
    overflow: hidden;
}

.act-meta {
    display: flex; gap: 12px; flex-wrap: wrap;
    font-size: 11.5px; color: var(--text-dim);
    margin-bottom: 12px;
}
.act-meta span { display: inline-flex; align-items: center; gap: 5px; }
.act-meta i { color: var(--text-hi); font-size: 11px; }
.act-rating {
    display: inline-flex; align-items: center; gap: 5px;
    font-size: 12px; font-weight: 700; color: white;
}
.act-rating i { color: var(--gold); font-size: 12px; }
.act-rating .count {
    color: var(--text-dim); font-weight: 500;
    font-size: 11px; font-family: 'SF Mono', Monaco, monospace;
}

.act-tags { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 12px; }
.act-tag {
    padding: 3px 10px; border-radius: 50px;
    background: rgba(102,126,234,0.12);
    border: 1px solid rgba(102,126,234,0.25);
    color: var(--text-hi);
    font-size: 10px; font-weight: 700;
    text-transform: uppercase; letter-spacing: 0.03em;
}
.act-tag.warn  { background: rgba(246,173,85,0.12); border-color: rgba(246,173,85,0.3); color: var(--orange); }
.act-tag.green { background: rgba(0,184,148,0.12);  border-color: rgba(0,184,148,0.3);  color: var(--green); }
.act-tag.blue  { background: rgba(0,212,255,0.12);  border-color: rgba(0,212,255,0.3);  color: var(--blue); }

.act-footer {
    display: flex; justify-content: space-between; align-items: center;
    padding-top: 12px; margin-top: auto;
    border-top: 1px solid rgba(255,255,255,0.05);
}
.act-price {
    font-size: 17px; font-weight: 900;
    color: var(--text-hi);
    font-family: 'SF Mono', Monaco, monospace;
    line-height: 1.1;
}
.act-price small {
    font-size: 10px; font-weight: 500;
    color: var(--text-dim); font-family: inherit;
    margin-left: 3px;
}
.act-price .free { color: var(--green); }
.act-cta {
    font-size: 12px; font-weight: 700;
    color: var(--text-hi); text-decoration: none;
    display: inline-flex; align-items: center; gap: 5px;
    transition: color 0.2s;
}
.act-cta:hover { color: white; }

/* Showcase footer CTA */
.act-footer-cta {
    text-align: center; margin-top: 34px;
}
.act-footer-cta a {
    display: inline-flex; align-items: center; gap: 8px;
    padding: 13px 26px; border-radius: 50px;
    background: linear-gradient(135deg, rgba(240,147,251,0.15), rgba(102,126,234,0.15));
    border: 1px solid rgba(240,147,251,0.35);
    color: white; font-size: 13.5px; font-weight: 800;
    text-decoration: none; transition: all 0.2s;
    letter-spacing: 0.01em;
}
.act-footer-cta a:hover {
    background: linear-gradient(135deg, rgba(240,147,251,0.25), rgba(102,126,234,0.25));
    transform: translateY(-2px);
    box-shadow: 0 10px 26px rgba(240,147,251,0.3);
}

/* PAGINATION */
.pagination-listing {
    display: flex; justify-content: center; gap: 8px;
    margin-top: 40px; flex-wrap: wrap;
}
.pagination-listing a, .pagination-listing span {
    padding: 9px 16px;
    background: rgba(255,255,255,0.05);
    border: 1px solid var(--border); border-radius: 10px;
    color: #cbd5e0; text-decoration: none;
    font-size: 13px; font-weight: 700;
    transition: all 0.2s; min-width: 40px;
    text-align: center; box-sizing: border-box;
}
.pagination-listing a:hover {
    background: rgba(255,255,255,0.1); color: white;
    border-color: rgba(102,126,234,0.4);
}
.pagination-listing .active {
    background: var(--grad); color: white;
    border-color: transparent;
    box-shadow: 0 6px 18px rgba(102,126,234,0.35);
}

/* MOBILE DRAWER */
.mobile-filters-toggle {
    display: none; padding: 12px 20px;
    background: var(--grad); color: white;
    border: none; border-radius: 12px;
    font-weight: 800; font-size: 13px;
    cursor: pointer; margin-bottom: 16px; width: 100%;
    box-shadow: 0 6px 18px rgba(102,126,234,0.3);
    font-family: inherit; align-items: center;
    justify-content: center; gap: 8px;
}
.mobile-filters-toggle .badge {
    background: rgba(0,0,0,0.3); border-radius: 50px;
    padding: 2px 8px; font-size: 10px;
    font-family: 'SF Mono', Monaco, monospace;
}
.filters-backdrop {
    display: none; position: fixed; inset: 0;
    background: rgba(0,0,0,0.7);
    backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px);
    z-index: 999;
}
.filters-backdrop.show { display: block; }

@media (max-width: 968px) {
    .listing-layout { grid-template-columns: 1fr; }
    .filters-sidebar {
        position: fixed; top: 0; left: -320px;
        width: 300px; height: 100vh; max-height: 100vh;
        border-radius: 0 20px 20px 0;
        z-index: 1000; transition: left 0.3s ease;
        background: #0f0c29;
        box-shadow: 20px 0 60px rgba(0,0,0,0.5);
        padding-top: 78px;
    }
    .filters-sidebar.active { left: 0; }
    .mobile-filters-toggle { display: inline-flex; }
    .property-grid-listing.list-view .property-card-listing { grid-template-columns: 1fr; }
    .property-grid-listing.list-view .card-image-listing { grid-row: auto; height: 200px; }
    .act-grid { grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); }
}

@media (max-width: 640px) {
    .listing-page { padding: 90px 0 40px; }
    .listing-header h1 { font-size: 26px; }
    .property-grid-listing { grid-template-columns: 1fr; }
    .property-card-listing .card-image-listing { height: 180px; }
    .act-head h2 { font-size: 22px; }
    .act-grid { grid-template-columns: 1fr; }
}

@media (prefers-reduced-motion: reduce) {
    *, *::before, *::after {
        animation-duration: 0.01ms !important;
        transition-duration: 0.01ms !important;
    }
    .property-card-listing:hover { transform: none; }
    .property-card-listing:hover .card-image-listing img { transform: none; }
    .btn-view:hover { transform: none; }
    .act-card:hover { transform: none; }
}
</style>

<div class="listing-page">
    <div class="container">

        <!-- HEADER -->
        <header class="listing-header">
            <div class="eyebrow">
                <i class="fas fa-compass"></i>
                <?= $categoryId && $catName ? ppxSafe($catName) : 'Browse Properties' ?>
            </div>
            <h1>
                <?php if (!empty($search)): ?>
                    Results for "<span class="grad"><?= ppxSafe($search) ?></span>"
                <?php elseif ($categoryId && $catName): ?>
                    <span class="grad"><?= ppxSafe($catName) ?></span>
                <?php else: ?>
                    Explore <span class="grad">every stay</span>
                <?php endif; ?>
            </h1>
            <div class="meta">
                <span><strong><?= number_format($totalResults) ?></strong> <?= $totalResults === 1 ? 'property' : 'properties' ?> available</span>
                <?php if ($checkIn && $checkOut): ?>
                    <span class="sep">·</span>
                    <span><i class="fas fa-calendar"></i> <?= ppxSafe(date('M j', strtotime($checkIn))) ?> – <?= ppxSafe(date('M j', strtotime($checkOut))) ?></span>
                <?php endif; ?>
                <?php if ($guests > 0): ?>
                    <span class="sep">·</span>
                    <span><i class="fas fa-user-friends"></i> <?= (int)$guests ?> guest<?= $guests === 1 ? '' : 's' ?></span>
                <?php endif; ?>
            </div>
        </header>

        <!-- MOBILE FILTER TOGGLE -->
        <button type="button" class="mobile-filters-toggle" onclick="ppxToggleFilters()">
            <i class="fas fa-filter"></i>
            Filters
            <?php if ($activeFilterCount > 0): ?>
                <span class="badge"><?= (int)$activeFilterCount ?></span>
            <?php endif; ?>
        </button>

        <div class="listing-layout">

            <!-- FILTERS SIDEBAR -->
            <aside class="filters-sidebar" id="filtersSidebar">
                <div class="filters-head">
                    <h3><i class="fas fa-sliders-h"></i> Filters</h3>
                    <?php if ($activeFilterCount > 0): ?>
                        <span class="badge"><?= (int)$activeFilterCount ?> active</span>
                    <?php endif; ?>
                </div>

                <form method="GET" id="filterForm">
                    <input type="hidden" name="page" value="properties">
                    <input type="hidden" name="view" value="<?= ppxSafe($viewMode) ?>">

                    <div class="filter-section">
                        <h4><i class="fas fa-search"></i> Keyword</h4>
                        <input type="text"
                               name="search"
                               class="filter-input"
                               placeholder="Name, city, or amenity…"
                               value="<?= ppxSafe($search) ?>">
                    </div>

                    <?php if (!empty($categories)): ?>
                        <div class="filter-section">
                            <h4><i class="fas fa-tag"></i> Category</h4>
                            <label class="filter-opt">
                                <input type="radio" name="category" value="0" <?= $categoryId == 0 ? 'checked' : '' ?>>
                                <span>All Categories</span>
                            </label>
                            <?php foreach ($categories as $cat): ?>
                                <label class="filter-opt">
                                    <input type="radio" name="category" value="<?= (int)$cat['id'] ?>" <?= $categoryId == $cat['id'] ? 'checked' : '' ?>>
                                    <span><?= ppxSafe($cat['name']) ?></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($countries)): ?>
                        <div class="filter-section">
                            <h4><i class="fas fa-globe"></i> Location</h4>
                            <select name="country" class="filter-input" onchange="this.form.submit()">
                                <option value="0">All Countries</option>
                                <?php foreach ($countries as $co): ?>
                                    <option value="<?= (int)$co['id'] ?>" <?= $countryId == $co['id'] ? 'selected' : '' ?>>
                                        <?= ppxSafe($co['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <?php if (!empty($cities)): ?>
                                <select name="city" class="filter-input" style="margin-top: 8px;">
                                    <option value="0">All Cities</option>
                                    <?php foreach ($cities as $ci): ?>
                                        <option value="<?= (int)$ci['id'] ?>" <?= $cityId == $ci['id'] ? 'selected' : '' ?>>
                                            <?= ppxSafe($ci['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>

                    <div class="filter-section">
                        <h4><i class="fas fa-dollar-sign"></i> Price per Night</h4>
                        <div class="price-range-inputs">
                            <input type="number" name="min_price" class="filter-input" placeholder="Min" min="0" value="<?= $minPrice > 0 ? (int)$minPrice : '' ?>">
                            <input type="number" name="max_price" class="filter-input" placeholder="Max" min="0" value="<?= $maxPrice < 5000 ? (int)$maxPrice : '' ?>">
                        </div>
                    </div>

                    <div class="filter-section">
                        <h4><i class="fas fa-star"></i> Star Rating</h4>
                        <?php for ($i = 5; $i >= 3; $i--): ?>
                            <label class="filter-opt">
                                <input type="radio" name="star_rating" value="<?= $i ?>" <?= $starRating == $i ? 'checked' : '' ?>>
                                <span><?= $i ?>★ &amp; up</span>
                            </label>
                        <?php endfor; ?>
                        <label class="filter-opt">
                            <input type="radio" name="star_rating" value="0" <?= $starRating == 0 ? 'checked' : '' ?>>
                            <span>Any rating</span>
                        </label>
                    </div>

                    <div class="filter-section">
                        <h4><i class="fas fa-concierge-bell"></i> Amenities</h4>
                        <div class="amenity-grid">
                            <?php foreach (array_slice($allAmenities, 0, 10) as $amenity): ?>
                                <label class="filter-opt">
                                    <input type="checkbox" name="amenities[]" value="<?= ppxSafe($amenity) ?>" <?= in_array($amenity, $amenitiesFilter, true) ? 'checked' : '' ?>>
                                    <i class="fas <?= ppxSafe(getAmenityIconSafe($amenity)) ?>" style="color: var(--text-hi); font-size: 11px; width: 14px;"></i>
                                    <span><?= ppxSafe(ucfirst(str_replace('_', ' ', $amenity))) ?></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div class="filter-section">
                        <h4><i class="fas fa-bolt"></i> Booking</h4>
                        <label class="filter-opt">
                            <input type="checkbox" name="instant_book" value="1" <?= $instantBook ? 'checked' : '' ?>>
                            <span>Instant Book only</span>
                        </label>
                    </div>

                    <button type="submit" class="btn-apply-filters">
                        <i class="fas fa-check"></i> Apply Filters
                    </button>
                    <a href="/?page=properties" class="btn-clear-filters">
                        <i class="fas fa-times"></i> Clear All
                    </a>
                </form>
            </aside>

            <div class="filters-backdrop" id="filtersBackdrop" onclick="ppxToggleFilters()"></div>

            <!-- MAIN -->
            <main class="listing-main">

                <?php if ($activeFilterCount > 0): ?>
                    <div class="active-chips">
                        <span class="label">Active:</span>
                        <?php if (!empty($search)): ?>
                            <span class="chip-active">
                                "<?= ppxSafe(mb_substr($search, 0, 20)) ?>"
                                <a href="?<?= ppxSafe(http_build_query(array_merge($_GET, ['search' => '']))) ?>" class="x"><i class="fas fa-times"></i></a>
                            </span>
                        <?php endif; ?>
                        <?php if ($categoryId && $catName): ?>
                            <span class="chip-active">
                                <?= ppxSafe($catName) ?>
                                <a href="?<?= ppxSafe(http_build_query(array_merge($_GET, ['category' => 0]))) ?>" class="x"><i class="fas fa-times"></i></a>
                            </span>
                        <?php endif; ?>
                        <?php if ($starRating): ?>
                            <span class="chip-active">
                                <?= (int)$starRating ?>★+
                                <a href="?<?= ppxSafe(http_build_query(array_merge($_GET, ['star_rating' => 0]))) ?>" class="x"><i class="fas fa-times"></i></a>
                            </span>
                        <?php endif; ?>
                        <?php if ($instantBook): ?>
                            <span class="chip-active">
                                Instant Book
                                <a href="?<?= ppxSafe(http_build_query(array_merge($_GET, ['instant_book' => null]))) ?>" class="x"><i class="fas fa-times"></i></a>
                            </span>
                        <?php endif; ?>
                        <?php foreach ($amenitiesFilter as $am): ?>
                            <span class="chip-active">
                                <?= ppxSafe(ucfirst(str_replace('_', ' ', $am))) ?>
                                <a href="?<?= ppxSafe(http_build_query(array_merge($_GET, ['amenities' => array_values(array_diff($amenitiesFilter, [$am]))]))) ?>" class="x"><i class="fas fa-times"></i></a>
                            </span>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <div class="listing-toolbar">
                    <div class="toolbar-left">
                        <span class="result-count">
                            <strong><?= number_format($totalResults) ?></strong> <?= $totalResults === 1 ? 'result' : 'results' ?>
                        </span>
                        <div class="view-toggle">
                            <a href="?<?= ppxSafe(http_build_query(array_merge($_GET, ['view' => 'grid']))) ?>" class="<?= $viewMode == 'grid' ? 'active' : '' ?>" title="Grid view">
                                <i class="fas fa-th"></i>
                            </a>
                            <a href="?<?= ppxSafe(http_build_query(array_merge($_GET, ['view' => 'list']))) ?>" class="<?= $viewMode == 'list' ? 'active' : '' ?>" title="List view">
                                <i class="fas fa-list"></i>
                            </a>
                        </div>
                    </div>

                    <div class="sort-dropdown">
                        <select onchange="window.location.href=this.value">
                            <?php
                            $sorts = [
                                'relevance'  => 'Most relevant',
                                'price_asc'  => 'Price: Low → High',
                                'price_desc' => 'Price: High → Low',
                                'rating'     => 'Top rated',
                                'newest'     => 'Newest first',
                            ];
                            foreach ($sorts as $key => $label):
                                $url = '?' . http_build_query(array_merge($_GET, ['sort' => $key]));
                            ?>
                                <option value="<?= ppxSafe($url) ?>" <?= $sort == $key ? 'selected' : '' ?>>
                                    <?= ppxSafe($label) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <?php if (!empty($properties)): ?>

                    <div class="property-grid-listing <?= $viewMode == 'list' ? 'list-view' : '' ?>">
                        <?php foreach ($properties as $p):
                            $img = getPropertyImageUrl($p);
                            $rating = function_exists('getAverageRating') ? getAverageRating($p['id']) : ['average' => 0, 'total' => 0];
                            $avgRating = (float)($rating['average'] ?? 0);
                            $totalReviews = (int)($rating['total'] ?? 0);
                            $propName = (string)($p['name'] ?? 'Property');
                            $propSlug = (string)($p['slug'] ?? '');
                            $city = trim((string)($p['city_name'] ?? ''));
                            $country = trim((string)($p['country_name'] ?? ''));
                            $location = $city . ($city && $country ? ', ' : '') . $country;
                            $price = (float)($p['min_price_per_night'] ?? 0);
                            $isFeatured = !empty($p['is_featured']);

                            $propAmenities = [];
                            $amenRaw = $p['amenities'] ?? [];
                            if (is_string($amenRaw)) {
                                $decoded = json_decode($amenRaw, true);
                                if (is_array($decoded)) $amenRaw = $decoded;
                            }
                            if (is_array($amenRaw)) {
                                foreach (array_slice($amenRaw, 0, 3) as $am) {
                                    if (is_string($am) && $am !== '') $propAmenities[] = $am;
                                }
                            }
                        ?>
                            <article class="property-card-listing" data-property-id="<?= (int)$p['id'] ?>">
                                <div class="card-image-listing">
                                    <a href="/?page=property&slug=<?= urlencode($propSlug) ?>" style="display:block; width:100%; height:100%;">
                                        <img src="<?= ppxSafe($img) ?>"
                                             alt="<?= ppxSafe($propName) ?>"
                                             loading="lazy"
                                             onerror="this.src='https://images.unsplash.com/photo-1566073771259-6a8506099945?w=800&h=600&fit=crop'">
                                    </a>
                                    <?php if ($isFeatured): ?>
                                        <span class="badge-featured"><i class="fas fa-star"></i> Featured</span>
                                    <?php endif; ?>
                                    <button type="button" class="badge-heart" onclick="ppxToggleWishlist(event, <?= (int)$p['id'] ?>)" aria-label="Save to wishlist">
                                        <i class="far fa-heart"></i>
                                    </button>
                                </div>

                                <div class="card-body-listing">
                                    <h3>
                                        <a href="/?page=property&slug=<?= urlencode($propSlug) ?>">
                                            <?= ppxSafe($propName) ?>
                                        </a>
                                    </h3>
                                    <?php if ($location !== ''): ?>
                                        <div class="card-location">
                                            <i class="fas fa-map-marker-alt"></i>
                                            <?= ppxSafe($location) ?>
                                        </div>
                                    <?php endif; ?>
                                    <?php if ($avgRating > 0 || $totalReviews > 0): ?>
                                        <div class="card-rating">
                                            <span class="stars"><?= safeStarRating($avgRating) ?></span>
                                            <?php if ($avgRating > 0): ?>
                                                <span style="color: white; font-weight: 800; font-size: 12.5px;"><?= number_format($avgRating, 1) ?></span>
                                            <?php endif; ?>
                                            <?php if ($totalReviews > 0): ?>
                                                <span class="count">(<?= number_format($totalReviews) ?>)</span>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (!empty($propAmenities)): ?>
                                        <div class="card-amenities">
                                            <?php foreach ($propAmenities as $am): ?>
                                                <span class="amenity-chip">
                                                    <i class="fas <?= ppxSafe(getAmenityIconSafe($am)) ?>"></i>
                                                    <?= ppxSafe(ucfirst(str_replace('_', ' ', $am))) ?>
                                                </span>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <div class="card-footer-listing">
                                    <div class="price-listing">
                                        <?= ppxSafe(formatCurrency($price)) ?>
                                        <small>/ night</small>
                                    </div>
                                    <a href="/?page=property&slug=<?= urlencode($propSlug) ?>" class="btn-view">
                                        View <i class="fas fa-arrow-right"></i>
                                    </a>
                                </div>
                            </article>
                        <?php endforeach; ?>
                    </div>

                <?php else: ?>

                    <div class="empty-state">
                        <div class="ico-wrap"><i class="fas fa-search"></i></div>
                        <h3>No properties found</h3>
                        <p>Try adjusting your filters or broadening your search. We add new properties every week.</p>
                        <a href="/?page=properties" class="btn-view" style="padding: 12px 24px; font-size: 13px;">
                            <i class="fas fa-rotate-left"></i> Clear all filters
                        </a>
                    </div>

                <?php endif; ?>

            </main>
        </div>

        <!-- ============================================
             ACTIVITIES SHOWCASE
             ============================================ -->
        <?php if (!empty($showcaseActivities)): ?>
            <section class="activities-showcase" id="activitiesShowcase">
                <div class="act-head">
                    <div class="eyebrow">
                        <i class="fas fa-map-marked-alt"></i> Local Experiences
                    </div>
                    <h2>
                        Things to <span class="grad">do</span>
                        <?php if ($showcaseHeadingLoc && $showcaseHeadingLoc !== 'around the world'): ?>
                            in <?= ppxSafe($showcaseHeadingLoc) ?>
                        <?php elseif ($showcaseHeadingLoc === 'around the world'): ?>
                            around the world
                        <?php endif; ?>
                    </h2>
                    <p class="sub">
                        <?php if ($showcaseHeadingType === 'city'): ?>
                            Curated attractions, dining, and experiences in
                            <strong><?= ppxSafe($showcaseHeadingLoc) ?></strong>
                            — picked from our global catalogue.
                        <?php elseif ($showcaseHeadingType === 'country'): ?>
                            Top-rated experiences across
                            <strong><?= ppxSafe($showcaseHeadingLoc) ?></strong>
                            — museums, landmarks, dining, and more.
                        <?php elseif ($showcaseHeadingType === 'search'): ?>
                            Discover what <strong><?= ppxSafe($showcaseHeadingLoc) ?></strong> has to offer —
                            activities matching your search.
                        <?php elseif ($showcaseHeadingType === 'destination'): ?>
                            Explore the best of <strong><?= ppxSafe($showcaseHeadingLoc) ?></strong> —
                            hand-picked experiences and attractions.
                        <?php else: ?>
                            A taste of the world's best experiences — refresh your filters to explore a specific destination.
                        <?php endif; ?>
                    </p>
                </div>

                <?php if ($showcaseStats): ?>
                    <div class="act-stats">
                        <div class="act-stat">
                            <div class="ico purple"><i class="fas fa-map-pin"></i></div>
                            <div>
                                <div class="v"><?= number_format($showcaseStats['total']) ?></div>
                                <div class="l">Experiences</div>
                            </div>
                        </div>
                        <div class="act-stat">
                            <div class="ico green"><i class="fas fa-tag"></i></div>
                            <div>
                                <div class="v"><?= number_format($showcaseStats['free']) ?></div>
                                <div class="l">Free to Visit</div>
                            </div>
                        </div>
                        <div class="act-stat">
                            <div class="ico orange"><i class="fas fa-star"></i></div>
                            <div>
                                <div class="v"><?= number_format($showcaseStats['top_rated']) ?></div>
                                <div class="l">Top Rated (4.5+)</div>
                            </div>
                        </div>
                        <div class="act-stat">
                            <div class="ico blue"><i class="fas fa-list"></i></div>
                            <div>
                                <div class="v"><?= count($showcaseStats['categories']) ?></div>
                                <div class="l">Categories</div>
                            </div>
                        </div>
                    </div>

                    <?php if (count($showcaseStats['categories']) > 1): ?>
                        <div class="act-filters" id="actFilters">
                            <button type="button" class="act-chip active" data-cat="all">
                                <i class="fas fa-th"></i> All <span class="count"><?= $showcaseStats['total'] ?></span>
                            </button>
                            <?php foreach ($showcaseStats['categories'] as $cat => $count): ?>
                                <button type="button" class="act-chip" data-cat="<?= ppxSafe($cat) ?>">
                                    <i class="fas <?= ppxActivityIcon('', $cat) ?>"></i>
                                    <?= ppxSafe(ucfirst(str_replace('_', ' ', $cat))) ?>
                                    <span class="count"><?= $count ?></span>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>

                <div class="act-grid" id="actGrid">
                    <?php foreach ($showcaseActivities as $a):
                        $aImg = '';
                        if (!empty($a['image'])) {
                            $aImg = strpos($a['image'], 'http') === 0
                                ? $a['image']
                                : '/uploads/' . ltrim($a['image'], '/');
                        }
                        $aTags = [];
                        if (!empty($a['tags'])) {
                            $decoded = json_decode($a['tags'], true);
                            if (is_array($decoded)) $aTags = $decoded;
                            else $aTags = array_filter(array_map('trim', explode(',', $a['tags'])));
                        }
                        $priceFormatted = ppxFormatActivityPrice($a['price_from'] ?? 0, $a['price_currency'] ?? 'USD');
                        $isFree = (float)($a['price_from'] ?? 0) <= 0;
                        $cat = $a['category'] ?: ($a['type'] ?: 'Other');

                        $badges = [];
                        if (!empty($a['booking_required'])) $badges[] = ['Book ahead', 'warn'];
                        if (!empty($a['family_friendly'])) $badges[] = ['Family', 'green'];
                        if (!empty($a['indoor']))          $badges[] = ['Indoor', 'blue'];
                        if (!empty($a['accessibility']))   $badges[] = ['Accessible', 'green'];
                        $allBadges = array_merge($badges, array_map(function($t) { return [ucfirst($t), '']; }, array_slice($aTags, 0, 2)));
                    ?>
                        <article class="act-card" data-cat="<?= ppxSafe($cat) ?>">
                            <div class="act-img">
                                <?php if ($aImg): ?>
                                    <img src="<?= ppxSafe($aImg) ?>" alt="<?= ppxSafe($a['name']) ?>" loading="lazy"
                                         onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                    <div class="placeholder" style="display:none;">
                                        <i class="fas <?= ppxActivityIcon($a['type'] ?? '', $a['category'] ?? '', $a['subcategory'] ?? '') ?>"></i>
                                    </div>
                                <?php else: ?>
                                    <div class="placeholder">
                                        <i class="fas <?= ppxActivityIcon($a['type'] ?? '', $a['category'] ?? '', $a['subcategory'] ?? '') ?>"></i>
                                    </div>
                                <?php endif; ?>

                                <?php if (!empty($a['is_verified'])): ?>
                                    <span class="badge-verified"><i class="fas fa-check"></i> Verified</span>
                                <?php endif; ?>

                                <span class="badge-type">
                                    <i class="fas <?= ppxActivityIcon($a['type'] ?? '', $a['category'] ?? '', $a['subcategory'] ?? '') ?>"></i>
                                    <?= ppxSafe($a['type'] ?: ($a['category'] ?: 'Attraction')) ?>
                                </span>
                            </div>

                            <div class="act-body">
                                <h3 class="act-name"><?= ppxSafe($a['name']) ?></h3>
                                <?php if (!empty($a['name_local']) && $a['name_local'] !== $a['name']): ?>
                                    <div class="act-name-local"><?= ppxSafe($a['name_local']) ?></div>
                                <?php endif; ?>

                                <?php if (!empty($a['description'])): ?>
                                    <div class="act-desc"><?= ppxSafe($a['description']) ?></div>
                                <?php endif; ?>

                                <div class="act-meta">
                                    <?php if (!empty($a['rating'])): ?>
                                        <span class="act-rating">
                                            <i class="fas fa-star"></i> <?= number_format((float)$a['rating'], 1) ?>
                                            <?php if ((int)($a['review_count'] ?? 0) > 0): ?>
                                                <span class="count">(<?= number_format((int)$a['review_count']) ?>)</span>
                                            <?php endif; ?>
                                        </span>
                                    <?php endif; ?>
                                    <?php if (!empty($a['duration_minutes'])): ?>
                                        <span><i class="fas fa-clock"></i> <?= ppxFormatActivityDuration($a['duration_minutes']) ?></span>
                                    <?php endif; ?>
                                    <?php if (!empty($a['opening_hours'])): ?>
                                        <span><i class="fas fa-door-open"></i> <?= ppxSafe(mb_substr($a['opening_hours'], 0, 22)) ?></span>
                                    <?php endif; ?>
                                    <?php if (!empty($a['best_time'])): ?>
                                        <span><i class="fas fa-sun"></i> Best: <?= ppxSafe($a['best_time']) ?></span>
                                    <?php endif; ?>
                                </div>

                                <?php if (!empty($allBadges)): ?>
                                    <div class="act-tags">
                                        <?php foreach ($allBadges as $b): ?>
                                            <span class="act-tag <?= ppxSafe($b[1]) ?>"><?= ppxSafe($b[0]) ?></span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>

                                <div class="act-footer">
                                    <div class="act-price">
                                        <?php if ($isFree): ?>
                                            <span class="free">Free</span>
                                        <?php else: ?>
                                            <?= ppxSafe($priceFormatted) ?>
                                            <small>from</small>
                                        <?php endif; ?>
                                    </div>
                                    <?php if (!empty($a['slug'])): ?>
                                        <a href="/?page=activity&slug=<?= urlencode($a['slug']) ?>" class="act-cta">
                                            Details <i class="fas fa-arrow-right"></i>
                                        </a>
                                    <?php elseif (!empty($a['website'])): ?>
                                        <a href="<?= ppxSafe($a['website']) ?>" target="_blank" rel="noopener" class="act-cta">
                                            Website <i class="fas fa-external-link-alt"></i>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>

                <div class="act-footer-cta">
                    <?php if ($resolveDestId > 0): ?>
                        <a href="/?page=activities&destination_id=<?= (int)$resolveDestId ?>">
                            <i class="fas fa-compass"></i>
                            Explore all activities<?= $showcaseHeadingLoc ? ' in ' . ppxSafe($showcaseHeadingLoc) : '' ?>
                        </a>
                    <?php else: ?>
                        <a href="/?page=activities">
                            <i class="fas fa-compass"></i>
                            Browse all activities
                        </a>
                    <?php endif; ?>
                </div>
            </section>
        <?php endif; ?>

    </div>
</div>

<script>
(function () {
    'use strict';

    // ============================================
    // MOBILE FILTER DRAWER
    // ============================================
    window.ppxToggleFilters = function () {
        var sidebar = document.getElementById('filtersSidebar');
        var backdrop = document.getElementById('filtersBackdrop');
        if (!sidebar) return;
        sidebar.classList.toggle('active');
        if (backdrop) backdrop.classList.toggle('show');
        document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
    };

    // ============================================
    // WISHLIST TOGGLE (preserved)
    // ============================================
    window.ppxToggleWishlist = function (evt, propertyId) {
        evt.preventDefault();
        evt.stopPropagation();

        var btn = evt.currentTarget;
        var icon = btn.querySelector('i');
        var wasLiked = btn.classList.contains('liked');

        btn.classList.toggle('liked', !wasLiked);
        if (icon) {
            icon.classList.toggle('fas', !wasLiked);
            icon.classList.toggle('far', wasLiked);
        }

        var endpoints = ['/?page=api-wishlist', '/?page=api-favorites'];
        var body = new URLSearchParams({
            action: wasLiked ? 'remove' : 'add',
            property_id: propertyId
        });

        function tryPost(i) {
            if (i >= endpoints.length) return;
            fetch(endpoints[i], {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: body.toString(),
                credentials: 'same-origin'
            })
            .then(function (r) {
                if (!r.ok) throw new Error('not ok');
                return r.json().catch(function () { return {}; });
            })
            .catch(function () { tryPost(i + 1); });
        }
        tryPost(0);
    };

    // ============================================
    // ACTIVITY CATEGORY FILTER
    // ============================================
    (function () {
        var filters = document.getElementById('actFilters');
        var grid = document.getElementById('actGrid');
        if (!filters || !grid) return;
        filters.addEventListener('click', function (e) {
            var chip = e.target.closest('.act-chip');
            if (!chip) return;
            filters.querySelectorAll('.act-chip').forEach(function (c) { c.classList.remove('active'); });
            chip.classList.add('active');
            var cat = chip.dataset.cat;
            grid.querySelectorAll('.act-card').forEach(function (card) {
                if (cat === 'all' || card.dataset.cat === cat) card.classList.remove('hidden');
                else card.classList.add('hidden');
            });
        });
    })();

    // ============================================
    // ESC closes mobile drawer
    // ============================================
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') {
            var sidebar = document.getElementById('filtersSidebar');
            if (sidebar && sidebar.classList.contains('active')) {
                window.ppxToggleFilters();
            }
        }
    });
})();
</script>

<?php
$footerPath = __DIR__ . '/../includes/footer.php';
if (is_file($footerPath)) require_once $footerPath;
?>