<?php

    // error_reporting(0);

    $root = $_GET["root"] ?? null;
    $roots = isset($_GET["roots"]) ? array_filter(explode("/", rtrim($_GET["roots"], "/"))) : [];
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 1]]);
    $status = filter_input(INPUT_GET, 'status', FILTER_VALIDATE_INT, ['options' => ['default' => 1]]);

    $REDIRECT_co = isset($_REDIRECT["REDIRECT_co"]) && !empty($_REDIRECT["REDIRECT_co"]) ? $_REDIRECT["REDIRECT_co"] : "US";
    $REDIRECT_ln = isset($_REDIRECT["REDIRECT_ln"]) && !empty($_REDIRECT["REDIRECT_ln"]) ? $_REDIRECT["REDIRECT_ln"] : "en";

    $statusQuery = $status > 2 || $status < 0 ? "status:1" : ($status == 2 ? "" : "status:{$status}");
    $statusText = $status > 2 || $status < 0 ? "online" : ($status == 2 ? "online and offline" : ($status == 1 ? "online" : "offline"));
    $statusTextLive = $status > 2 || $status < 0 ? "live" : ($status == 2 ? "live and offline" : ($status == 1 ? "live" : "offline"));
    $statusUrlParameter = "?" . ($status == 1 ? "" : "status={$status}");
    

    if (empty($root) || count($roots) > 3) {
        exit;
    }

    /**
     * Calculates the great-circle distance between two points using the Haversine formula.
     */
    function calculateDistance($lat1, $lon1, $lat2, $lon2, $unit = 'K') {
        if (($lat1 == $lat2) && ($lon1 == $lon2)) {
            return 0;
        }
    
        $earthRadius = 6371; 
        
        $latDelta = deg2rad($lat2 - $lat1);
        $lonDelta = deg2rad($lon2 - $lon1);
        
        $a = sin($latDelta / 2) * sin($latDelta / 2) +
             cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
             sin($lonDelta / 2) * sin($lonDelta / 2);
             
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
        $distanceInKm = $earthRadius * $c;
    
        switch (strtoupper($unit)) {
            case 'M': return $distanceInKm * 0.621371;
            case 'N': return $distanceInKm * 0.539957;
            case 'K':
            default:  return $distanceInKm;
        }
    }

    function paginate(array $items, int $perPage = 10, int $page = 1): array {
        $total = count($items);
        $lastPage = (int) max(1, ceil($total / $perPage));
        $page = max(1, min($page, $lastPage)); // Clamp page between 1 and last page

        $offset = ($page - 1) * $perPage;
        $data = array_slice($items, $offset, $perPage);
        $totalOnPage = count($data);

        // Correct from and to calculations
        $fromResult = $total > 0 ? $offset + 1 : 0;
        $toResult = $offset + $totalOnPage;

        return [
            'first_page'   => 1,
            'current_page' => $page,
            'last_page'    => $lastPage,
            'per_page'     => $perPage,
            'on_page'      => $totalOnPage,
            'from_result'  => $fromResult,
            'to_result'    => $toResult,
            'total'        => $total,
            'data'         => $data,
        ];
    }

    $baseDir = __DIR__ . "/../../..";

    require_once $baseDir . '/v/home/scripts/seo.php';
    require_once $baseDir . '/v/home/scripts/csvActions.php';
    require_once $baseDir . '/v/home/scripts/CSVDatabase.php';
    
    $sourceDir = $baseDir . '/v/home/databases/central/assets/devices/cameras/accessible';

    $db = new CSVDatabase($sourceDir, $idName = "internal_id");

    $resultsPerPage = 15;

    $zoom = 0;

    $htmlPageSuggestedViews = "";
    $htmlPageCategoriesList = "";

    $htmlPageFAQs = "";
    $htmlPageBreadcrumbs = "";
    $htmlPageStatBarList = "";
    $htmlPageFrequencyList = "";
    $htmlPageBreakDownList = "";
    $htmlPageHighlightedViews = "";
    $htmlPageNotableViews = "";
    $htmlPageDirectoryGrid = "";
    
    $textPageTitle = "";
    $textPageSubheading = "";
    $textPageMetaTitle = "";
    $textPageMetaDescription = "";
    
    $htmlPageStatBarListCount = 0;
    $mostFrequentValues = [];

    // 1. Extract locale from the current request efficiently
    $isSecure = false;
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
        $isSecure = true;
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
        $isSecure = true;
    } elseif (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) {
        $isSecure = true;
    }

    $LocalDefault = "en-US";
    $applicationName = "Surveillance Map";
    $applicationAuthor = "Surveillance Map Foundation";

    $protocol = $isSecure ? 'https' : 'http';
    $requestHost = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $requestHostWithoutWww = str_replace("www.", "", $requestHost);
    $requestUri = $_SERVER['REQUEST_URI'] ?? '/';
    $locale = preg_match('/^\/(.*?-.*?)\//', $requestUri, $matches) ? $matches[1] : $LocalDefault;
    $localeMeta = str_replace("-", "_", $locale);

    $currentEndpoint = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://$requestHost";
    $currentUrl = "$currentEndpoint$requestUri";

    $localPathToHome = "/$locale";
    $localPathToMap = "/$locale/map";
    $localPathToBrowse = "/$locale/search";
    $localPathToEmbeds = "/embed";
    $localPathToImageArchive = "/image/archive";
    $localPathToImageThumbnail = "/image/thumb";

    $globalUriToHome = "$currentEndpoint$localPathToHome";
    $globalUriToMap = "$currentEndpoint$localPathToMap";
    $globalUriToBrowse = "$currentEndpoint$localPathToBrowse";
    $globalUriToEmbeds = "$currentEndpoint$localPathToEmbeds";
    $globalUriToImageArchive = "$currentEndpoint$localPathToImageArchive";
    $globalUriToImageThumbnail = "$currentEndpoint$localPathToImageThumbnail";

    $imageArchiveFirstExtension = "/first";
    $imageArchiveLatestExtension = "/last";

    $stages = ["continent", "country", "region", "city"];
    $segments = array_merge([$root], $roots); // Combine all active segments
    // $segmentsUcwords = array_map('ucwords', $segments);
    $segmentsUcwords = array_map(fn($segment) => ucwords(str_replace('-', ' ', $segment)), $segments);
    $totalNodes = count($segments);
    
    // Start with your base path (e.g., removing any trailing slash from the base endpoint)
    $searchCurrentStage = "";
    $searchArray = [];
    $searchQueryParts = [];

    $breadcrumbsPath0 = "";
    $breadcrumbsPath1 = "$breadcrumbsPath0/$locale";
    $breadcrumbsPath1Canoncial = "$breadcrumbsPath0/$locale";
    $breadcrumbsPath2 = "$breadcrumbsPath1/" . implode("/", $segments);
    $breadcrumbsPath2Canoncial = "$breadcrumbsPath1Canoncial/" . implode("/", $segments);

    $currentPath = $currentEndpoint . $breadcrumbsPath1; 

    $itemListElements = [
        [
            "@type" => "ListItem",
            "position" => 1,
            "name" => "Home",
            "item" => $currentPath
        ]
    ];
    
    foreach ($segments as $i => $val) {
        $stage = $stages[$i];
        $searchCurrentStage = $stage;
        
        // 1. Store Search Ref & Raw string
        $searchArray[$stage] = $val;
        // Temporary override
        // $searchQueryParts[] = $stage . ':"' . $val . '"';
        // $searchQueryParts[] = $stage . '_seo:"' . $val . '"';
        array_push($searchQueryParts, ...array_map(fn($part) => $stage . ':"' . trim($part) . '"', explode('-', $val)));
        
        // 2. Build the Clean URL iteratively (e.g., /base/asia -> /base/asia/japan)
        $currentPath .= '/' . $val; 
        
        // 3. Build Breadcrumb item
        $itemElement = [
            "@type" => "ListItem",
            "position" => $i + 2,
            "name" => ucwords(str_replace("-", " ", $val))
        ];
    
        // Only assign the link if it is NOT the final node
        if ($i < $totalNodes - 1) {
            $itemElement["item"] = $currentPath;
        }
    
        $itemListElements[] = $itemElement;
    }
    
    $searchCurrentStageValue = ucwords(str_replace("-", " ", $searchArray[$searchCurrentStage]));

    $jsonBreadcrumbs = [
        "@context" => "https://schema.org",
        "@type" => "BreadcrumbList",
        "itemListElement" => $itemListElements
    ];

    $searchTerm = implode(" ", $searchQueryParts);
    
    $searchFollowingStage = count($searchArray) < count($stages) ? $stages[count($searchArray)] : $stages[count($searchArray) - 1];
    
    $searchColumsBase = count($searchArray) < count($stages) ? array_merge(array_keys($searchArray), [$searchFollowingStage]) : array_keys($searchArray);

    // print($searchTerm);
    
    $searchResultsCurrent = $db->searchEntries($searchTerm . " {$statusQuery}", $fields = array_merge($searchColumsBase, ["status"]), $returnStats = true, $statsColumns = array_merge($searchColumsBase, ["status"]), $excludeStatsColumns = [], $includeAllValues = true, $returnColumns = array_merge($stages, ["latitude", "longitude", "status", "notes_name_en", "notes_description_en"]), $includeResultsInStats = true);

    if (empty($searchResultsCurrent["results"])) {
        $status = 2;

        $statusQuery = $status > 2 || $status < 0 ? "status:1" : ($status == 2 ? "" : "status:{$status}");
        $statusText = $status > 2 || $status < 0 ? "online" : ($status == 2 ? "online and offline" : ($status == 1 ? "online" : "offline"));
        $statusTextLive = $status > 2 || $status < 0 ? "live" : ($status == 2 ? "live and offline" : ($status == 1 ? "live" : "offline"));
        $statusUrlParameter = "?" . ($status == 1 ? "" : "status={$status}");

        $searchResultsCurrent = $db->searchEntries($searchTerm . " {$statusQuery}", $fields = array_merge($searchColumsBase, ["status"]), $returnStats = true, $statsColumns = array_merge($searchColumsBase, ["status"]), $excludeStatsColumns = [], $includeAllValues = true, $returnColumns = array_merge($stages, ["latitude", "longitude", "status", "notes_name_en", "notes_description_en"]), $includeResultsInStats = true);

        if (empty($searchResultsCurrent["results"])) {
            header('HTTP/2 503');
            header('Retry-After: ' . (2 * 24 * 60 * 60));
            exit;
        }
    }

    $pageResults = paginate($searchResultsCurrent["results"], $resultsPerPage, $page);
    $nextPageButtonDisableValue = $pageResults["last_page"] == $pageResults["current_page"] ? "disabled" : "";
    $previousPageButtonDisableValue = $pageResults["first_page"] == $pageResults["current_page"] ? "disabled" : "";

    $suggestions = empty($searchResultsCurrent["results"]) ? [] : array_intersect_key($searchResultsCurrent["results"], array_flip((array) array_rand($searchResultsCurrent["results"], min(4, count($searchResultsCurrent["results"])))));
    $array = array_shift($suggestions);

    $arrayLatitude = !empty($array) && isset($array["latitude"]) && !empty($array["latitude"]) ? $array["latitude"] : null;
    $arrayLongitude = !empty($array) && isset($array["longitude"])  && !empty($array["longitude"])? $array["longitude"] : null;
    $arrayInternalId = !empty($array) && isset($array["internal_id"]) && !empty($array["internal_id"]) ? $array["internal_id"] : null;
    $arrayContinent = !empty($array) && isset($array["continent"]) && !empty($array["continent"]) ? $array["continent"] : null;
    $arrayCountry = !empty($array) && isset($array["country"]) && !empty($array["country"]) ? $array["country"] : null;
    $arrayRegion = !empty($array) && isset($array["region"]) && !empty($array["region"]) ? $array["region"] : null;
    $arrayCity = !empty($array) && isset($array["city"]) && !empty($array["city"]) ? $array["city"] : null;
    $arrayName = !empty($array) && isset($array["notes_name_en"]) && !empty($array["notes_name_en"]) ? $array["notes_name_en"] : null;
    $arrayDescription = !empty($array) && isset($array["notes_description_en"]) && !empty($array["notes_description_en"]) ? $array["notes_description_en"] : null;

