<?php

    error_reporting(0);

    $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';
    $sourceExplore = $sourceDir . "/../accessible_explore_export.csv";

    $ipApiComDataDir = $baseDir . '/v/home/databases/central/assets/data/internet/ipAddresses/ip-api.com';
    $ipApiComMappingFile = $ipApiComDataDir . '/data.csv';
 
    $db = new CSVDatabase($sourceDir, $idName = "internal_id");
    
    $internalId = $_GET["internal_id"] ? strtolower($_GET["internal_id"]) : null;
    $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";

    $array = $internalId ? $db->getEntryById($internalId) : [];

    if (empty($array)) {
        // Handle missing entry appropriately if needed
        // $array = [];
        header('HTTP/2 404');
        exit;
    }

    // 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 = "$REDIRECT_ln-$REDIRECT_co";
    $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";

    $breadcrumbsPath0 = "";
    $breadcrumbsPath1 = "$breadcrumbsPath0/$locale";
    $breadcrumbsPath1Canoncial = "$breadcrumbsPath0/$locale";
    $breadcrumbsPath2 = "$breadcrumbsPath1";
    $breadcrumbsPath2Canoncial = "$breadcrumbsPath1Canoncial";

    $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";

    $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;

    $availabilityStatus = $array["status"] == 1 ? "online" : "offline";

    // 2. Determine the correct entry name/slug (Optimized with null coalescing)
    $computedNameOriginal = 
        !is_null($arrayName) 
        ? $arrayName
        : ltrim(($arrayCity ? $arrayCity : '') . ($arrayRegion ? " · " . $arrayRegion : '') . ($arrayCountry ? " · " . $arrayCountry : ''), ' ,');

    $computedNameOriginalUrl = strtolower(trim(generate_seo_slug($computedNameOriginal)));

    // 3 & 4. Redirect check (Performed immediately to avoid redundant processing)
    $expectedPath = "$breadcrumbsPath2/" . strtolower(trim(generate_seo_slug($arrayContinent)))  . "/" . strtolower(trim(generate_seo_slug($arrayCountry))) . "/" . strtolower(trim(generate_seo_slug($arrayRegion))) . "/" . strtolower(trim(generate_seo_slug($arrayCity))) . (!empty($arrayName) ? "-" . generate_seo_slug($arrayName) : "") . ".view." . $arrayInternalId;

    $cannoncialUrl = "$currentEndpoint$breadcrumbsPath2Canoncial/" . $computedNameOriginalUrl . "/" . $arrayInternalId;

    if ($requestUri !== $expectedPath) {
        header("Location: " . $expectedPath, true, 301);
        exit;
    }

    $currentTimestamp = date('Y-m-d\\TH:i:s\\Z');

    /**
     * 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;
        }
    }

    $count = 0;
    $suggestionsNeeded = 10;
    $suggestionsNeededSimilarViews = 6;
    $suggestionsNeededProximityViews = 4;
    $searchResults = [];
    $searchResultsIds = [];
    $totalSearchResults = 0;

    $htmlPageSuggestedViews = "";
    $htmlPageSuggestedProximityViews = "";
    $htmlPageCategoriesList = "";
    $htmlPageFAQs = "";
    $htmlPageBreadcrumbs = "";
    $arrayLocationChangesText = "";

    /*
    for ($decimal = 6; $decimal >= 0; $decimal--) {
        $latRounded = round((float)($arrayLatitude ?? 0), $decimal);
        $lonRounded = round((float)($arrayLongitude ?? 0), $decimal);

        $searchResultsCurrent = $db->searchEntries("latitude:{$latRounded} _longitude:{$lonRounded} _status:1", ["latitude", "longitude", "status"]);
        $totalSearchResults += count($searchResultsCurrent);

        foreach ($searchResultsCurrent as $match) {
            if (isset($match["internal_id"]) && ($match["internal_id"] === $arrayInternalId || in_array($match["internal_id"], $searchResultsIds))) {
                continue;
            }

            $searchResults[] = $match;
            $searchResultsIds[] = $match["internal_id"];
            $count++;

            if ($count >= $suggestionsNeeded) {
                break;
            }
        }
            
        // Stop reducing decimal precision once matching records are populated
        if (!empty($searchResults) && count($searchResults) >= $suggestionsNeeded) {
            break;
        }
    }
    */

    $queries = [
        // 'latitude:"' . round((float)($arrayLatitude ?? 0), 3) . '" _longitude:"' . round((float)($arrayLongitude ?? 0), 3) . '" _status:1',
        'continent:"' . $arrayContinent . '" country:"' . $arrayCountry . '" region:"' . $arrayRegion . '" city:"' . $arrayCity . '" status:1',
        'continent:"' . $arrayContinent . '" country:"' . $arrayCountry . '" region:"' . $arrayRegion . '" status:1',
        'continent:"' . $arrayContinent . '" country:"' . $arrayCountry . '" status:1',
        'continent:"' . $arrayContinent . '" status:1',
        // 'latitude:"' . round((float)($arrayLatitude ?? 0), 0) . '" _longitude:"' . round((float)($arrayLongitude ?? 0), 0) . '" _status:1',
        ];

    foreach ($queries as $query) {
        
        /* Use to simulate similar views
         * $searchResultsCurrent = array_merge($searchResults, $db->searchEntries($query, $fields = ["continent", "country", "region", "city", "status", "latitude", "longitude", "notes_name_en"], $returnStats = false, $statsColumns = [], $excludeStatsColumns = [], $includeAllValues = false, $returnColumns = ["continent", "country", "region", "city", "status", "latitude", "longitude", "notes_name_en"], $includeResultsInStats = false));
         */
        $searchResultsCurrent = $db->searchEntries($query, $fields = ["continent", "country", "region", "city", "status", "latitude", "longitude", "notes_name_en"], $returnStats = false, $statsColumns = [], $excludeStatsColumns = [], $includeAllValues = false, $returnColumns = ["continent", "country", "region", "city", "status", "latitude", "longitude", "notes_name_en"], $includeResultsInStats = false);

        $totalSearchResults += count($searchResultsCurrent);

        foreach ($searchResultsCurrent as $match) {
            if (isset($match["internal_id"]) && ($match["internal_id"] === $arrayInternalId || in_array($match["internal_id"], $searchResultsIds))) {
                continue;
            }

            $searchResults[] = $match;
            $searchResultsIds[] = $match["internal_id"];
            $count++;

            if ($count >= $suggestionsNeeded) {
                break;
            }
        }
            
        // Stop reducing decimal precision once matching records are populated
        if (!empty($searchResults) && count($searchResults) >= $suggestionsNeeded) {
            break;
        }
    }

    
    $arrayIpAddress = !empty($array["access_rtsp_access_point_ip_current"]) ? $array["access_rtsp_access_point_ip_current"] : $array["access_image_access_point_ip_current"];

    if (!empty($arrayIpAddress) && !is_null(valueExistsInCsv($ipApiComMappingFile, "ip_address", $arrayIpAddress))) {
        $csvLine = getCsvLine($ipApiComMappingFile, $arrayIpAddress, $key = "ip_address");
        $arrayLocationChangesCount = count(explode("|", $csvLine["mapping_patterns"]));

        if ($arrayLocationChangesCount == 1) {
            $arrayLocationChangesText = ", has never changed its geographical location";
        } else if ($arrayLocationChangesCount > 1){
            $arrayLocationChangesText = ", has changed its geographical location $arrayLocationChangesCount times";
        }
    }

    $textPageDescriptionFallback = "Live webcam at {$arrayCity}: {$arrayRegion}, {$arrayCountry} in {$arrayCity}: {$arrayRegion}, {$arrayCountry}. Watch real-time conditions at {$arrayCity}: {$arrayRegion}, {$arrayCountry}. Explore more cameras from around the world on {$requestHostWithoutWww}.\n{$arrayCity}: {$arrayRegion}, {$arrayCountry} is a camera in {$arrayCity}: {$arrayRegion}, {$arrayCountry}, positioned at {$arrayLatitude}°, {$arrayLongitude}°. It looks out over {$arrayCity} in {$arrayContinent}, refreshes continuously{$arrayLocationChangesText} and is currently {$availabilityStatus}. {$totalSearchResults} other live cameras are located nearby.";

    $textPageDescription = !is_null($arrayDescription) 
        ? $arrayDescription
        : $textPageDescriptionFallback;

    if (count($searchResults) > 0) {
        // Safely pick up to 3 random keys without throwing warnings if results < 3
        $sampleKeys = count($searchResults) >= $suggestionsNeededSimilarViews ? array_rand($searchResults, $suggestionsNeededSimilarViews) : array_keys($searchResults);
        if (!is_array($sampleKeys)) {
            $sampleKeys = [$sampleKeys];
        }

        foreach ($sampleKeys as $key) {
            if (empty($searchResults[$key])) continue;

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


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

            $suggestionSlug = "$breadcrumbsPath2/" . 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($searchResults[$key]["notes_name_en"]) ? "-" . generate_seo_slug($searchResults[$key]["notes_name_en"]) : "") . ".view." . $searchResults[$key]["internal_id"];
            $distance = round(calculateDistance($arrayLatitude, $arrayLongitude, $searchResults[$key]["latitude"], $searchResults[$key]["longitude"], 'K'), 2);

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

            // $htmlPageSuggestedViews .= "<a href=\"{$suggestionSlug}\" class=\"suggestion-card\">\n" . 
            $htmlPageSuggestedViews .= "<a href=\"{$suggestionSlug}\" class=\"suggestion-card\">\n" . 
                 "                    <img src=\"{$globalUriToImageArchive}/{$searchResults[$key]["internal_id"]}{$imageArchiveLatestExtension}\" alt=\"{$suggestionNameOriginal}\" class=\"suggestion-image\">\n" . 
                 "                    <div class=\"suggestion-content\">\n" . 
                 "                        <h3 class=\"suggestion-title\">{$suggestionNameOriginal}</h3>\n" . 
                 "                        <p style=\"color: var(--text-secondary); font-size: 0.9rem;\">{$suggestionDescription}</p>\n" . 
                 "                    </div>" . 
                 "                </a>\n                ";

            $htmlPageSuggestedProximityViews .= "<div alt-link=\"{$suggestionSlug}\" class=\"proximity-card\">\n" . 
                 "                    <div class=\"proximity-title\">{$suggestionNameOriginal}</div>\n" . 
                 "                    <div class=\"proximity-distance\">{$suggestionDescription}</div>\n" . 
                 "                </div>\n                ";

        }
    }

    /* Activate when results differ
    if (count($searchResults) > 0) {
        // Safely pick up to 3 random keys without throwing warnings if results < 3
        $sampleKeys = count($searchResults) >= $suggestionsNeededProximityViews ? array_rand($searchResults, $suggestionsNeededProximityViews) : array_keys($searchResults);
        if (!is_array($sampleKeys)) {
            $sampleKeys = [$sampleKeys];
        }

        foreach ($sampleKeys as $key) {
            if (empty($searchResults[$key])) continue;

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


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

            $suggestionSlug = "$breadcrumbsPath2/" . 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($searchResults[$key]["notes_name_en"]) ? "-" . generate_seo_slug($searchResults[$key]["notes_name_en"]) : "") . ".view." . $searchResults[$key]["internal_id"];

            $distance = round(calculateDistance($arrayLatitude, $arrayLongitude, $searchResults[$key]["latitude"], $searchResults[$key]["longitude"], 'K'), 2);

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

            $htmlPageSuggestedProximityViews .= "<div alt-link=\"{$suggestionSlug}\" class=\"proximity-card\">\n" . 
                 "                    <div class=\"proximity-title\">{$suggestionNameOriginal}</div>\n" . 
                 "                    <div class=\"proximity-distance\">{$suggestionDescription}</div>\n" . 
                 "                </div>\n                ";
        }
    }
    */

    if (!is_null(valueExistsInCsv($sourceExplore, "internal_id", $arrayInternalId))) {
        $arrayExplore = getCsvLine($sourceExplore, $arrayInternalId, $key = "internal_id");

        foreach (json_decode($arrayExplore["categories"], true) as $category) {
            $categoryUpperCase = ucwords($category);

            $htmlPageCategoriesList .= "                            <a href=\"$globalUriToBrowse?term=" . rawurlencode('categories:"' . $category . '"') . "\" class=\"category-tag\">{$categoryUpperCase}</a>";
        }
        
        $sourceTypeUpperCase = ucwords($arrayExplore["source_type"]);

        $htmlPageCategoriesList .= "                            <a href=\"$globalUriToBrowse?term=" . rawurlencode('source_type:"' . $arrayExplore["source_type"] . '"' ) . "\" class=\"category-tag\">{$sourceTypeUpperCase}</a>";
    }

    $shareUrlTwitter = 'https://twitter.com/intent/tweet?' . http_build_query([
        'text' => 'Watch live ' . $arrayRegion . " in " . $arrayCountry, 
        'url'  => $currentUrl
    ]);

    $shareUrlFacebook = 'https://www.facebook.com/sharer/sharer.php?' . http_build_query([
        'u'  => $currentUrl
    ]);

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


    // $textPageMetaTitle = "{$arrayCity}: {$arrayRegion}, {$arrayCountry} Live Webcam -  {$arrayContinent} | $applicationName";
    $textPageMetaTitle = "{$arrayCity}: {$arrayRegion}, {$arrayCountry} Live Webcam: Real-Time Views & Conditions in {$arrayContinent} | $applicationName";
    $textPageMetaDescription = (mb_strlen($textPageDescriptionFallback) > 155) ? mb_substr($textPageDescriptionFallback, 0, 152) . '...' : $textPageDescriptionFallback;
    $textPageMetaImage = "";
    $textPageMetaVideo = "";

    $jsonFAQs = [
		"@context" => "https://schema.org", 
		"@type" => "FAQPage", 
		"mainEntity" => 
		[[
			"@type" => "Question", 
			"name" => "How often does this camera update?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "This camera provides real-time access and therefore updates continuously."
			]
		],
		[
			"@type" => "Question", 
			"name" => "Is this camera live now?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "Yes — the feed is provided directly from the public source in real time. If the camera is offline, the page will indicate this."
			]
		],
		[
			"@type" => "Question", 
			"name" => "May I watch this camera on my phone?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "Yes — every camera on {$requestHostWithoutWww} works on mobile browsers. Open the page on your phone and the live feed will play directly."
			]
		],
		[
			"@type" => "Question", 
			"name" => "Why is the camera offline?", 
			"acceptedAnswer" => 
			[
				"@type" => "Answer", 
				"text" => "Cameras occasionally go offline for maintenance, weather, or network issues. The page will indicate the camera is offline and we re-check the feed automatically."
			]
		]]
	];

	$jsonHowTo = [
		"@context" => "https://schema.org", 
		"@type" => "HowTo", 
		"name" => "How to embed {$arrayCity}: {$arrayRegion}, {$arrayCountry} on your website", 
		"description" => "Embed the {$arrayCity}: {$arrayRegion}, {$arrayCountry} live camera feed on any web page using a single iframe tag.", 
		"step" => 
		[[
			"@type" => "HowToStep", 
			"position" => 1,"name" => "Copy the embed code", 
			"text" => "Scroll to the \"Embed Options\" area. Choose between Viewer, Map, Availability, Suggestions, Weather and click the \"Embed\" button on the {$arrayCity}: {$arrayRegion}, {$arrayCountry} camera page. Then copy the iframe snippet."
		],
		[
			"@type" => "HowToStep", 
			"position" => 2,
			"name" => "Paste into your HTML", 
			"text" => "Paste the iframe tag wherever you want the camera to appear in your HTML."
		],[
			"@type" => "HowToStep", 
			"position" => 3,
			"name" => "Adjust width and height", 
			"text" => "Optionally change the width and height attributes to fit your layout. The iframe is responsive by default at 16:9 aspect ratio."
		]],
		"tool" => 
		[[
			"@type" => "HowToTool", 
			"name" => "A web page or HTML editor"
		]]
	];
	
    // 1. Define the segments in an array
    $segments = [
        rtrim($globalUriToHome, '/'),
        strtolower(trim(generate_seo_slug($arrayContinent))),
        strtolower(trim(generate_seo_slug($arrayCountry))),
        strtolower(trim(generate_seo_slug($arrayRegion))),
        strtolower(trim(generate_seo_slug($arrayCity)))
    ];

	$jsonBreadcrumbs = [
		"@context" => "https://schema.org", 
		"@type" => "BreadcrumbList", 
		"itemListElement" => 
		[[
			"@type" => "ListItem", 
			"position" => 1,
			"name" => "Home", 
			"item" => "$currentEndpoint$breadcrumbsPath1"
		],
		[
			"@type" => "ListItem", 
			"position" => 2,
			"name" => !is_null($arrayContinent) ? $arrayContinent : "N/A", 
			"item" => implode('/', array_slice($segments, 0, 2))
		],
		[
			"@type" => "ListItem", 
			"position" => 3,
			"name" => !is_null($arrayCountry) ? $arrayCountry : "N/A", 
			"item" => implode('/', array_slice($segments, 0, 3))
		],
		[
			"@type" => "ListItem", 
			"position" => 4,
			"name" => !is_null($arrayRegion) ? $arrayRegion : "N/A", 
			"item" => implode('/', array_slice($segments, 0, 4))
		],
		[
			"@type" => "ListItem", 
			"position" => 5,
			"name" => !is_null($arrayCity) ? $arrayCity : "N/A", 
			"item" => implode('/', array_slice($segments, 0, 5))
		],
		[
			"@type" => "ListItem", 
			"position" => 6,
			"name" => "$computedNameOriginal"
		]]
	];

	/*
	// temporary override to check google ranking impact
	$jsonBreadcrumbs = [
		"@context" => "https://schema.org", 
		"@type" => "BreadcrumbList", 
		"itemListElement" => 
		[[
			"@type" => "ListItem", 
			"position" => 1,
			"name" => "Home", 
			"item" => "$currentEndpoint$breadcrumbsPath1"
		],
		[
			"@type" => "ListItem", 
			"position" => 2,
			"name" => !is_null($arrayContinent) ? $arrayContinent : "N/A", 
			"item" => "$globalUriToBrowse?term=" . rawurlencode('continent:"' . $arrayContinent. '"')
		],
		[
			"@type" => "ListItem", 
			"position" => 3,
			"name" => !is_null($arrayCountry) ? $arrayCountry : "N/A", 
			"item" => "$globalUriToBrowse?term=" . rawurlencode('continent:"' . $arrayContinent . '" country:"' . $arrayCountry. '"')
		],
		[
			"@type" => "ListItem", 
			"position" => 4,
			"name" => !is_null($arrayRegion) ? $arrayRegion : "N/A", 
			"item" => "$globalUriToBrowse?term=" . rawurlencode('continent:"' . $arrayContinent . '" country:"' . $arrayCountry . '" region:"' . $arrayRegion. '"')
		],
		[
			"@type" => "ListItem", 
			"position" => 5,
			"name" => !is_null($arrayCity) ? $arrayCity : "N/A", 
			"item" => "$globalUriToBrowse?term=" . rawurlencode('continent:"' . $arrayContinent . '" country:"' . $arrayCountry . '" region:"' . $arrayRegion . '" city:"' . $arrayCity. '"')
		],
		[
			"@type" => "ListItem", 
			"position" => 6,
			"name" => "$computedNameOriginal"
		]]
	];
	*/

	$jsonGeneral = [
		"@context" => "https://schema.org", 
		"@type" => "VideoObject", 
		"@id" => "$currentUrl", 
		"name" => $computedNameOriginal, 
		"description" => $textPageDescription, 
		"uploadDate" => $currentTimestamp, 
		"thumbnailUrl" => "$globalUriToImageArchive/$arrayInternalId$imageArchiveLatestExtension", 
		"url" => $currentUrl, 
		"contentUrl" => $currentUrl, 
		"embedUrl" => "$globalUriToEmbeds/viewer/$arrayInternalId", 
		"contentLocation" => 
		[
			"@type" => "Place", 
			"name" => "$arrayCity, $arrayRegion, $arrayCountry", 
			"geo" => 
		    [
				"@type" => "GeoCoordinates", 
				"latitude" => !is_null($arrayLatitude) ? (float)$arrayLatitude : 0,
				"longitude" => !is_null($arrayLongitude) ? (float)$arrayLongitude : 0
			],"address" => 
			[
				"@type" => "PostalAddress", 
				"addressLocality" => $arrayCity, 
				"addressRegion" => $arrayRegion, 
				"addressCountry" => $arrayCountry,
			]
		],
		"publication" => 
		[
			"@type" => "BroadcastEvent", 
			"isLiveBroadcast" => true,
			"startDate" => $currentTimestamp
		],
		"identifier" => $arrayInternalId
	];

    foreach ($jsonFAQs["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 ($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               ";
        }
    }

