<?php

declare(strict_types=1);

/**
 * 店家詳情：OpenStreetMap 官方 embed iframe（免費、不需 API、不受 Leaflet／全站 CSS 影響）。
 */

const FATE_STORE_MAP_HEIGHT = 360;

/** bbox 半徑（度）；約 0.0018° ≈ 街區 300–400m，愈小愈放大 */
const FATE_STORE_MAP_BBOX_PAD = 0.0018;

/**
 * @param array<string,mixed>|null $storeRow
 * @return array{
 *   fateIncludeStoreMap:bool,
 *   storeMapLat:?float,
 *   storeMapLng:?float,
 *   storeMapEmbedUrl:?string
 * }
 */
function fate_store_map_prepare_from_row(?array $storeRow): array
{
    $empty = [
        'fateIncludeStoreMap' => false,
        'storeMapLat' => null,
        'storeMapLng' => null,
        'storeMapEmbedUrl' => null,
    ];

    if (!is_array($storeRow)) {
        return $empty;
    }

    $la = isset($storeRow['latitude']) ? trim((string) $storeRow['latitude']) : '';
    $ln = isset($storeRow['longitude']) ? trim((string) $storeRow['longitude']) : '';
    if ($la === '' || $ln === '' || !is_numeric($la) || !is_numeric($ln)) {
        return $empty;
    }

    $storeMapLat = round((float) $la, 7);
    $storeMapLng = round((float) $ln, 7);
    if ($storeMapLat >= 118 && $storeMapLat <= 124 && $storeMapLng >= 20 && $storeMapLng <= 27) {
        $swap = $storeMapLat;
        $storeMapLat = $storeMapLng;
        $storeMapLng = $swap;
    }

    return [
        'fateIncludeStoreMap' => true,
        'storeMapLat' => $storeMapLat,
        'storeMapLng' => $storeMapLng,
        'storeMapEmbedUrl' => fate_store_map_osm_embed_url($storeMapLat, $storeMapLng),
    ];
}

function fate_store_map_height(): int
{
    return FATE_STORE_MAP_HEIGHT;
}

/**
 * OSM 官方內嵌地圖（含 marker 參數）。
 * bbox 順序：minLon,minLat,maxLon,maxLat；marker 順序：緯度,經度
 */
function fate_store_map_osm_embed_url(float $lat, float $lng, ?float $padDeg = null): string
{
    if ($padDeg === null) {
        $padDeg = FATE_STORE_MAP_BBOX_PAD;
    }
    // 高緯度地區經度 1° 的實際距離較短，略縮 lon 方向使視野接近正方形、避免過寬
    $padLon = $padDeg * 0.88;
    $padLat = $padDeg;
    $minLon = $lng - $padLon;
    $minLat = $lat - $padLat;
    $maxLon = $lng + $padLon;
    $maxLat = $lat + $padLat;
    $bbox = implode(',', [
        number_format($minLon, 6, '.', ''),
        number_format($minLat, 6, '.', ''),
        number_format($maxLon, 6, '.', ''),
        number_format($maxLat, 6, '.', ''),
    ]);
    $marker = number_format($lat, 6, '.', '') . ',' . number_format($lng, 6, '.', '');

    return 'https://www.openstreetmap.org/export/embed.html?bbox=' . rawurlencode($bbox)
        . '&layer=mapnik&marker=' . rawurlencode($marker);
}

function fate_store_map_osm_browse_url(float $lat, float $lng): string
{
    return 'https://www.openstreetmap.org/?mlat=' . rawurlencode((string) $lat)
        . '&mlon=' . rawurlencode((string) $lng)
        . '#map=18/' . rawurlencode((string) $lat) . '/' . rawurlencode((string) $lng);
}

/** 店家頁地圖 iframe（寬度 100% 填滿左欄 .layout-main） */
function fate_store_map_styles(): void
{
    $h = FATE_STORE_MAP_HEIGHT;
    ?>
        .layout-main .store-card-fate--block .store-map-embed,
        .layout-main .store-extra-tabs .store-map-embed {
            position: relative;
            display: block;
            width: 100%;
            max-width: 100%;
            min-width: 0;
            height: <?= (int) $h ?>px;
            margin-top: 0.35rem;
            border: 1px solid var(--line);
            border-radius: var(--radius);
            overflow: hidden;
            background: #e8ecf1;
            line-height: 0;
        }
        .layout-main .store-map-marker-label {
            position: absolute;
            left: 50%;
            top: 46%;
            z-index: 2;
            margin: 0;
            padding: 0;
            transform: translate(-50%, calc(-100% - 10px));
            pointer-events: none;
            max-width: min(92%, 20rem);
            text-align: center;
        }
        .layout-main .store-map-marker-label__text {
            display: inline-block;
            padding: 0.38rem 0.72rem;
            border-radius: 8px;
            border: 1px solid rgba(122, 184, 255, 0.45);
            background: rgba(10, 12, 16, 0.92);
            color: #f0f2f6;
            font-size: 0.84rem;
            font-weight: 700;
            line-height: 1.35;
            letter-spacing: 0.02em;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.45);
            word-break: break-word;
        }
        .layout-main .store-card-fate--block .store-map-embed iframe,
        .layout-main .store-extra-tabs .store-map-embed iframe {
            display: block;
            width: 100% !important;
            height: <?= (int) $h ?>px !important;
            border: 0;
        }
        @media (max-width: 640px) {
            .layout-main .store-card-fate--block .store-map-embed,
            .layout-main .store-card-fate--block .store-map-embed iframe,
            .layout-main .store-extra-tabs .store-map-embed,
            .layout-main .store-extra-tabs .store-map-embed iframe {
                height: 300px !important;
            }
        }
        .store-map-caption {
            margin: 0.45rem 0 0;
            font-size: 0.72rem;
            color: var(--muted);
            line-height: 1.45;
        }
        .store-map-caption a { color: var(--accent); text-decoration: none; }
        .store-map-caption a:hover { text-decoration: underline; }
    <?php
}