// United Kingdon Locale Decimal
// $ukFormatter = new NumberFormatter('en_UK', NumberFormatter::DECIMAL);
// echo $ukFormatter->format(1234567.89); 

// US Locale Currency
// $usCurrency = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
// echo $usCurrency->formatCurrency(1234567.89, 'USD'); 
// Output: $1,234,567.89

    $usFormatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);

    $searchResultsAllRecordsScanned = $usFormatter->format($searchResultsCurrent["statistics"]["datasetMetrics"]["totalRecordsScanned"]);
    $searchResultsCurrenttAllMatchesFound = $usFormatter->format($searchResultsCurrent["statistics"]["datasetMetrics"]["totalMatchesFound"]);
    $searchResultsCurrentMaxHitRatePercentage = $usFormatter->format($searchResultsCurrent["statistics"]["datasetMetrics"]["matchHitRatePercentage"]);
    $searchFollowingStageValuesCount = $usFormatter->format($searchResultsCurrent["statistics"]["columnValueStats"][$searchFollowingStage]["uniqueValuesCount"]);

    switch ($searchCurrentStage) {
        case "continent":
            $zoom = 2;
            $textPageTitle = ucwords(str_replace("-", " ", $searchArray["continent"])) . " Camera Views";
            $textPageSubheading = "{$searchResultsCurrenttAllMatchesFound} in {$searchFollowingStageValuesCount} countries";
            $textPageMetaTitle = "{$searchResultsCurrenttAllMatchesFound} " . str_replace("And", "and", ucwords($statusTextLive)) . " Traffic, Beach, Weather, Airport and Nature Cameras in " . implode(", ", $segmentsUcwords) . " (" . date("Y") . ") - Watch Live | $applicationName";
            $textPageMetaDescription = "Watch $searchResultsCurrenttAllMatchesFound $statusTextLive cameras in " . end($segmentsUcwords) . " right now - traffic, beach, weather, airport and nature webcams streaming in real time on an interactive map. Updated continuously, " . date("Y") . ".";
            $textPageMostFrequentValuesDescription = "The countries on the continent " . ucwords(str_replace("-", " ", $searchArray["continent"])) . " with most cameras on record are ";
            break;
        case "country":
            $zoom = 4;
            $textPageTitle = ucwords(str_replace("-", " ", $searchArray["country"])) . " " . ucwords(str_replace("and", "&", $statusTextLive)) . " Cameras";
            $textPageSubheading = "{$searchResultsCurrenttAllMatchesFound} $statusTextLive cameras across {$searchFollowingStageValuesCount} states/provinces";
            $textPageMetaTitle = "{$searchResultsCurrenttAllMatchesFound} " . str_replace("And", "and", ucwords($statusTextLive)) . " Traffic, Ski, Weather, Landmark and Nature Cameras in " . implode(", ", $segmentsUcwords) . " (" . date("Y") . ") - Watch Live | $applicationName";
            $textPageMetaDescription = "Watch $searchResultsCurrenttAllMatchesFound $statusTextLive cameras in " . implode(", ", $segmentsUcwords) . " right now - traffic, ski, weather, landmark and nature webcams streaming in real time on an interactive map. Updated continuously, " . date("Y") . ".";
            $textPageMostFrequentValuesDescription = "The regions/states/provinces in the country " . ucwords(str_replace("-", " ", $searchArray["country"])) . " with most cameras on record are ";
            break;
        case "region":
            $zoom = 9;
            $textPageTitle = ucwords(str_replace("-", " ", $searchArray["region"])) . ", " . ucwords(str_replace("-", " ", $searchArray["country"])) . " " . ucwords(str_replace("and", "&", $statusTextLive)) . " Cameras";
            $textPageSubheading = "{$searchResultsCurrenttAllMatchesFound} $statusTextLive cameras across {$searchFollowingStageValuesCount} " . ($searchFollowingStageValuesCount > 1 ? "cities" : "city");
            $textPageMetaTitle = "{$searchResultsCurrenttAllMatchesFound} " . str_replace("And", "and", ucwords($statusTextLive)) . " Water, Beach, Weather, Museum and Nature Cameras Cameras in " . implode(", ", $segmentsUcwords) . " (" . date("Y") . ") - Watch Live | $applicationName";
            $textPageMetaDescription = "Watch {$searchResultsCurrenttAllMatchesFound} $statusTextLive traffic cameras in " . implode(", ", $segmentsUcwords) . ". " . str_replace("And", "and", ucwords($statusTextLive)) . " webcams updated in real time - water,beach, weather, museum, nature cams, and more.";
            $textPageMostFrequentValuesDescription = "The cities in the region of " . ucwords(str_replace("-", " ", $searchArray["region"])) . " with most cameras on record are ";
            break;
        case "city":
            $zoom = 13;
            $textPageTitle = "{$searchCurrentStageValue} Cameras $statusTextLive";
            $textPageSubheading = "{$searchResultsCurrenttAllMatchesFound} $statusTextLive cameras";
            $textPageMetaTitle = "{$searchResultsCurrenttAllMatchesFound} " . str_replace("And", "and", ucwords($statusTextLive)) . " Wildlife, Beach, Weather, Monument and Nature Cameras Cameras in " . implode(", ", $segmentsUcwords) . " (" . date("Y") . ") - Watch Live | $applicationName";
            $textPageMetaDescription = "Watch {$searchResultsCurrenttAllMatchesFound} $statusTextLive traffic cameras in " . implode(", ", $segmentsUcwords) . ". " . str_replace("And", "and", ucwords($statusTextLive)) . " webcams updated in real time - wildlife, beach, weather, monument, nature cams, and more.";
            $textPageMostFrequentValuesDescription = "The city in " . ucwords(str_replace("-", " ", $searchArray["city"])) . " with most cameras on record is ";
            break;
    }

    $jsonFAQs = [
        "continent" => [
		"@context" => "https://schema.org", 
		"@type" => "FAQPage", 
		"mainEntity" => 
		[[
			"@type" => "Question", 
			"name" => "How many $statusTextLive cameras are in {$searchCurrentStageValue}?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "$searchCurrentStageValue has {$searchResultsCurrenttAllMatchesFound} active $statusTextLive cameras streaming on {$requestHostWithoutWww}. Coverage spans {$searchFollowingStageValuesCount} states, provinces, and regions, with new cameras added continuously."
			]
		],
		[
			"@type" => "Question", 
			"name" => "What types of cameras may I watch in {$searchCurrentStageValue}?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "{$searchCurrentStageValue} cameras cover traffic, beach, weather, airport and nature — all updated in real time and free to watch."
			]
		],
		[
			"@type" => "Question", 
			"name" => "Are the $statusTextLive cameras in {$searchCurrentStageValue} free to watch?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "Yes — every camera on {$requestHostWithoutWww} is publicly available and free to watch. There is no signup, paywall, or rate limit."
			]
		],
		[
			"@type" => "Question", 
			"name" => "How often do {$searchCurrentStageValue} cameras update?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "All cameras in {$searchCurrentStageValue} provide real-time access and therefore update continuously."
			]
		],
		[
			"@type" => "Question", 
			"name" => "May I see all {$searchCurrentStageValue} cameras on a map?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "Yes — open the interactive map to see every {$searchCurrentStageValue} camera plotted geographically. You may zoom into any region, filter by category, and click any marker to start watching the live feed."
			]
		]]
	],
	"country" => [
		"@context" => "https://schema.org", 
		"@type" => "FAQPage", 
		"mainEntity" => 
		[[
			"@type" => "Question", 
			"name" => "How many $statusTextLive cameras are in {$searchCurrentStageValue}?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "$searchCurrentStageValue has {$searchResultsCurrenttAllMatchesFound} active $statusTextLive cameras streaming on {$requestHostWithoutWww}. Coverage spans {$searchFollowingStageValuesCount} states, provinces, and regions, with new cameras added continuously."
			]
		],
		[
			"@type" => "Question", 
			"name" => "What types of cameras may I watch in {$searchCurrentStageValue}?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "{$searchCurrentStageValue} cameras cover traffic, ski, weather, landmark and nature — all updated in real time and free to watch."
			]
		],
		[
			"@type" => "Question", 
			"name" => "Are the $statusTextLive cameras in {$searchCurrentStageValue} free to watch?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "Yes — every camera on {$requestHostWithoutWww} is publicly available and free to watch. There is no signup, paywall, or rate limit."
			]
		],
		[
			"@type" => "Question", 
			"name" => "How often do {$searchCurrentStageValue} cameras update?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "All cameras in {$searchCurrentStageValue} provide real-time access and therefore update continuously."
			]
		],
		[
			"@type" => "Question", 
			"name" => "May I see all {$searchCurrentStageValue} cameras on a map?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "Yes — open the interactive map to see every {$searchCurrentStageValue} camera plotted geographically. You may zoom into any region, filter by category, and click any marker to start watching the live feed."
			]
		]]
	],
	"region" => [
		"@context" => "https://schema.org", 
		"@type" => "FAQPage", 
		"mainEntity" => 
		[[
			"@type" => "Question", 
			"name" => "How many $statusTextLive cameras are in {$searchCurrentStageValue}?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "$searchCurrentStageValue has {$searchResultsCurrenttAllMatchesFound} active $statusTextLive cameras on {$requestHostWithoutWww}, distributed across {$searchFollowingStageValuesCount} cities and towns. Every feed is publicly available and updates in real time."
			]
		],
		[
			"@type" => "Question", 
			"name" => "What kinds of cameras are available in {$searchCurrentStageValue}?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "{$searchCurrentStageValue} cameras cover water,beach, weather, museum and nature — all updated in real time and free to watch."
			]
		],
		[
			"@type" => "Question", 
			"name" => "Are the $statusTextLive cameras in {$searchCurrentStageValue} free to watch?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "Yes — every camera on {$requestHostWithoutWww} is publicly available and free to watch. There is no signup, paywall, or rate limit."
			]
		],
		[
			"@type" => "Question", 
			"name" => "How often do {$searchCurrentStageValue} cameras update?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "All cameras in {$searchCurrentStageValue} provide real-time access and therefore update continuously."
			]
		],
		[
			"@type" => "Question", 
			"name" => "Where may I see {$searchCurrentStageValue} cameras on a map?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "Open the interactive map to see every {$searchCurrentStageValue} camera plotted geographically — zoom in, filter, and click any marker to watch live."
			]
		]]
	],
	"city" => [
		"@context" => "https://schema.org", 
		"@type" => "FAQPage", 
		"mainEntity" => 
		[[
			"@type" => "Question", 
			"name" => "How many $statusTextLive cameras are in {$searchCurrentStageValue}?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "$searchCurrentStageValue has {$searchResultsCurrenttAllMatchesFound} active $statusTextLive cameras streaming on {$requestHostWithoutWww}. Coverage spans {$searchFollowingStageValuesCount} city, with new cameras added continuously."
			]
		],
		[
			"@type" => "Question", 
			"name" => "What types of cameras are in {$searchCurrentStageValue}?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "{$searchCurrentStageValue} cameras cover wildlife, beach, weather, monument and nature — all updated in real time and free to watch."
			]
		],
		[
			"@type" => "Question", 
			"name" => "Are the $statusTextLive cameras in {$searchCurrentStageValue} free to watch?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "Yes — every camera on {$requestHostWithoutWww} is publicly available and free to watch. There is no signup, paywall, or rate limit."
			]
		],
		[
			"@type" => "Question", 
			"name" => "What is the best live camera in {$searchCurrentStageValue}?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "The most-watched and highlighted {$searchCurrentStageValue} cameras are featured on the top of the {$searchCurrentStageValue} page — open the city page to see the current ranking and click any camera to watch."
			]
		],
		[
			"@type" => "Question", 
			"name" => "How often do {$searchCurrentStageValue} cameras update?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "All cameras in {$searchCurrentStageValue} provide real-time access and therefore update continuously."
			]
		],
		[
			"@type" => "Question", 
			"name" => "How I see {$searchCurrentStageValue} cameras on a map?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "The interactive map shows every {$searchCurrentStageValue} camera plotted by location. Zoom in, filter by category, and click any marker to start watching."
			]
		]]
	]];
	
	$jsonCollectionPage = [
    "@context" => "https://schema.org",
    "@type" => "CollectionPage",
    "name" => end($segmentsUcwords) . " " . ucwords(str_replace("and", "&", $statusTextLive)) . " Cameras",
    "url" => $currentEndpoint . $breadcrumbsPath2Canoncial
    ];

	$jsonItemList = [
    "@context" => "https://schema.org",
    "@type" => "ItemList",
    "name" => end($segmentsUcwords) . " " . ucwords(str_replace("and", "&", $statusTextLive)) . " Cameras",
    "url" => $currentEndpoint . $breadcrumbsPath2Canoncial,
    "numberOfItems" => $pageResults["on_page"],
    "itemListElement" => []
    ];

    $jsonPlace = [
    "@context" => "https://schema.org",
    "@type" => "Place",
    "name" => end($segmentsUcwords),
    "url" => $currentEndpoint . $breadcrumbsPath2Canoncial,
    "geo" =>
    	[
    	    "@type" => "GeoCoordinates",
    	    "latitude" => (float)$arrayLatitude,
    	    "longitude" => (float)$arrayLongitude
    	],
    "description" => "{$searchResultsCurrenttAllMatchesFound} {$statusTextLive} cameras"
   ];
   
   if ($searchCurrentStage != "continent") {
       $jsonPlace["containedInPlace"] =
    	[
    	    "@type" => "Place",
    	    "name" => $segmentsUcwords[count($segmentsUcwords) - 2]
    	];
   }

    // header('Content-Type: application/json; charset=utf-8');
    // print_r(json_encode($searchResultsCurrent, JSON_PRETTY_PRINT));
    // exit;

    foreach ($jsonBreadcrumbs["itemListElement"] as $breadcrumb) {
        if (!isset($breadcrumb["item"])) {
            $htmlPageBreadcrumbs .= "<li class=\"breadcrumbs-item active\" aria-current=\"page\">{$breadcrumb["name"]}</li>\n               ";
        } else {
            $htmlPageBreadcrumbs .= "<li class=\"breadcrumbs-item\"><a href=\"{$breadcrumb["item"]}\" class=\"breadcrumbs-link\">{$breadcrumb["name"]}</a></li>\n               ";
        }
    }

    foreach ($jsonFAQs[$searchCurrentStage]["mainEntity"] as $faq) {
        $htmlPageFAQs .= "<div class=\"qa-item\">
                    <div class=\"qa-question\">{$faq["name"]}</div>
                    <div class=\"qa-answer\">{$faq["acceptedAnswer"]["text"]}</div>
                </div>\n                ";
    }
    
    foreach ($searchResultsCurrent["statistics"]["columnValueStats"][$searchFollowingStage]["frequentValues"] as $key => $val) {
        $htmlPageFrequencyList .= "<div class=\"frequency-row\">
                    <span style=\"font-weight: 600; min-width: 140px;\">$key</span>
                    <div class=\"frequency-bar-bg\"><div class=\"frequency-bar-fill\" style=\"width: {$val["percentage"]}%;\"></div></div>
                    <span style=\"color: var(--text-secondary); min-width: 50px; text-align: right;\">{$val["count"]} records</span>
                </div>";
        
        $htmlPageFollowingBreadcrumbLink = "{$breadcrumbsPath2}/" . strtolower(trim(generate_seo_slug($key))) . ($status == 1 ? "" : "?status={$status}");

        $htmlPageBreakDownList .= "<a href=\"{$htmlPageFollowingBreadcrumbLink}\" class=\"frequent-item category-tag\"><span>{$key}</span><span>{$val["count"]}</span></a>";

        if ($htmlPageStatBarListCount < 5) {
            $valPercentage = (int)$val["percentage"];
            $htmlPageStatBarList .= "<div class=\"stat-bar-item\">
                        <div class=\"stat-bar-label\"><span><a href=\"{$htmlPageFollowingBreadcrumbLink}\" class=\"featured-link\">{$key}</a></span><span>{$val["count"]} records</span></div>
                        <div class=\"stat-bar-track\"><div class=\"stat-bar-fill\" style=\"width: {$val["percentage"]}%;\"></div></div>
                    </div>";

            $mostFrequentValues[] = "<a href=\"{$htmlPageFollowingBreadcrumbLink}\" class=\"featured-link\">{$key}</a> ({$val["count"]}/{$valPercentage}%)";

            $htmlPageStatBarListCount++;
        }
    }

    foreach ($suggestions as $index => $suggestion) {
        if (empty($suggestion)) continue;

        $sCity = $suggestion["city"] ?? '';
        $sRegion = $suggestion["region"] ?? '';
        $sCountry = $suggestion["country"] ?? '';
        $sContinent = $suggestion["continent"] ?? '';
        $sAvailabilityStatus = $suggestion["status"] == 1 ? "online" : "offline";


        $suggestionNameOriginal = !empty($suggestion["notes_name_en"]) 
                ? $suggestion["notes_name_en"] 
                : ltrim(($sCity ? $sCity : '') . ($sRegion ? " · " . $sRegion : '') . ($sCountry ? " · " . $sCountry : ''), ' ,');

        $suggestionSlug = "$breadcrumbsPath1/" . strtolower(trim(generate_seo_slug($sContinent)))  . "/" . strtolower(trim(generate_seo_slug($sCountry))) . "/" . strtolower(trim(generate_seo_slug($sRegion))) . "/" . strtolower(trim(generate_seo_slug($sCity))) . (!empty($suggestion["notes_name_en"]) ? "-" . generate_seo_slug($suggestion["notes_name_en"]) : "") . ".view." . $suggestion["internal_id"];
        $distance = round(calculateDistance($arrayLatitude, $arrayLongitude, $suggestion["latitude"], $suggestion["longitude"], 'K'), 2);

        $suggestionDescription = "{$distance} km away from centre and {$sAvailabilityStatus}";

        $htmlPageHighlightedViews .= "<!-- Highlighted View $index -->
                <a href=\"{$suggestionSlug}\" class=\"featured-card\">
                    <img src=\"{$globalUriToImageArchive}/{$suggestion["internal_id"]}{$imageArchiveLatestExtension}\" alt=\"{$suggestionNameOriginal}\" class=\"featured-image\">
                    <div class=\"featured-content\">
                        <div class=\"featured-subhead\">Featured {$statusTextLive} camera in {$searchCurrentStageValue}</div>
                        <h3 class=\"featured-title\">{$suggestionNameOriginal}</h3>
                        <p class=\"featured-desc\">{$suggestionDescription}</p>
                        <span class=\"featured-link\">Go To Camera View →</span>
                    </div>
                </a>";

        $htmlPageNotableViews .= "<p><a href=\"{$suggestionSlug}\" class=\"featured-link\">{$suggestionNameOriginal}</a></p>";
    }

    foreach ($pageResults["data"] as $index => $pageResult) {
        if (empty($pageResult)) continue;

        $sCity = $pageResult["city"] ?? '';
        $sRegion = $pageResult["region"] ?? '';
        $sCountry = $pageResult["country"] ?? '';
        $sContinent = $pageResult["continent"] ?? '';
        $sLatitude = $pageResult["latitude"] ?? '';
        $sLongitude = $pageResult["longitude"] ?? '';
        $sAvailabilityStatus = $pageResult["status"] == 1 ? "online" : "offline";


        $pageResultNameOriginal = !empty($pageResult["notes_name_en"]) 
                ? $pageResult["notes_name_en"] 
                : ltrim(($sCity ? $sCity : '') . ($sRegion ? " · " . $sRegion : '') . ($sCountry ? " · " . $sCountry : ''), ' ,');

        $pageResultSlug = "$breadcrumbsPath1/" . strtolower(trim(generate_seo_slug($sContinent)))  . "/" . strtolower(trim(generate_seo_slug($sCountry))) . "/" . strtolower(trim(generate_seo_slug($sRegion))) . "/" . strtolower(trim(generate_seo_slug($sCity))) . (!empty($pageResult["notes_name_en"]) ? "-" . generate_seo_slug($pageResult["notes_name_en"]) : "") . ".view." . $pageResult["internal_id"];
        $distance = round(calculateDistance($arrayLatitude, $arrayLongitude, $pageResult["latitude"], $pageResult["longitude"], 'K'), 2);

        $pageResultDescription = "{$distance} km away from centre and {$sAvailabilityStatus}";

        $htmlPageDirectoryGrid .= "<div class=\"directory-card\">
                    <img src=\"{$globalUriToImageArchive}/{$pageResult["internal_id"]}{$imageArchiveLatestExtension}\" alt=\"{$pageResultNameOriginal}\" class=\"directory-card-img\">
                    <div class=\"directory-card-body\">
                        <h4 class=\"directory-card-heading\">{$pageResultNameOriginal}</h4>
                        <div class=\"directory-card-subheading\">{$pageResultDescription}</div>
                        <a href=\"{$pageResultSlug}\" class=\"featured-link\" style=\"font-size: 0.85rem;\">Go To Camera View →</a>
                    </div>
                </div>";

        $jsonItemList["itemListElement"][] = [
    	"@type" => "ListItem",
    	"position" => $index + 1,
    	"item" => 
    	[
    		"@type" => "ImageObject",
    		"name" => $pageResultNameOriginal,
    		"contentUrl" => "{$globalUriToImageArchive}/{$pageResult["internal_id"]}{$imageArchiveLatestExtension}",
    		"thumbnailUrl" => "{$globalUriToImageArchive}/{$pageResult["internal_id"]}{$imageArchiveLatestExtension}",
    		"url" => "{$currentEndpoint}{$pageResultSlug}",
    		"contentLocation" => 
    		[
    			"@type" => "Place",
    			"name" => str_replace(" · ", ", ", $pageResultNameOriginal),
    			"geo" => 
    			[
    				"@type" => "GeoCoordinates",
    				"latitude" => (float)$sLatitude,
    				"longitude" => (float)$sLongitude
    			]
    		]
    	]
    ];

    }

    $globalUriToEntryMap = "$globalUriToMap?lat=" . (!is_null($arrayLatitude) ? $arrayLatitude : 0) . "&lon=" . (!is_null($arrayLongitude) ? $arrayLongitude : 0) . "&zoom=11000&pitch=-90";

    $textPageMetaDescription = (mb_strlen($textPageMetaDescription) > 155) ? mb_substr($textPageMetaDescription, 0, 152) . '...' : $textPageMetaDescription;