?>
<!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="video.other">
    <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:video" content="<?php echo $currentUrl; ?>">
    <meta property="og:video:url" content="<?php echo $currentUrl; ?>">
    <meta property="og:video:secure_url" content="<?php echo $currentUrl; ?>">
    <meta property="og:video:type" content="text/html">
    <meta property="og:video:width" content="1280">
    <meta property="og:video:height" content="720">
    <meta property="og:site_name" content="<?php echo $applicationName; ?>">
    <meta name="twitter:card" content="player">
    <meta name="twitter:title" content="<?php echo $textPageMetaTitle; ?>">
    <meta name="twitter:description" content="<?php echo $textPageMetaDescription; ?>">
    <meta name="twitter:image" content="<?php echo "$globalUriToImageArchive/$arrayInternalId$imageArchiveLatestExtension"; ?>">
    <meta name="twitter:player" content="<?php echo $currentUrl; ?>">
    <meta name="twitter:player:width" content="1280">
    <meta name="twitter:player:height" content="720">

    <!-- Schema.org Structured Data for AI Agents & SEO -->
    <script type="application/ld+json"><?php echo json_encode($jsonGeneral, 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, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?></script>
    <script type="application/ld+json"><?php echo json_encode($jsonHowTo, 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">

    <!-- Chart.js Core Library -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

    <link href="/assets/css/telemetry.css" rel="stylesheet">
    <link href="/assets/css/weather.css" rel="stylesheet">
    <link href="/assets/css/availability.css" rel="stylesheet">
    <link href="/assets/css/suggestions.css" rel="stylesheet">
    <link href="/assets/css/viewer.css" rel="stylesheet">

    <script src="/assets/js/weather.js"></script>
    <script src="/assets/js/availability.js"></script>
    <script src="/assets/js/suggestions.js"></script>
    <script type="module" src="/assets/js/viewer.js"></script>
    <script type="module" src="/assets/js/telemetry.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
    <script src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1"></script>
    <link rel="stylesheet" href="https://www.cestla.ch/assets/js/SwiftPlayer/player.css">

    <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;
        }

        /* Layout Container - Responsive for TV, Computer, Tablet, Phone */
        .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 1rem;
            }
        }

        /* Top 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;
        }

        /* Viewer / Player Area */
        .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;
        }

        .mock-player-content {
            text-align: center;
            padding: 2rem;
        }

        .mock-player-content h2 {
            font-family: var(--font-serif);
            font-size: 2rem;
            margin-bottom: 0.5rem;
            color: var(--text-primary);
        }

        .mock-player-content p {
            color: var(--text-secondary);
            font-size: 0.95rem;
        }

        /* Details Area */
        .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;
        }

        @media (max-width: 968px) {
            .details-grid {
                grid-template-columns: 100%;
            }
        }

        .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;
        }

        .categories-list {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
            margin-bottom: 1.5rem;
        }

        .category-tag {
            background-color: var(--surface-alt);
            color: var(--text-primary);
            padding: 0.25rem 0.75rem;
            border-radius: var(--radius-sm);
            font-size: 0.8rem;
            text-decoration: none;
            border: 1px solid var(--border-color);
            transition: var(--transition);
        }

        .category-tag:hover {
            border-color: var(--accent-color);
            color: var(--accent-color);
        }

        .details-title {
            font-family: var(--font-serif);
            font-size: clamp(2rem, 3vw, 3rem);
            font-weight: 700;
            line-height: 1.15;
            margin-bottom: 1rem;
        }

        .details-description {
            color: var(--text-secondary);
            font-size: 1.05rem;
            margin-bottom: 2rem;
        }

        /* Sidebar Widgets (Weather, Availability, Share, Embed) */
        .sidebar-widgets {
            display: flex;
            flex-direction: column;
            gap: 1.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 Widget */
        .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;
        }

        /* Availability Widget */
        .availability-status {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 500;
            font-size: 0.95rem;
            color: #2e7d32;
        }

        .availability-status.busy {
            color: #c62828;
        }

        .status-dot {
            width: 10px;
            height: 10px;
            background-color: currentColor;
            border-radius: 50%;
            display: inline-block;
            box-shadow: 0 0 0 3px rgba(46, 125, 50, 0.15);
        }

        /* Share & Embed Buttons */
        .share-buttons, .embed-options {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
        }

        .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 {
            background-color: var(--accent-color);
            color: #fff;
            border-color: var(--accent-color);
        }

        .btn-primary {
            background-color: var(--accent-color);
            color: #fff;
            border-color: var(--accent-color);
        }

        .btn-primary:hover {
            background-color: var(--accent-hover);
        }

        /* Map Section */
        .map-section {
            background-color: var(--surface-color);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-lg);
            padding: 2rem;
            margin-bottom: 2.5rem;
            box-shadow: var(--shadow-subtle);
        }

        .section-header {
            font-family: var(--font-serif);
            font-size: 2rem;
            margin-bottom: 1.5rem;
        }

        .interactive-map-container {
            width: 100%;
            /* height: 400px; */
            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;
        }

        /* Similar Suggestions Area */
        .suggestions-section {
            margin-bottom: 2.5rem;
        }

        .suggestions-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 1.5rem;
        }

        .suggestion-card {
            background-color: var(--surface-color);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-md);
            overflow: hidden;
            box-shadow: var(--shadow-card);
            transition: var(--transition);
            text-decoration: none;
            color: inherit;
            display: flex;
            flex-direction: column;
        }

        .suggestion-card:hover {
            transform: translateY(-4px);
            box-shadow: var(--shadow-subtle);
            border-color: var(--accent-color);
        }

        .suggestion-image {
            width: 100%;
            aspect-ratio: 16 / 10;
            background-color: var(--surface-alt);
            object-fit: cover;
        }

        .suggestion-content {
            padding: 1.25rem;
        }

        .suggestion-title {
            font-family: var(--font-serif);
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        /* Question & Answer Area */
        .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: 1rem;
        }

        .qa-item {
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 1rem;
        }

        .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 Suggestions Area */
        .proximity-section {
            background-color: var(--surface-alt);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-lg);
            padding: 2.5rem;
            margin-bottom: 2.5rem;
        }

        .proximity-grid {
            /*
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
            */
            display: flex;
            justify-content: center;
            /* max-width: 80vw; */
            margin: auto;
            gap: 1.25rem;
        }

        .proximity-card {
            background-color: var(--surface-color);
            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 {
            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;
        }
        
        /*
        .ab-viewport {
            height: auto !important;
        }
        */

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

    </style>
</head>
<body>

    <div class="page-container">

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

        <!-- Viewer / Player Area -->
        <section class="viewer-section">
            <div id="media-viewer-container" class="media-container">
                <!-- Initialised via JS third-party API -->
                <div class="mock-player-content">
                    <h2>Loading Media Viewer...</h2>
                    <p>Connecting to stream container</p>
                </div>
            </div>

            <!-- Details Section -->
            <div class="details-section">
                <div class="details-grid">
                    <div>
                        <!-- Location as Breadcrumbs & Metadata -->
                        <div class="details-meta-box">
                            <div class="meta-item">
                                <span>📍</span> <?php echo !is_null($arrayRegion) ? $arrayRegion : "N/A"; ?>, <?php echo !is_null($arrayCountry) ? $arrayCountry : "N/A"; ?>
                            </div>
                            <div class="meta-item">
                                <span>🌐</span> <span id="item-coordinates"><?php $latFormatted = $arrayLatitude !== null ? abs($arrayLatitude) . '° ' . ($arrayLatitude < 0 ? 'S' : 'N') : 'N/A'; $lonFormatted = $arrayLongitude !== null ? abs($arrayLongitude) . '° ' . ($arrayLongitude < 0 ? 'W' : 'E') : 'N/A'; echo "$latFormatted, $lonFormatted"; ?></span>
                            </div>
                            <div class="meta-item">
                                <span>🆔</span> <span id="item-id"><?php echo !is_null($arrayInternalId) ? $arrayInternalId : "N/A"; ?></span>
                            </div>
                        </div>

                        <!-- Categories with Links -->
                        <div class="categories-list">
                            <?php echo $htmlPageCategoriesList; ?>
                        </div>

                        <h1 class="details-title"><?php echo $computedNameOriginal; ?></h1>
                        <p class="details-description">
                            <?php echo $textPageDescription; ?>
                        </p>
                    </div>

                    <!-- Sidebar Widgets Area -->
                    <div class="sidebar-widgets">
                        <!-- Local Weather Widget -->
                        <div class="widget-card">
                            <div class="widget-title">
                                <span>Local Weather</span>
                                <span style="font-size: 0.75rem; color: var(--text-secondary);">Live Weather</span>
                            </div>
                            <div id="weather-widget-container" class="weather-content">
                                <div class="weather-temp">18°C</div>
                                <div class="weather-condition">Partly Cloudy<br>Wind: 12 km/h</div>
                            </div>
                        </div>

                        <!-- Availability Widget -->
                        <div class="widget-card">
                            <div class="widget-title"><span>Availability Status</span></div>
                            <div id="availability-container">
                                <div class="availability-status">
                                    <span class="status-dot"></span> Available for Booking
                                </div>
                            </div>
                        </div>

                        <!-- Share & Embed Options -->
                        <div class="widget-card">
                            <div class="widget-title"><span>Share & Connect</span></div>
                            <div class="share-buttons">
                                <button class="btn" id="btn-copy-link">📍 Copy Link</button>
                                <button class="btn" id="btn-copy-link-map">🌐 Copy Link to Map</button>
                                <a href="<?= htmlspecialchars($shareUrlTwitter) ?>" class="btn" target="_blank" rel="noopener">Twitter</a>
                                <a href="<?= htmlspecialchars($shareUrlFacebook) ?>" class="btn" target="_blank" rel="noopener">Facebook</a>
                            </div>
                        </div>

                        <div class="widget-card">
                            <div class="widget-title"><span>Embed Options (Click prefered option)</span></div>
                            <div class="embed-options">
                                <button class="btn" onclick="openEmbedModal('viewer')">Viewer</button>
                                <button class="btn" onclick="openEmbedModal('map')">Map</button>
                                <button class="btn" onclick="openEmbedModal('telemetry')">GeoPulse</button>
                                <button class="btn" onclick="openEmbedModal('availability')">Availability</button>
                                <button class="btn" onclick="openEmbedModal('suggestions')">Suggestions</button>
                                <button class="btn" onclick="openEmbedModal('weather')">Weather</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Map Section -->
        <section class="map-section">
            <h2 class="section-header">Geographic Location</h2>
            <div id="interactive-map" class="interactive-map-container">
                    <div class="app-shell">
        <!-- Production Glassmorphism Navigation Bar -->
        <header>
            <div class="brand">
                <div class="brand-logo">GP</div>
                <div class="brand-text">
                    <h1>GeoPulse OmniView</h1>
                    <p>Enterprise Location Intelligence</p>
                </div>
            </div>
            <div class="header-actions">
                <div class="status-pill">
                    <div id="connection-dot" class="status-dot"></div>
                    <span id="connection-text">Connecting...</span>
                </div>
                <div class="mode-switchers">
                    <button class="mode-btn active" data-target="location-view">Location Map</button>
                    <button class="mode-btn" data-target="timeline-view">Animated Timeline</button>
                    <button class="mode-btn" data-target="pure-timeline-view">Pure Timeline</button>
                    <button class="mode-btn" data-target="table-view">Data Matrix</button>
                </div>
            </div>
        </header>

        <!-- Main Workspace View Container -->
        <div class="workspace">
            
            <!-- Global Loading Shield -->
            <div id="loading-overlay" class="loading-overlay">
                <div class="loading-spinner"></div>
                <p style="font-size: 0.85rem; color: var(--text-secondary); font-weight: 500;">Authenticating & Syncing Telemetry Stream...</p>
            </div>

            <!-- 1. LOCATION MODE VIEW -->
            <div id="location-view" class="view-pane active">
                <div id="map-location" class="map-container"></div>
                
                <div class="inspector-card">
                    <span class="inspector-title">Active Telemetry Point</span>
                    <div id="inspector-location-content">
                        <!-- Populated dynamically -->
                    </div>
                </div>
            </div>

            <!-- 2. ANIMATED SCROLLABLE TIMELINE VIEW -->
            <div id="timeline-view" class="view-pane">
                <div id="map-timeline" class="map-container"></div>
                
                <div class="inspector-card">
                    <span class="inspector-title">Timeline State Inspector</span>
                    <div id="inspector-timeline-content">
                        <!-- Populated dynamically on timeline step change -->
                    </div>
                </div>

                <div class="timeline-overlay">
                    <div class="timeline-header">
                        <span class="timeline-badge" id="timeline-index-badge">Step 0 of 0</span>
                        <div class="timeline-date-display" id="timeline-timestamp-label">Syncing Epoch...</div>
                    </div>
                    <div class="timeline-controls-row">
                        <button class="control-btn" id="play-pause-btn">Play Animation</button>
                        <div class="slider-wrapper">
                            <input type="range" id="timeline-range" min="0" max="0" value="0" step="1">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 3. PURE TIMELINE VIEW (NO MAP) -->
            <div id="pure-timeline-view" class="view-pane">
                <div class="pure-timeline-container">
                    <div>
                        <h2 style="font-size: 1.25rem; font-weight: 600; margin-bottom: 6px;">Chronological Telemetry Stream</h2>
                        <p style="font-size: 0.85rem; color: var(--text-secondary);">Inspect sequence logs and telemetry records step-by-step without cartographic rendering.</p>
                    </div>

                    <div class="pure-timeline-scrubber-card">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <span class="timeline-badge" id="pure-index-badge">Step 0 of 0</span>
                            <span id="pure-timestamp-label" style="font-weight: 600; font-size: 0.9rem;">--</span>
                        </div>
                        <div style="display: flex; align-items: center; gap: 16px;">
                            <button class="control-btn" id="pure-play-pause-btn">Play Stream</button>
                            <div class="slider-wrapper">
                                <input type="range" id="pure-timeline-range" min="0" max="0" value="0" step="1">
                            </div>
                        </div>
                    </div>

                    <div class="inspector-grid" style="grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));">
                        <div class="inspector-metric"><span class="metric-label">Target City</span><span class="metric-value" id="pure-city">--</span></div>
                        <div class="inspector-metric"><span class="metric-label">Country</span><span class="metric-value" id="pure-country">--</span></div>
                        <div class="inspector-metric"><span class="metric-label">ISP Network</span><span class="metric-value" id="pure-isp">--</span></div>
                        <div class="inspector-metric"><span class="metric-label">Coordinates</span><span class="metric-value" id="pure-coords">--</span></div>
                    </div>

                    <div>
                        <h3 style="font-size: 0.9rem; font-weight: 600; margin-bottom: 12px; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em;">Telemetry Log History</h3>
                        <div class="events-stream" id="pure-events-stream">
                            <!-- Injected rows -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 4. COMPREHENSIVE TABLE VIEW -->
            <div id="table-view" class="view-pane">
                <div class="table-wrapper">
                    <table id="telemetry-table">
                        <thead>
                            <tr>
                                <th>Timestamp (UTC)</th>
                                <th>City / Region</th>
                                <th>Country</th>
                                <th>Coordinates</th>
                                <th>ISP Network</th>
                                <th>Organization</th>
                                <th>Timezone / Offset</th>
                                <th>Currency</th>
                                <th>AS Details</th>
                                <th>Flags (Mobile/Proxy/Hosting)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Populated dynamically via JS -->
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </div>
            </div>
        </section>

        <!-- Similar Suggestion Area -->
        <section class="suggestions-section">
            <h2 class="section-header">Similar Views</h2>
            <div class="suggestions-grid">
                <?php echo $htmlPageSuggestedViews ?>
            </div>
        </section>

        <!-- Question and Answer Area -->
        <section class="qa-section">
            <h2 class="section-header">Frequently Asked Questions</h2>
            <div class="qa-list">
                <?php echo $htmlPageFAQs; ?>
            </div>
        </section>

        <!-- Proximity Suggestions Area -->
        <section class="proximity-section">
            <h2 class="section-header">Nearby Points of Interest</h2>
            <div id="proximity-container" class="proximity-grid">
                <!-- Initialised via CameraSuggestionsWidget -->
                <?php echo $htmlPageSuggestedProximityViews ?>
           </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 Integration Layer
         * Simulates initializing widgets and components via standardized external calls.
         */

        // 1. Third Party Viewer/Player API Simulation: thirdpartyapi(container, details)
        function thirdpartyapi(containerId, detailsObj) {
            const container = document.getElementById(containerId);
            if (!container) return;

            // Simulating a rich interactive media player initialization
            setTimeout(() => {
                container.innerHTML = `
                    <div style="width: 100%; height: 100%; background: linear-gradient(135deg, #1a1816, #2d2925); display: flex; flex-direction: column; align-items: center; justify-content: center; color: #f4f1ea; position: relative;">
                        <div style="font-family: var(--font-serif); font-size: 1.75rem; margin-bottom: 0.5rem;">${detailsObj.title}</div>
                        <div style="font-size: 0.85rem; color: #a39e93; margin-bottom: 1.5rem;">Stream ID: ${detailsObj.id} | Status: Live Feed Active</div>
                        <button onclick="alert('Playing interactive media stream...')" style="background-color: var(--accent-color); color: #fff; border: none; padding: 0.75rem 1.5rem; border-radius: var(--radius-sm); font-weight: 600; cursor: pointer; transition: var(--transition);">▶ Play Stream</button>
                    </div>
                `;
            }, 600);
        }

        // 2. Ready Third Party Weather API Simulation: ready 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);
        }

        // 3. Third Party Availability API Simulation: 3rdpartyavilabilityapi
        function initAvailabilityAPI() {
            const availContainer = document.getElementById('availability-container');
            setTimeout(() => {
                availContainer.innerHTML = `
                        <div class="analytics-browser-app" id="surveillanceWidgetApp">
        <!-- Header Controls -->
        <div class="app-header">
            <div class="header-title-row">
                <div class="app-title-group">
                    <button class="minimize-btn" id="minimizeBtn" title="Minimize / Expand Widget">−</button>
                    <div class="app-title">Surveillance Availability Browser</div>
                </div>
                <div class="status-badge" id="globalStatusBadge">
                    <span class="status-dot"></span> <span id="statusBadgeText">Active Node</span>
                </div>
            </div>
            <div class="endpoint-control" style="display:none;">
                <div class="endpoint-input-wrapper">
                    <span>Key / ID:</span>
                    <input type="text" id="targetKeyInput" value="<?php echo $arrayInternalId; ?>">
                </div>
                <button class="fetch-btn" id="fetchDataBtn">Fetch Analytics</button>
            </div>
        </div>

        <!-- Scrollable Dashboard Body -->
        <div class="app-body" id="appBodyContent">
            <!-- Metrics Cards Grid -->
            <div class="metrics-overview" id="metricsOverview"></div>

            <!-- Chart Timeline View (Line Chart) -->
            <div class="section-card">
                <div class="section-header">
                    <div class="section-title">Availability Timeline Trend (Line View)</div>
                </div>
                <div class="chart-container">
                    <canvas id="availabilityChart"></canvas>
                </div>
            </div>

            <!-- Chart Timeline View (Bar Chart) -->
            <div class="section-card">
                <div class="section-header">
                    <div class="section-title">Availability Distribution (Bar View)</div>
                </div>
                <div class="chart-container">
                    <canvas id="availabilityBarChart"></canvas>
                </div>
            </div>

            <!-- In-Depth Analytics & Frequency Analysis Grid -->
            <div class="insights-grid">
                <div class="section-card">
                    <div class="section-header">
                        <div class="section-title">In-Depth Analysis</div>
                    </div>
                    <div id="analyticsDetails"></div>
                </div>

                <div class="section-card">
                    <div class="section-header">
                        <div class="section-title">Frequency Metrics</div>
                    </div>
                    <div id="frequencyMetrics"></div>
                </div>
            </div>

            <!-- Complete Log History Browser Table -->
            <div class="section-card">
                <div class="section-header">
                    <div class="section-title">Complete Event Log Stream Browser</div>
                    <span style="font-size: 11px; color: var(--text-secondary);" id="eventCountLabel">0 events</span>
                </div>
                <div class="history-table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th>Timestamp (UTC)</th>
                                <th>Epoch Integer</th>
                                <th>Event Type</th>
                            </tr>
                        </thead>
                        <tbody id="historyTableBody"></tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="app-footer">
            Surveillance Intelligence Viewer SDK
        </div>
    </div>
                `;
                 window.surveillanceWidget = new SurveillanceAnalyticsSDK('surveillanceWidgetApp', {
                keyInputId: 'targetKeyInput',
                fetchBtnId: 'fetchDataBtn'
            });
            }, 400);
        }

        // 4. Third Party Proximity API Simulation: CameraSuggestionsWidget
        function initProximityAPI() {
            new CameraSuggestionsWidget('proximity-container', {
                key: "<?php echo $_GET['internal_id']; ?>",
                suggestionUrlPrefix: "<?php echo $breadcrumbsPath1; ?>"
            });
        }

        // Copy Link Functionality
        document.getElementById('btn-copy-link').addEventListener('click', () => {
            navigator.clipboard.writeText("<?php echo $currentUrl; ?>").then(() => {
                const btn = document.getElementById('btn-copy-link');
                btn.textContent = '✓ Copied!';
                setTimeout(() => { btn.textContent = '📍 Copy Link'; }, 2000);
            });
        });

        document.getElementById('btn-copy-link-map').addEventListener('click', () => {
            navigator.clipboard.writeText("<?php echo $globalUriToEntryMap; ?>").then(() => {
                const btn = document.getElementById('btn-copy-link-map');
                btn.textContent = '✓ Copied!';
                setTimeout(() => { btn.textContent = '🌐 Copy Link to Map'; }, 2000);
            });
        });

        // Embed Modal Helper
        window.openEmbedModal = function(type) {
            let snippet;
            if (type === "map") {
                snippet = `<iframe src="<?php echo $globalUriToEntryMap; ?>" width="640" height="360" frameborder="0" allowfullscreen></iframe>`;
            } else {
                snippet = `<iframe src="<?php echo $globalUriToEmbeds; ?>/${type}/<?php echo !is_null($arrayInternalId) ? $arrayInternalId : "N/A"; ?>" width="640" height="360" frameborder="0" allowfullscreen></iframe>`;
            }
            prompt(`Copy ${type} embed code manually for AI agents or websites:`, snippet);
        };

        // Initialize APIs on window load for performance optimization
        window.addEventListener('DOMContentLoaded', () => {
                document.querySelectorAll('.proximity-card').forEach(card => {
                  const url = card.getAttribute('alt-link');
                    if (url && url.trim() !== '') {
                    card.addEventListener('click', () => {
                      window.location.href = url;
                    });
                  }
                });

            /*
            thirdpartyapi('media-viewer-container', {
                title: 'Grand Classical Observatory Live Stream',
                id: '<?php echo !is_null($arrayInternalId) ? $arrayInternalId : "N/A"; ?>',
                coordinates: '<?php echo !is_null($arrayLatitude) ? $arrayLatitude : "N/A"; ?>° N, <?php echo !is_null($arrayLongitude) ? $arrayLongitude : "N/A"; ?>° E'
            });
            */
            new CameraViewerWidget('media-viewer-container', {
                mode: "live",
                key: "<?php echo $arrayInternalId; ?>",
                suggestionUrlPrefix: "<?php echo $breadcrumbsPath1; ?>"
            });
            initWeatherAPI();
            initAvailabilityAPI();
            GeoPulseSDK.init("#map-location", {
                key: "<?php echo $arrayInternalId; ?>"
            });
            initProximityAPI();
        });
    </script>
</body>
</html>