/*
    <script type="application/ld+json">{"@context":"https://schema.org","@type":"CollectionPage","name":"Condove, Piemont, Italy Live Cameras","url":"https://opencctv.org/cameras/italy/piemont/condove"}</script>
    <script type="application/ld+json">}</script>
    <script type="application/ld+json">{"@context":"https://schema.org","@type":"Place","name":"Condove, Piemont, Italy","url":"https://opencctv.org/cameras/italy/piemont/condove","geo":{"@type":"GeoCoordinates","latitude":45.11691,"longitude":7.31064},"containedInPlace":{"@type":"Place","name":"Piemont"},"description":"1 live cameras"}</script>

    <script type="application/ld+json">{"@context":"https://schema.org","@type":"FAQPage","mainEntity":[{"@type":"Question","name":"How many live cameras are in Condove?","acceptedAnswer":{"@type":"Answer","text":"Condove, Piemont has 1 active live cameras on opencctv.org. Most are ski cameras."}},{"@type":"Question","name":"What types of cameras are in Condove?","acceptedAnswer":{"@type":"Answer","text":"Condove cameras cover ski. All updates happen in real time from official public sources."}},{"@type":"Question","name":"What is the best live camera in Condove?","acceptedAnswer":{"@type":"Answer","text":"The most-watched Condove cameras are typically ski feeds — open the city page to see the current ranking and click any camera to watch."}},{"@type":"Question","name":"How often do Condove cameras update?","acceptedAnswer":{"@type":"Answer","text":"Most Condove cameras refresh every 30 to 60 seconds. Live video streams update continuously."}},{"@type":"Question","name":"How can I see Condove cameras on a map?","acceptedAnswer":{"@type":"Answer","text":"The interactive map shows every Condove camera plotted by location. Zoom in, filter by category, and click any marker to start watching."}}]}</script>
    */

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="index,follow,max-image-preview:large,max-snippet:-1,max-video-preview:-1">
    <title><?php echo $textPageMetaTitle; ?></title>
    
    <!-- SEO Meta Tags -->
    <meta name="description" content="<?php echo $textPageMetaDescription; ?>">
    <meta name="author" content="<?php echo $applicationAuthor; ?>">
    <link rel="canonical" href="<?php echo $currentUrl; ?>">
    <link rel="icon" href="<?php echo $currentEndpoint; ?>/favicon.ico">

    <!-- Open Graph / Social SEO -->
    <meta property="og:title" content="<?php echo $textPageMetaTitle; ?>">
    <meta property="og:description" content="<?php echo $textPageMetaDescription; ?>">
    <meta property="og:type" content="website">
    <meta property="og:url" content="<?php echo $currentUrl; ?>">
    <meta property="og:image" content="<?php echo "$globalUriToImageArchive/$arrayInternalId$imageArchiveLatestExtension"; ?>">
    <meta property="og:locale" content="<?php echo $localeMeta; ?>">
    <meta property="og:site_name" content="<?php echo $applicationName; ?>">
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?php echo $textPageMetaTitle; ?>">
    <meta name="twitter:description" content="<?php echo $textPageMetaDescription; ?>">
    <meta name="twitter:image" content="<?php echo $currentEndpoint; ?>/favicon.ico">

    <!-- Schema.org Structured Data for AI Agents & SEO -->
    <script type="application/ld+json"><?php echo json_encode($jsonCollectionPage, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?></script>
    <script type="application/ld+json"><?php echo json_encode($jsonItemList, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?></script>
    <script type="application/ld+json"><?php echo json_encode($jsonPlace, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?></script>
    <script type="application/ld+json"><?php echo json_encode($jsonBreadcrumbs, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?></script>
    <script type="application/ld+json"><?php echo json_encode($jsonFAQs[$searchCurrentStage], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?></script>

    <!-- Preconnect to third parties used for faster load speeds -->
    <link rel="preconnect" href="https://www.psb.li" crossorigin>
    <link rel="preconnect" href="https://www.cestla.ch" crossorigin>
    <link rel="preconnect" href="https://api.open-meteo.com" crossorigin>
    <link rel="preconnect" href="https://air-quality-api.open-meteo.com" crossorigin>
    <link rel="preconnect" href="<?php echo $currentEndpoint; ?>" crossorigin>
    <link rel="preconnect" href="https://unpkg.com">
    <link rel="preconnect" href="https://cdn.jsdelivr.net">
    <link rel="preconnect" href="https://mt0.google.com">
    <link rel="preconnect" href="https://mt1.google.com">
    <link rel="preconnect" href="https://mt2.google.com">
    <link rel="preconnect" href="https://mt3.google.com">

    <!-- Google Fonts for Classical-Modern Typography -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,400;0,600;0,700;1,400&family=Plus+Jakarta+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <link href="/assets/css/weather.css" rel="stylesheet">
    <script src="/assets/js/weather.js"></script>

    <script src="https://unpkg.com/maplibre-gl@3.6.1/dist/maplibre-gl.js"></script>
    <link href="https://unpkg.com/maplibre-gl@3.6.1/dist/maplibre-gl.css" rel="stylesheet"/>

    <!-- Clarity tracking code for https://www.surveillance-map.com/ -->
    <script>
    (function(c, l, a, r, i, t, y) {
        c[a] = c[a] || function() {
            (c[a].q = c[a].q || []).push(arguments)
        };
        t = l.createElement(r);
        t.async = 1;
        t.src = "https://www.clarity.ms/tag/" + i + "?ref=bwt";
        y = l.getElementsByTagName(r)[0];
        y.parentNode.insertBefore(t, y);
    })(window, document, "clarity", "script", "xkhagxf226");
    </script>

    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2319892673201245" crossorigin="anonymous"></script>
    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-4MMFDZY7M3"></script>
    <script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }
    gtag('js', new Date());

    gtag('config', 'G-4MMFDZY7M3');
    </script>

    <!-- Stylesheet -->
    <style>
    :root {
        --bg-color: #fcfbf9;
        --surface-color: #ffffff;
        --surface-alt: #f4f1ea;
        --text-primary: #1a1917;
        --text-secondary: #635f56;
        --accent-color: #8c6d46;
        --accent-hover: #6e5435;
        --border-color: #e3ded4;
        --font-serif: 'Cormorant Garamond', Georgia, serif;
        --font-sans: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        --max-width: 1400px;
        --radius-sm: 6px;
        --radius-md: 12px;
        --radius-lg: 20px;
        --shadow-subtle: 0 10px 30px -10px rgba(26, 25, 23, 0.05);
        --shadow-card: 0 4px 20px rgba(26, 25, 23, 0.03);
        --transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    }
    
    @media (prefers-color-scheme: dark) {
        :root {
            --bg-color: #121110;
            --surface-color: #1a1816;
            --surface-alt: #24221f;
            --text-primary: #f4f1ea;
            --text-secondary: #a39e93;
            --accent-color: #d4b58e;
            --accent-hover: #e5c9a6;
            --border-color: #332f2b;
            --shadow-subtle: 0 10px 30px -10px rgba(0, 0, 0, 0.3);
            --shadow-card: 0 4px 20px rgba(0, 0, 0, 0.2);
        }
    }

    * {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
    }
    
    html {
        scroll-behavior: smooth;
    }
    
    body {
        background-color: var(--bg-color);
        color: var(--text-primary);
        font-family: var(--font-sans);
        line-height: 1.6;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        overflow-x: hidden;
        display: block !important;
    }
    
    .page-container {
        max-width: var(--max-width);
        margin: 0 auto;
        padding: 2rem 1.5rem;
    }
    
    @media (min-width: 1920px) {
        :root {
            --max-width: 1700px;
        }
    
        body {
            font-size: 1.125rem;
        }
    }
    
    @media (max-width: 768px) {
        .page-container {
            padding: 1rem;
        }
    }
    
    /* =========================================================
       BREADCRUMBS
       ========================================================= */
    
    .breadcrumbs-nav {
        margin-bottom: 2rem;
    }
    
    .breadcrumbs-list {
        list-style: none;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.875rem;
        color: var(--text-secondary);
    }
    
    .breadcrumbs-item:not(:last-child)::after {
        content: "/";
        margin-left: 0.5rem;
        color: var(--border-color);
    }
    
    .breadcrumbs-link {
        color: var(--text-secondary);
        text-decoration: none;
        transition: var(--transition);
    }
    
    .breadcrumbs-link:hover {
        color: var(--accent-color);
    }
    
    .breadcrumbs-item.active {
        color: var(--text-primary);
        font-weight: 500;
    }
    
    /* =========================================================
       PAGE HEADER
       ========================================================= */
    
    .page-header-section {
        margin-bottom: 2.5rem;
        background: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        padding: 3rem 2.5rem;
        box-shadow: var(--shadow-subtle);
        text-align: left;
    }
    
    .page-title {
        font-family: var(--font-serif);
        font-size: clamp(2.25rem, 4vw, 3.5rem);
        font-weight: 700;
        line-height: 1.15;
        margin-bottom: 0.75rem;
        color: var(--text-primary);
    }
    
    .page-subtitle {
        font-size: 1.15rem;
        color: var(--text-secondary);
        max-width: 900px;
    }
    
    /* Backwards-compatible header classes */
    .page-header-block {
        margin-bottom: 2.5rem;
        text-align: left;
    }
    
    .page-header-block h1 {
        font-family: var(--font-serif);
        font-size: clamp(2.25rem, 4vw, 3.5rem);
        font-weight: 700;
        line-height: 1.15;
        margin-bottom: 0.5rem;
    }
    
    .page-header-block p {
        color: var(--text-secondary);
        font-size: 1.1rem;
        max-width: 800px;
    }
    
    /* =========================================================
       FEATURED CONTENT
       ========================================================= */
    
    .featured-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
        gap: 2rem;
        margin-bottom: 2.5rem;
        justify-content: center;
    }
    
    .featured-card {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        overflow: hidden;
        box-shadow: var(--shadow-card);
        display: flex;
        flex-direction: column;
        transition: var(--transition);
        text-decoration: none;
        color: inherit;
    }
    
    .featured-card:hover {
        transform: translateY(-4px);
        box-shadow: var(--shadow-subtle);
        border-color: var(--accent-color);
    }
    
    .featured-image {
        width: 100%;
        aspect-ratio: 16 / 9;
        background-color: var(--surface-alt);
        object-fit: cover;
    }
    
    .featured-content {
        padding: 1.75rem;
        display: flex;
        flex-direction: column;
        flex-grow: 1;
    }
    
    .featured-subhead {
        font-size: 0.85rem;
        color: var(--accent-color);
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 0.5rem;
    }
    
    .featured-title {
        font-family: var(--font-serif);
        font-size: 1.5rem;
        font-weight: 600;
        margin-bottom: 0.75rem;
    }
    
    .featured-desc {
        color: var(--text-secondary);
        font-size: 0.95rem;
        margin-bottom: 1.5rem;
        flex-grow: 1;
    }
    
    .featured-link {
        font-weight: 600;
        font-size: 0.9rem;
        color: var(--accent-color);
        display: inline-flex;
        align-items: center;
        gap: 0.4rem;
        text-decoration: none;
    }
    
    /* Alternate featured layout retained */
    .featured-section {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        padding: 2.5rem;
        box-shadow: var(--shadow-subtle);
        margin-bottom: 2.5rem;
        display: grid;
        grid-template-columns: 1.2fr 1fr;
        gap: 2rem;
        align-items: center;
    }
    
    .featured-content h3 {
        font-family: var(--font-serif);
        font-size: 2rem;
        margin-bottom: 1rem;
    }
    
    .featured-content p {
        color: var(--text-secondary);
        margin-bottom: 1.5rem;
    }
    
    .featured-media-box {
        width: 100%;
        aspect-ratio: 16 / 10;
        background-color: var(--surface-alt);
        border-radius: var(--radius-md);
        overflow: hidden;
        border: 1px solid var(--border-color);
    }
    
    .featured-media-box img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    /* =========================================================
       CATEGORIES
       ========================================================= */
    
    .categories-section {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        padding: 2rem 2.5rem;
        margin-bottom: 2.5rem;
        box-shadow: var(--shadow-subtle);
    }
    
    .section-header {
        font-family: var(--font-serif);
        font-size: 2rem;
        margin-bottom: 1.25rem;
    }
    
    .section-subheader {
        color: var(--text-secondary);
        margin-bottom: 1.5rem;
        font-size: 0.95rem;
    }
    
    .categories-list {
        display: flex;
        gap: 0.75rem;
        flex-wrap: wrap;
        margin-bottom: 1.5rem;
    }
    
    .category-tag {
        background-color: var(--surface-alt);
        color: var(--text-primary);
        padding: 0.5rem 1rem;
        border-radius: var(--radius-sm);
        font-size: 0.875rem;
        font-weight: 500;
        text-decoration: none;
        border: 1px solid var(--border-color);
        transition: var(--transition);
    }
    
    .category-tag:hover {
        border-color: var(--accent-color);
        color: var(--accent-color);
        background-color: var(--surface-color);
    }
    
    /* =========================================================
       CONTENT / SIDEBAR
       ========================================================= */
    
    .content-sidebar-grid {
        display: grid;
        grid-template-columns: 2fr 1fr;
        gap: 2.5rem;
        margin-bottom: 2.5rem;
    }
    
    .extensive-text-card {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        padding: 2.5rem;
        box-shadow: var(--shadow-subtle);
        justify-content: center;
    }
    
    .extensive-text-card h3 {
        font-family: var(--font-serif);
        font-size: 1.75rem;
        margin-bottom: 1rem;
    }
    
    .extensive-text-card p {
        color: var(--text-secondary);
        margin-bottom: 1.25rem;
        font-size: 1.05rem;
    }
    
    .sidebar-widgets {
        display: flex;
        flex-direction: column;
        gap: 1.5rem;
        justify-content: center;
        max-width: 70vw;
        margin: auto;
    }
    
    .widget-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2.5rem;
    }
    
    .widget-card {
        background-color: var(--surface-alt);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        padding: 1.5rem;
    }
    
    .widget-title {
        font-size: 1rem;
        font-weight: 600;
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    
    .weather-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    
    .weather-temp {
        font-family: var(--font-serif);
        font-size: 2.5rem;
        font-weight: 700;
    }
    
    .weather-condition {
        font-size: 0.9rem;
        color: var(--text-secondary);
        text-align: right;
    }
    
    /* =========================================================
       VIEWER / PLAYER
       ========================================================= */
    
    .viewer-section {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        overflow: hidden;
        box-shadow: var(--shadow-subtle);
        margin-bottom: 2.5rem;
    }
    
    .media-container {
        width: 100%;
        aspect-ratio: 16 / 9;
        background-color: var(--surface-alt);
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .details-section {
        padding: 2.5rem;
        background-color: var(--surface-color);
        border-top: 1px solid var(--border-color);
    }
    
    .details-grid {
        display: grid;
        grid-template-columns: 2fr 1fr;
        gap: 2rem;
    }
    
    .details-meta-box {
        display: flex;
        flex-wrap: wrap;
        gap: 1.5rem;
        margin-bottom: 1.5rem;
        font-size: 0.9rem;
        color: var(--text-secondary);
        border-bottom: 1px solid var(--border-color);
        padding-bottom: 1rem;
    }
    
    .meta-item {
        display: flex;
        align-items: center;
        gap: 0.4rem;
    }
    
    /* =========================================================
       DIRECTORY
       ========================================================= */
    
    .directory-selection-section,
    .results-section,
    .directory-section {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        padding: 2.5rem;
        margin-bottom: 2.5rem;
        box-shadow: var(--shadow-subtle);
    }
    
    .directory-selection-section .section-header {
        margin-bottom: 1.5rem;
    }
    
    .directory-controls {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .control-group {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .control-label {
        font-weight: 600;
        font-size: 0.95rem;
    }
    
    .control-subtext {
        font-size: 0.8rem;
        color: var(--text-secondary);
    }
    
    .select-input,
    .text-input {
        background-color: var(--surface-alt);
        border: 1px solid var(--border-color);
        color: var(--text-primary);
        padding: 0.75rem 1rem;
        border-radius: var(--radius-sm);
        font-family: var(--font-sans);
        font-size: 0.95rem;
        outline: none;
        transition: var(--transition);
    }
    
    .select-input:focus,
    .text-input:focus {
        border-color: var(--accent-color);
        box-shadow: 0 0 0 3px rgba(140, 109, 70, 0.15);
    }
    
    .directory-grid,
    .directory-results-grid,
    .results-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
        justify-content: center;
    }
    
    .directory-card,
    .result-card {
        background-color: var(--surface-alt);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        overflow: hidden;
        transition: var(--transition);
    }
    
    .directory-card {
        display: flex;
        flex-direction: column;
    }
    
    .result-card {
        box-shadow: var(--shadow-card);
        display: flex;
        flex-direction: column;
    }
    
    .directory-card:hover {
        border-color: var(--accent-color);
        transform: translateY(-2px);
    }
    
    .result-card:hover {
        transform: translateY(-4px);
        box-shadow: var(--shadow-subtle);
        border-color: var(--accent-color);
    }
    
    .directory-card-img,
    .directory-card img,
    .result-image {
        width: 100%;
        aspect-ratio: 16 / 10;
        object-fit: cover;
        background-color: var(--border-color);
    }
    
    .directory-card-body,
    .result-body {
        padding: 1.25rem;
    }
    
    .result-body {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .directory-card-heading,
    .directory-card-title,
    .result-heading {
        font-family: var(--font-serif);
        font-size: 1.25rem;
        font-weight: 600;
        margin-bottom: 0.35rem;
    }
    
    .directory-card-subheading,
    .directory-card-subtitle,
    .result-subheading {
        font-size: 0.875rem;
        color: var(--text-secondary);
        margin-bottom: 0.75rem;
    }
    
    .directory-card-text {
        font-size: 0.875rem;
        color: var(--text-secondary);
    }
    
    /* =========================================================
       PAGINATION
       ========================================================= */
    
    .pagination-bar {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        gap: 1rem;
        padding-top: 1.5rem;
        border-top: 1px solid var(--border-color);
    }
    
    .pagination-container {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: center;
        gap: 0.5rem;
        padding-top: 1rem;
        border-top: 1px solid var(--border-color);
    }
    
    .pagination-info {
        font-size: 0.875rem;
        color: var(--text-secondary);
    }
    
    .pagination-controls {
        display: flex;
        gap: 0.5rem;
    }
    
    /* =========================================================
       BUTTONS
       ========================================================= */
    
    .btn {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        color: var(--text-primary);
        padding: 0.5rem 1rem;
        border-radius: var(--radius-sm);
        font-size: 0.875rem;
        font-weight: 500;
        cursor: pointer;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        gap: 0.4rem;
        text-decoration: none;
    }
    
    .btn:hover:not(:disabled) {
        background-color: var(--accent-color);
        color: #fff;
        border-color: var(--accent-color);
    }
    
    .btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
    
    .btn.active {
        background-color: var(--accent-color);
        color: #fff;
        border-color: var(--accent-color);
    }
    
    /* =========================================================
       STATISTICS / ANALYTICS
       ========================================================= */
    
    .stats-section,
    .analytics-section {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        padding: 2.5rem;
        margin-bottom: 2.5rem;
        box-shadow: var(--shadow-subtle);
    }
    
    .stats-metrics-grid,
    .analytics-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
        justify-content: center;
    }
    
    .metric-card,
    .stat-card {
        background-color: var(--surface-alt);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        padding: 1.5rem;
    }
    
    .metric-card {
        text-align: center;
    }
    
    .metric-title,
    .stat-label {
        font-size: 0.85rem;
        color: var(--text-secondary);
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 0.5rem;
    }
    
    .metric-value,
    .stat-value {
        font-family: var(--font-serif);
        font-size: 2.25rem;
        font-weight: 700;
        color: var(--accent-color);
    }
    
    .metric-note,
    .stat-subtext {
        font-size: 0.8rem;
        color: var(--accent-color);
        margin-top: 0.25rem;
        font-weight: 500;
    }
    
    .stat-subtext {
        color: var(--text-secondary);
        font-weight: normal;
    }
    
    .breakdown-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
        gap: 2rem;
        margin-bottom: 2rem;
        justify-content: center;
    }
    
    .breakdown-card {
        background-color: var(--surface-alt);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        padding: 1.5rem;
    }
    
    .breakdown-card h4,
    .stats-breakdown-box h4 {
        font-family: var(--font-serif);
        font-size: 1.25rem;
        margin-bottom: 1rem;
    }
    
    .stats-breakdown-box {
        background-color: var(--surface-alt);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        padding: 1.75rem;
        margin-bottom: 2em;
    }
    
    .stat-bar-item {
        margin-bottom: 0.85rem;
    }
    
    .stat-bar-label {
        display: flex;
        justify-content: space-between;
        font-size: 0.9rem;
        margin-bottom: 0.25rem;
    }
    
    .stat-bar-track {
        width: 100%;
        height: 8px;
        background-color: var(--border-color);
        border-radius: 4px;
        overflow: hidden;
    }
    
    .stat-bar-fill {
        height: 100%;
        background-color: var(--accent-color);
        border-radius: 4px;
    }
    
    .frequency-list {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
    }
    
    .frequency-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        background-color: var(--surface-alt);
        padding: 0.75rem 1rem;
        border-radius: var(--radius-sm);
        font-size: 0.9rem;
        border: 1px solid var(--border-color);
    }
    
    .frequency-bar-bg {
        flex-grow: 1;
        margin: 0 1.5rem;
        height: 8px;
        background-color: var(--border-color);
        border-radius: 4px;
        overflow: hidden;
    }
    
    .frequency-bar-fill {
        height: 100%;
        background-color: var(--accent-color);
    }
    
    .frequent-list {
        list-style: none;
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 0.75rem;
        justify-content: center;
    }
    
    .frequent-item {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        padding: 0.5rem 0.75rem;
        border-radius: var(--radius-sm);
        font-size: 0.85rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .frequent-item span:last-child {
        font-weight: 600;
        color: var(--accent-color);
    }
    
    /* =========================================================
       MAP
       ========================================================= */
    
    .map-section {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        padding: 2.5rem;
        margin-bottom: 2.5rem;
        box-shadow: var(--shadow-subtle);
    }
    
    .interactive-map-container {
        width: 100%;
        height: 420px;
        background-color: var(--surface-alt);
        border-radius: var(--radius-md);
        border: 1px solid var(--border-color);
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-secondary);
        font-style: italic;
    }
    
    /* =========================================================
       FAQ / Q&A
       ========================================================= */
    
    .qa-section {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        padding: 2.5rem;
        margin-bottom: 2.5rem;
        box-shadow: var(--shadow-subtle);
    }
    
    .qa-list {
        display: flex;
        flex-direction: column;
        gap: 1.25rem;
    }
    
    .qa-item {
        border-bottom: 1px solid var(--border-color);
        padding-bottom: 1.25rem;
    }
    
    .qa-question {
        font-weight: 600;
        font-size: 1.05rem;
        margin-bottom: 0.5rem;
        color: var(--text-primary);
    }
    
    .qa-answer {
        color: var(--text-secondary);
        font-size: 0.95rem;
    }
    
    /* =========================================================
       PROXIMITY
       ========================================================= */
    
    .proximity-section {
        background-color: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        padding: 2.5rem;
        margin-bottom: 2.5rem;
        box-shadow: var(--shadow-subtle);
    }
    
    .proximity-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
        gap: 1.25rem;
    }
    
    .proximity-card {
        background-color: var(--surface-alt);
        border: 1px solid var(--border-color);
        padding: 1.25rem;
        border-radius: var(--radius-md);
    }
    
    .proximity-title {
        font-weight: 600;
        margin-bottom: 0.25rem;
    }
    
    .proximity-distance {
        font-size: 0.85rem;
        color: var(--accent-color);
        font-weight: 500;
    }
    
    /* =========================================================
       FOOTER
       ========================================================= */
    
    footer {
        text-align: center;
        padding: 3rem 0;
        color: var(--text-secondary);
        font-size: 0.875rem;
        border-top: 1px solid var(--border-color);
    }
    
    /* =========================================================
       OVERLAY
       ========================================================= */
    
    #overlay {
        position: absolute;
        width: 100%;
        height: 100%;
        background-color: lightgrey;
        opacity: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        transition: opacity 0.5s;
        z-index: 2000;
    }
    
    #overlay.show {
        opacity: 0.5;
    }
    
    /* =========================================================
       RESPONSIVE RULES
       ========================================================= */
    
    @media (max-width: 968px) {
        .featured-section,
        .content-sidebar-grid,
        .details-grid {
            grid-template-columns: 1fr;
        }
        
        .pagination-controls {
            display: block;
            text-align: center;
        }
    }

    .ab-viewport {
        /* height: auto !important; */
    }

    .asset-browser-widget {
        max-width: 80% !important; /* 100% */
    }

    </style>
<body>

    <div class="page-container">

        <!-- Top Breadcrumbs -->
        <nav class="breadcrumbs-nav" aria-label="Breadcrumb">
            <ol class="breadcrumbs-list">
                <?php echo $htmlPageBreadcrumbs; ?>
            </ol>
        </nav>

        <!-- Header Subheader Block -->
        <header class="page-header-block">
            <h1><?php echo $textPageTitle; ?></h1>
            <p><?php echo $textPageSubheading; ?></p>
        </header>

        <!-- Multiple Featured / Highlighted Views -->
        <section>
            <div class="featured-grid">
                <?php echo $htmlPageHighlightedViews; ?>
            </div>
        </section>
        <!-- Description & Extensive Texts + Weather Sidebar -->
        <div class="content-sidebar-grid">
            <!-- Extensive Texts -->
            <div class="extensive-text-card">
                <h3>About <?php echo $statusTextLive; ?> cameras in <?php echo $searchCurrentStageValue; ?></h3>
                <p>
                    <?php echo implode(", ", $segmentsUcwords); ?> has <?php echo $searchResultsCurrenttAllMatchesFound . " {$statusTextLive}"; ?> cameras covering the <?php echo $searchCurrentStage; ?>. The camera network in <?php echo implode(", ", array_reverse($segmentsUcwords)); ?> emphasises <?php echo $statusText; ?> cameras. Check real-time traffic and weather conditions in <?php echo $searchCurrentStageValue; ?> before your commute, travel and plan your day. All cameras update continuously. View <a href="<?php echo "{$breadcrumbsPath2}?status=1"; ?>" class="featured-link">online</a>, <a href="<?php echo "{$breadcrumbsPath2}?status=0"; ?>" class="featured-link">offline</a>, or <a href="<?php echo "{$breadcrumbsPath2}?status=2"; ?>" class="featured-link">all cameras combined (online &amp; offline)</a> in <?php echo implode(", ", $segmentsUcwords); ?>. The cameras displayed constitute <?php echo $searchResultsCurrentMaxHitRatePercentage ?> percent of <?php echo $searchResultsAllRecordsScanned; ?> cameras on record. <?php echo $textPageMostFrequentValuesDescription . implode(", ", $mostFrequentValues); ?>.
                </p>
                <p>
                    <a href="<?php echo $globalUriToEntryMap; ?>" class="featured-link">Open the live webcam map</a> to explore all public cameras in <?php echo $searchCurrentStageValue; ?>.
                </p>
                <p>
                    Notable cameras include: <?php echo $htmlPageNotableViews; ?>
                </p>
            </div>

            <!-- Sidebar Widgets -->
            <div class="sidebar-widgets">
                <!-- Local Weather Widget loaded via weather api -->
                <div class="widget-card">
                    <div class="widget-title">
                        <span>Local Weather</span>
                        <span style="font-size: 0.75rem; color: var(--accent-color);">Live Weather</span>
                    </div>
                    <div id="weather-widget-container" class="weather-content">
                        <div class="weather-temp">19°C</div>
                        <div class="weather-condition">Sunny Skies<br>Humidity: 45%</div>
                        <div class="weather-condition">Sunny Skies<br> Accomodations available for booking </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Directory Index / Cards Section with Scrollable / First, Last, Next, Previous Pagination -->
        <section class="directory-section">
            <h2 class="section-header"><?php echo ucwords(str_replace("and", "&", $statusTextLive)); ?> Cameras in <?php echo $searchCurrentStageValue; ?></h2>
            <div class="directory-grid" id="directory-container">
                <!-- Dynamic or Paginated Cards -->
                <?php echo $htmlPageDirectoryGrid; ?>
            </div>

            <!-- Pagination Bar -->
            <div class="pagination-bar">
                <div class="pagination-info">Showing records <?php echo $pageResults["from_result"]; ?>–<?php echo $pageResults["to_result"]; ?> of <?php echo $pageResults["total"]; ?> total cameras found</div>
                <div class="pagination-controls">
                    <button class="btn" id="btn-first" <?php echo $previousPageButtonDisableValue; ?>>⏮ First</button>
                    <button class="btn" id="btn-prev" <?php echo $previousPageButtonDisableValue; ?>>◀ Previous</button>
                    <button class="btn" id="btn-next" <?php echo $nextPageButtonDisableValue; ?>>Next ▶</button>
                    <button class="btn" id="btn-last" <?php echo $nextPageButtonDisableValue; ?>>Last ⏭</button>
                </div>
            </div>
        </section>

        <!-- Listed Categories -->
        <section>
            <div class="stats-breakdown-box">
                <h4><?php echo ucwords($searchFollowingStage); ?> Distributions</h4>
                <ul class="frequent-list" id="frequent-cities-list">
                    <?php echo $htmlPageBreakDownList; ?>
                </ul>
            </div>
        </section>

        <!-- Statistics and Analysis Section -->
        <section class="stats-section">
            <h2 class="section-header">Dataset Statistics & Analysis - <?php echo $searchCurrentStageValue; ?></h2>
            <div class="stats-metrics-grid">
                <div class="metric-card">
                    <div class="metric-value" id="metric-scanned"><?php echo $usFormatter->format($searchResultsCurrent["statistics"]["datasetMetrics"]["totalRecordsScanned"]); ?></div>
                    <div class="metric-label">Total Records Scanned</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value" id="metric-matches"><?php echo $searchResultsCurrenttAllMatchesFound ?></div>
                    <div class="metric-label">Total Matches Found</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value" id="metric-hitrate"><?php echo $searchResultsCurrentMaxHitRatePercentage ?>%</div>
                    <div class="metric-label">Match Hit Rate Percentage</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value" id="metric-priority"><?php echo $usFormatter->format($searchResultsCurrent["statistics"]["priorityBreakdown"]["priority1Percentage"]) ?>%</div>
                    <div class="metric-label">Priority 1 Coverage</div>
                </div>
            </div>

            <div class="breakdown-grid">
                <!-- Frequent <?php echo ucwords($searchFollowingStage); ?> Breakdown -->
                <div class="breakdown-card">
                    <h4>Frequent <?php echo ucwords($searchFollowingStage); ?> Distributions</h4>
                    <?php echo $htmlPageStatBarList; ?>
                </div>
            </div>
        </section>

        <!-- Header & Sub-header Area -->
        <section class="page-header-section" style="display:none;">
            <h1 class="page-title"></h1>
            <p class="page-subtitle"></p>
        </section>

        <!-- Map Section -->
        <section class="map-section">
            <h2 class="section-header">Geographic Location - <?php echo implode(" · ", count($segmentsUcwords) > 1 ? array_slice(array_reverse($segmentsUcwords), 0, -1, true) : array_reverse($segmentsUcwords)); ?></h2>
            <p class="section-subheader">Click on the map to show all cameras in <?php echo $searchCurrentStageValue; ?> on the Global Map.</p>
            <div id="interactive-map" class="interactive-map-container">
                <div id="overlay">
                    <p>Show map</p>
                </div>
                [ Interactive Map Loaded via GIS Integration ]
            </div>
        </section>

        <!-- FAQ Section -->
        <section class="qa-section">
            <h2 class="section-header">Frequently Asked Questions</h2>
            <div class="qa-list">
                <?php echo $htmlPageFAQs; ?>
            </div>
        </section>

        <!-- Footer -->
        <footer>
            <p>&copy; <?php echo date("Y"); ?> <?php echo $applicationName; ?>. All available camera and broadcasting feeds are aggregated from transportation agencies, weather services, and other public sources worldwide. Operated by <?php echo $applicationName; ?>. We do not operate or own any of the cameras or broadcasts ourselves.</p>
        </footer>

    </div>

    <!-- JavaScript Implementation matching specifications -->
    <script>
        /**
         * Third-Party API Simulation Layer
         */

        // 1. Weather API Simulation: 3rdpartyweatherapi
        function initWeatherAPI() {
            const weatherContainer = document.getElementById('weather-widget-container');
            // Simulated live fetch response
            setTimeout(() => {
                weatherContainer.innerHTML = `
                    <div class="app-container" id="weatherApp">
        <!-- Search & Control -->
        <div class="search-bar-container">
            <div class="search-box">
                <input type="text" id="citySearchInput" placeholder="Search city or location..." autocomplete="off">
            </div>
            <div class="search-results" id="searchResults"></div>
        </div>

        <!-- Scrollable Dynamic Dashboard -->
        <div class="content-scroll" id="contentScroll">
            <div class="status-state">Initializing Weather Engine...</div>
        </div>

        <div class="embed-badge">
            Powered by Open-Meteo Free APIs
        </div>
    </div>

                `;
            window.weatherWidget = new OpenMeteoBrowserWidget('weatherApp', {
                    name: `<?php echo $arrayCity; ?>`,
                    country: `<?php echo $arrayCountry; ?>`,
                    admin1: `<?php echo $arrayRegion; ?>`,
                    latitude: <?php echo $arrayLatitude; ?>,
                    longitude: <?php echo $arrayLongitude; ?>
                });
            }, 500);
        }

        // 2. Map API Simulation: 3rdpartymap
        function initMapAPI() {
            setTimeout(() => {
                                // GOOGLE TILE URL TEMPLATE
                const GOOGLE_URL =
                "https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}";

                // GOOGLE SUBDOMAINS
                const SUBDOMAINS = ["mt0", "mt1", "mt2", "mt3"];

                // MAP INIT
                const map = new maplibregl.Map({
                    container: "interactive-map",
                    style: {
                        version: 8,
                        sources: {
                            googleTiles: {
                                type: "raster",
                                tiles: SUBDOMAINS.map(
                                s => GOOGLE_URL.replace("{s}", s)
                                ),
                                tileSize: 256,
                                maxzoom: 22
                            }
                        },
                        layers: [
                        {
                            id: "google-layer",
                            type: "raster",
                            source: "googleTiles"
                        }
                        ]
                    },
                    center: [<?php echo !is_null($arrayLongitude) ? $arrayLongitude : "N/A"; ?>, <?php echo !is_null($arrayLatitude) ? $arrayLatitude : "N/A"; ?>],
                    zoom: <?php echo $zoom; ?>,
                    attributionControl: true
                });

                // MARKER
                new maplibregl.Marker()
                .setLngLat([<?php echo !is_null($arrayLongitude) ? $arrayLongitude : "N/A"; ?>, <?php echo !is_null($arrayLatitude) ? $arrayLatitude : "N/A"; ?>])
                .addTo(map);

                // OVERLAY BEHAVIOR
                const overlay = document.getElementById("overlay");
                const mapDiv = document.getElementById("interactive-map");

                mapDiv.addEventListener("mouseover", () => overlay.classList.add("show"));
                mapDiv.addEventListener("mouseout", () => overlay.classList.remove("show"));

                // CLICK REDIRECT
                mapDiv.addEventListener("click", () => {
                    window.location.href = "<?php echo $globalUriToEntryMap; ?>";
                });
            }, 600);
        }

        document.getElementById('btn-next').addEventListener('click', () => {
            window.location.href = "<?php echo "{$breadcrumbsPath2}$statusUrlParameter&page=" . ($pageResults["last_page"] == $pageResults["current_page"] ? $pageResults["last_page"] : $pageResults["current_page"] + 1) . "#directory-container"; ?>";
        });

        document.getElementById('btn-last').addEventListener('click', () => {
            window.location.href = "<?php echo "{$breadcrumbsPath2}$statusUrlParameter&page={$pageResults["last_page"]}#directory-container"; ?>";
        });

        document.getElementById('btn-prev').addEventListener('click', () => {
            window.location.href = "<?php echo "{$breadcrumbsPath2}$statusUrlParameter&page=" . ($pageResults["first_page"] == $pageResults["current_page"] ? $pageResults["first_page"] : $pageResults["current_page"] - 1) . "#directory-container"; ?>";
        });

        document.getElementById('btn-first').addEventListener('click', () => {
            window.location.href = "<?php echo "{$breadcrumbsPath2}$statusUrlParameter&$status#directory-container"; ?>";
        });

        // Initialize APIs on window load
        window.addEventListener('DOMContentLoaded', () => {
            initWeatherAPI();
            initMapAPI();
        });
    </script>
</body>
</html>