<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <title><?= htmlspecialchars($location['name']) ?> – Menu</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- AOS -->
    <link href="https://unpkg.com/aos@2.3.4/dist/aos.css" rel="stylesheet">

    <style>
        :root {
            --accent-main: #a32386;
            --accent-soft: #f08bbf;
            --text-main: #3b2c3b;
            --muted: #8a8190;
            --border-soft: #f4d6ea;
            --bg-soft: #fff7fc;
        }

        body {
            font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
            background: #f8f5fb;
            color: var(--text-main);
        }

        .menu-header {
            max-width: 900px;
            margin: 40px auto 20px;
            background: #ffffff;
            border-radius: 18px;
            box-shadow: 0 8px 8px rgba(0, 0, 0, 0.06);
            padding: 32px;
            
            top: 20px;
            z-index: 100;
        }

        .menu-wrapper-top {
            max-width: 900px;
            margin: 20px auto;
            background: #ffffff;
            border-radius: 18px;
            box-shadow: 0 18px 40px rgba(0, 0, 0, 0.06);
            padding: 32px 32px 40px;
        }
        .menu-wrapper {
            max-width: 900px;
            margin: 20px auto;
            background: #ffffff;
            border-radius: 18px;
            box-shadow: 0 18px 40px rgba(0, 0, 0, 0.06);
            padding: 32px 32px 40px;
        }
        .menu-wrapper:last-of-type {
            margin-bottom: 40px;
        }

        @media (max-width: 576px) {
            .menu-header {
                margin: 16px 16px 12px;
                padding: 20px 16px;
                top: 10px;
            }
            
            .menu-wrapper {
                margin: 12px 16px;
                padding: 20px 16px 28px;
            }
        }

        .menu-heading {
            border-bottom: 1px solid var(--border-soft);
            padding-bottom: 18px;
            margin-bottom: 18px;
        }

        .menu-title {
            font-size: clamp(2.1rem, 4vw, 2.7rem);
            font-weight: 700;
            color: var(--accent-main);
            letter-spacing: 0.02em;position: sticky;
        }

        .category-nav {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 16px;
        }

        .category-nav-link {
            padding: 6px 14px;
            background: var(--bg-soft);
            border: 1px solid var(--border-soft);
            border-radius: 20px;
            color: var(--accent-main);
            text-decoration: none;
            font-size: 0.9rem;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .category-nav-link:hover {
            background: var(--accent-main);
            color: white;
            border-color: var(--accent-main);
        }
        .lang-pill {
            width: 48px !important;
            height: 48px !important;
            border-radius: 50%;
            border: 2px solid var(--border-soft);
            display: flex;
            align-items: center;
            justify-content: center;
            background: var(--bg-soft);
            cursor: pointer;
            transition: all 0.3s ease;
            position: absolute;
            overflow: hidden;
            right: 10px;
            top: 10px;
        }

        .lang-pill:hover {
            border-color: var(--accent-main);
            transform: scale(1.1);
            box-shadow: 0 4px 12px rgba(163, 35, 134, 0.3);
        }

        .lang-flag {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
        }

        .lang-pill:hover .lang-flag {
            transform: scale(1.1);
        }

        .section-title {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 18px;
        }

        .section-subtitle {
            font-size: .92rem;
            color: var(--muted);
            margin-bottom: 22px;
        }

        .menu-item {
            border-top: 1px solid var(--border-soft);
            padding-block: 16px;
            cursor: pointer;
            transition: transform 0.5s ease, background-color 0.5s ease, box-shadow 0.5s ease,  scale 0.5s ease;
            border-radius: 8px;
            margin-inline: -8px;
            padding-inline: 8px;
             transform: scale(1.0);
            box-shadow: 0 0 0 rgba(0, 0, 0, 0.06);
        }

        .menu-item:hover {
            transform: scale(1.02);
            background-color: var(--bg-soft);
            z-index: 10;
            box-shadow: 0 8px 8px rgba(0, 0, 0, 0.06);
        }

        .menu-item.selected {
            background-color: #fef0f9;
            border-color: var(--accent-soft);
            position: relative;
        }

        .menu-item.selected::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 3px;
            background: var(--accent-main);
            border-radius: 0 3px 3px 0;
        }

        .menu-item:first-of-type {
            border-top: none;
        }

        .menu-item-title {
            font-weight: 700;
            font-size: 1.05rem;
            margin-bottom: 4px;
        }

        .menu-item-subtitle {
            font-weight: 500;
            font-size: 0.95rem;
            color: var(--muted);
            margin-bottom: 4px;
        }

        .menu-item-desc {
            font-size: .92rem;
            color: var(--muted);
        }

        .menu-item-price {
            font-weight: 600;
            white-space: nowrap;
            font-size: 1rem;
        }

        .menu-item-price-label {
            font-size: 0.85rem;
            color: var(--muted);
            display: block;
        }

        .menu-item-img {
            width: 120px;
            
            aspect-ratio: 1 / 1;
            border-radius: 18px;
            overflow: hidden;
            background: var(--bg-soft);
            border: 1px solid var(--border-soft);
            object-fit: cover;
        }

        .floating-buttons {
            position: fixed;
            bottom: 24px;
            right: 24px;
            display: flex;
            flex-direction: column;
            gap: 12px;
            z-index: 1000;
        }

        .floating-btn {
            width: 56px;
            height: 56px;
            border-radius: 50%;
            background: var(--accent-main);
            color: white;
            border: none;
            box-shadow: 0 4px 12px rgba(163, 35, 134, 0.3);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.3rem;
            transition: all 0.3s ease;
            opacity: 0;
            transform: scale(0.8);
        }

        .floating-btn.visible {
            opacity: 1;
            transform: scale(1);
        }

        .floating-btn:hover {
            background: var(--accent-soft);
            transform: scale(1.1);
            box-shadow: 0 6px 16px rgba(163, 35, 134, 0.4);
        }

        .category-menu-popup {
            position: fixed;
            bottom: 100px;
            right: 24px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
            padding: 16px;
            max-width: 280px;
            max-height: calc(100vh - 140px);
            overflow-y: auto;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.3s ease;
            pointer-events: none;
            z-index: 999;
        }

        .category-menu-popup.visible {
            opacity: 1;
            transform: translateY(0);
            pointer-events: all;
        }

        .category-menu-popup h6 {
            font-size: 0.9rem;
            font-weight: 700;
            color: var(--accent-main);
            margin-bottom: 12px;
        }

        .category-menu-popup .category-nav-link {
            display: block;
            margin-bottom: 6px;
        }

        .lightbox {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0);
            z-index: 2000;
            align-items: center;
            justify-content: center;
            padding: 20px;
            transition: background 0.3s ease;
        }

        .lightbox.active {
            display: flex;
            animation: lightboxFadeIn 0.3s ease forwards;
        }

        .lightbox.closing {
            animation: lightboxFadeOut 0.3s ease forwards;
        }

        @keyframes lightboxFadeIn {
            from {
                background: rgba(0, 0, 0, 0);
            }
            to {
                background: rgba(0, 0, 0, 0.9);
            }
        }

        @keyframes lightboxFadeOut {
            from {
                background: rgba(0, 0, 0, 0.9);
            }
            to {
                background: rgba(0, 0, 0, 0);
            }
        }

        .lightbox-content {
            max-width: 600px;
            width: 100%;
            background: white;
            border-radius: 18px;
            overflow: hidden;
            position: relative;
            max-height: 90vh;
            overflow-y: auto;
            transform: scale(0.8);
            opacity: 0;
            transition: transform 0.3s ease, opacity 0.3s ease;
                overflow: hidden;
        }

        .lightbox.active .lightbox-content {
            transform: scale(1);
            opacity: 1;
        }

        .lightbox.closing .lightbox-content {
            transform: scale(0.8);
            opacity: 0;
        }

        .lightbox-image {
            width: 100%;
            aspect-ratio: 1 / 1;
            object-fit: cover;
        }

        .lightbox-details {
            padding: 24px;
        }

        .lightbox-title {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--accent-main);
            margin-bottom: 8px;
        }

        .lightbox-subtitle {
            font-size: 1.1rem;
            color: var(--muted);
            margin-bottom: 16px;
        }

        .lightbox-desc {
            font-size: 1rem;
            color: var(--text-main);
            margin-bottom: 20px;
            line-height: 1.6;
        }

        .lightbox-prices {
            border-top: 2px solid var(--border-soft);
            padding-top: 16px;
        }

        .lightbox-price-item {
            margin-bottom: 8px;
        }

        .lightbox-price-label {
            font-size: 0.9rem;
            color: var(--muted);
        }

        .lightbox-price {
            font-size: 1.3rem;
            font-weight: 700;
            color: var(--accent-main);
        }

        .lightbox-close {
            position: absolute;
            top: 16px;
            right: 16px;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: white;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
            transition: all 0.2s ease;
            z-index: 10;
        }

        .lightbox-close:hover {
            background: var(--accent-main);
            color: white;
            transform: rotate(90deg);
        }

        .menu-item-img {
            cursor: pointer;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .menu-item-img:hover {
            transform: scale(1.05);
            box-shadow: 0 4px 12px rgba(163, 35, 134, 0.3);
        }
h2.section-title {
    position: sticky;
    top: 0px;
    z-index: 55;
    background: white;
    padding: 1.5em;
    margin: 0px;
    margin-left: -0.3em;
    margin-right: -0.3em;
    padding-left: 0;
    border-radius: 0px 0px 20px 20px;
}
        .remove-item-btn {
            position: absolute;
            top: -12px;
            right: -12px;
            width: 28px;
            height: 28px;
            border-radius: 50%;
            background: rgba(163, 35, 134, 0.9);
            color: white;
            border: 2px solid white;
            display: none;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.2s ease;
            z-index: 20;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        }

        .menu-item.selected .remove-item-btn {
            display: flex;
        }

        .remove-item-btn:hover {
            transform: rotate(90deg) scale(1.1);
            background: #c42d9f;
        }

        .cart-badge {
            position: absolute;
            top: -8px;
            right: -8px;
            background: var(--accent-main);
            color: white;
            font-size: 0.75rem;
            font-weight: 700;
            min-width: 22px;
            height: 22px;
            border-radius: 11px;
            display: none;
            align-items: center;
            justify-content: center;
            padding: 0 6px;
            box-shadow: 0 2px 6px rgba(163, 35, 134, 0.4);
        }

        .cart-badge.visible {
            display: flex;
        }

        .cart-view {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: #f8f5fb;
            z-index: 1500;
            overflow-y: auto;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s ease;
        }

        .cart-view.active {
            opacity: 1;
            pointer-events: all;
        }

        .cart-header {
            max-width: 900px;
            margin: 40px auto 20px;
            background: #ffffff;
            border-radius: 18px;
            box-shadow: 0 8px 8px rgba(0, 0, 0, 0.06);
            padding: 32px;
            position: sticky;
            top: 20px;
            z-index: 100;
        }

        .cart-close-btn {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--bg-soft);
            border: 1px solid var(--border-soft);
            color: var(--accent-main);
            font-size: 1.5rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }

        .cart-close-btn:hover {
            background: var(--accent-main);
            color: white;
            transform: scale(1.1);
        }

        .cart-empty {
            max-width: 900px;
            margin: 20px auto;
            background: #ffffff;
            border-radius: 18px;
            box-shadow: 0 18px 40px rgba(0, 0, 0, 0.06);
            padding: 60px 32px;
            text-align: center;
        }

        .cart-empty-icon {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.3;
        }

        @media (max-width: 576px) {
            .cart-header {
                margin: 16px 16px 12px;
                padding: 20px 16px;
                top: 10px;
            }
        }

        .share-btn {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--accent-main);
            color: white;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            margin-left: 8px;
        }

        .share-btn:hover {
            background: var(--accent-soft);
            transform: scale(1.1);
        }

        .share-menu {
            position: absolute;
            top: 50px;
            right: 0;
            background: white;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
            padding: 12px;
            display: none;
            flex-direction: column;
            gap: 8px;
            min-width: 200px;
            z-index: 1000;
        }

        .share-menu.active {
            display: flex;
        }

        .share-option {
            padding: 12px 16px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 12px;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            color: var(--text-main);
            border: 1px solid var(--border-soft);
        }

        .share-option:hover {
            background: var(--bg-soft);
            border-color: var(--accent-main);
            color: var(--accent-main);
            transform: translateX(4px);
        }

        .share-icon {
            font-size: 1.5rem;
            width: 24px;
            text-align: center;
        }
    </style>
</head>
<body>

<!-- Menu Header (Sticky) -->
<div class="menu-header" data-aos="fade-down" data-aos-duration="500">
    <div class="menu-heading d-flex justify-content-between align-items-center">
        <div>
            <h1 class="menu-title mb-0" data-aos="fade-right" data-aos-delay="50">
                <?= htmlspecialchars($location['name']) ?>
            </h1>
            <?php if (!empty($groupedItems)): ?>
                <nav class="category-nav" data-aos="fade-up" data-aos-delay="150">
                    <?php foreach ($groupedItems as $categoryName => $categoryData): ?>
                        <a href="#category-<?= urlencode($categoryName) ?>" class="category-nav-link">
                            <span class="lang-text lang-pl"><?= htmlspecialchars($categoryName) ?></span>
                            <span class="lang-text lang-en" style="display: none;"><?= htmlspecialchars($categoryData['name_en'] ?: $categoryName) ?></span>
                        </a>
                    <?php endforeach; ?>
                </nav>
            <?php endif; ?>
        </div>
        <div class="lang-pill" data-aos="zoom-in" data-aos-delay="120" onclick="toggleLanguage()" title="Przełącz język / Switch language">
            <img src="https://www.cukierniasamanta.pl/sklep/wp-content/uploads/2022/08/Poland_flag_icon_round-copy.svg" 
                 alt="Polish flag" 
                 class="lang-flag" 
                 id="langFlag">
        </div>
    </div>
</div>

<!-- Menu Categories -->
<?php if (empty($groupedItems)): ?>
    <div class="menu-wrapper" data-aos="fade-up">
        <div class="text-center py-5">
            <p class="text-muted">Brak pozycji menu dla tej lokalizacji</p>
        </div>
    </div>
<?php else: ?>
    <?php 
    $categoryIndex = 0;
    foreach ($groupedItems as $categoryName => $categoryData): 
        $categoryIndex++;
        $items = $categoryData['items'];
    ?>
        <div class="menu-wrapper" data-aos="fade-up" data-aos-duration="700" data-aos-delay="<?= $categoryIndex * 100 ?>" id="category-<?= urlencode($categoryName) ?>">
            <h2 class="section-title">
                <span class="lang-text lang-pl"><?= htmlspecialchars($categoryName) ?></span>
                <span class="lang-text lang-en" style="display: none;"><?= htmlspecialchars($categoryData['name_en'] ?: $categoryName) ?></span>
            </h2>
            
            <div class="menu-items">
                <?php 
                $itemIndex = 0;
                foreach ($items as $item): 
                    $itemIndex++;
                    $hasImage = !empty($item['image_url']);
                ?>
                    <div class="menu-item" data-aos="fade-up" data-aos-delay="<?= 80 + ($itemIndex * 50) ?>" 
                         data-item-id="<?= $item['id'] ?>"
                         data-item-name="<?= htmlspecialchars($item['name_pl']) ?>"
                         data-item-price="<?= $item['price_1'] ?? 0 ?>"
                         data-name-pl="<?= htmlspecialchars($item['name_pl']) ?>"
                         data-name-en="<?= htmlspecialchars($item['name_en'] ?? '') ?>"
                         data-desc-pl="<?= htmlspecialchars($item['description_pl'] ?? '') ?>"
                         data-desc-en="<?= htmlspecialchars($item['description_en'] ?? '') ?>"
                         data-price1-prefix-pl="<?= htmlspecialchars($item['price_1_prefix_pl'] ?? '') ?>"
                         data-price1-prefix-en="<?= htmlspecialchars($item['price_1_prefix_en'] ?? '') ?>"
                         data-price2-prefix-pl="<?= htmlspecialchars($item['price_2_prefix_pl'] ?? '') ?>"
                         data-price2-prefix-en="<?= htmlspecialchars($item['price_2_prefix_en'] ?? '') ?>"
                         data-price3-prefix-pl="<?= htmlspecialchars($item['price_3_prefix_pl'] ?? '') ?>"
                         data-price3-prefix-en="<?= htmlspecialchars($item['price_3_prefix_en'] ?? '') ?>"
                         onclick="toggleCartItem(this, event)">
                        <button class="remove-item-btn" onclick="removeFromCart(this, event)" title="Usuń z wyboru">×</button>
                        <div class="row g-3 align-items-center">
                            <?php if ($hasImage): ?>
                                <div class="col-4 col-md-3">
                                    <img src="<?= htmlspecialchars($item['image_url']) ?>"
                                         alt="<?= htmlspecialchars($item['name_pl']) ?>" 
                                         class="menu-item-img w-100"
                                         data-lightbox-title="<?= htmlspecialchars($item['name_pl']) ?>"
                                         data-lightbox-subtitle="<?= htmlspecialchars($item['name_en'] ?? '') ?>"
                                         data-lightbox-desc="<?= htmlspecialchars($item['description_pl'] ?? '') ?>"
                                         data-lightbox-price1-label="<?= htmlspecialchars($item['price_1_prefix_pl'] ?? '') ?>"
                                         data-lightbox-price1="<?= $item['price_1'] ? number_format($item['price_1'], 0) . ' zł' : '' ?>"
                                         data-lightbox-price2-label="<?= htmlspecialchars($item['price_2_prefix_pl'] ?? '') ?>"
                                         data-lightbox-price2="<?= $item['price_2'] ? number_format($item['price_2'], 0) . ' zł' : '' ?>"
                                         data-lightbox-price3-label="<?= htmlspecialchars($item['price_3_prefix_pl'] ?? '') ?>"
                                         data-lightbox-price3="<?= $item['price_3'] ? number_format($item['price_3'], 0) . ' zł' : '' ?>"
                                         onclick="openLightbox(this, event)">
                                </div>
                                <div class="col-8 col-md-7">
                            <?php else: ?>
                                <div class="col-9 col-sm-10">
                            <?php endif; ?>
                                    <div class="menu-item-title">
                                        <span class="lang-text lang-pl"><?= htmlspecialchars($item['name_pl']) ?></span>
                                        <span class="lang-text lang-en" style="display: none;"><?= htmlspecialchars($item['name_en'] ?: $item['name_pl']) ?></span>
                                    </div>
                                    <?php if ($item['name_en'] || $item['name_pl']): ?>
                                        <div class="menu-item-subtitle">
                                            <span class="lang-text lang-pl"><?= htmlspecialchars($item['name_en'] ?: '') ?></span>
                                            <span class="lang-text lang-en" style="display: none;"><?= htmlspecialchars($item['name_pl']) ?></span>
                                        </div>
                                    <?php endif; ?>
                                    <div class="menu-item-desc">
                                        <span class="lang-text lang-pl"><?= htmlspecialchars($item['description_pl'] ?? '') ?></span>
                                        <span class="lang-text lang-en" style="display: none;"><?= htmlspecialchars($item['description_en'] ?: $item['description_pl'] ?: '') ?></span>
                                    </div>
                                </div>
                                <div class="<?= $hasImage ? 'col-12 col-md-2' : 'col-3 col-sm-2' ?> text-<?= $hasImage ? 'md-' : '' ?>end <?= $hasImage ? 'mt-2 mt-md-0' : '' ?>">
                                    <?php if ($item['price_1']): ?>
                                        <?php if ($item['price_1_prefix_pl'] || $item['price_1_prefix_en']): ?>
                                            <div class="menu-item-price-label">
                                                <span class="lang-text lang-pl"><?= htmlspecialchars($item['price_1_prefix_pl'] ?? '') ?></span>
                                                <span class="lang-text lang-en" style="display: none;"><?= htmlspecialchars($item['price_1_prefix_en'] ?: $item['price_1_prefix_pl'] ?: '') ?></span>
                                            </div>
                                        <?php endif; ?>
                                        <div class="menu-item-price"><?= number_format($item['price_1'], 0) ?> zł</div>
                                    <?php endif; ?>
                                    <?php if ($item['price_2']): ?>
                                        <?php if ($item['price_2_prefix_pl'] || $item['price_2_prefix_en']): ?>
                                            <div class="menu-item-price-label mt-2">
                                                <span class="lang-text lang-pl"><?= htmlspecialchars($item['price_2_prefix_pl'] ?? '') ?></span>
                                                <span class="lang-text lang-en" style="display: none;"><?= htmlspecialchars($item['price_2_prefix_en'] ?: $item['price_2_prefix_pl'] ?: '') ?></span>
                                            </div>
                                        <?php endif; ?>
                                        <div class="menu-item-price"><?= number_format($item['price_2'], 0) ?> zł</div>
                                    <?php endif; ?>
                                    <?php if ($item['price_3']): ?>
                                        <?php if ($item['price_3_prefix_pl'] || $item['price_3_prefix_en']): ?>
                                            <div class="menu-item-price-label mt-2">
                                                <span class="lang-text lang-pl"><?= htmlspecialchars($item['price_3_prefix_pl'] ?? '') ?></span>
                                                <span class="lang-text lang-en" style="display: none;"><?= htmlspecialchars($item['price_3_prefix_en'] ?: $item['price_3_prefix_pl'] ?: '') ?></span>
                                            </div>
                                        <?php endif; ?>
                                        <div class="menu-item-price"><?= number_format($item['price_3'], 0) ?> zł</div>
                                    <?php endif; ?>
                                </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endforeach; ?>
<?php endif; ?>

<!-- Floating Buttons -->
<div class="floating-buttons">
    <button class="floating-btn" id="cartBtn" title="Wybrane pozycje" style="position: relative;">
        🛒
        <span class="cart-badge" id="cartBadge">0</span>
    </button>
    <button class="floating-btn" id="menuBtn" title="Menu kategorii">
        ☰
    </button>
    <button class="floating-btn" id="scrollTopBtn" title="Przewiń do góry">
        ↑
    </button>
</div>

<!-- Category Menu Popup -->
<?php if (!empty($groupedItems)): ?>
<div class="category-menu-popup" id="categoryMenuPopup">
    <h6>
        <span class="lang-text lang-pl">Przejdź do kategorii:</span>
        <span class="lang-text lang-en" style="display: none;">Go to category:</span>
    </h6>
    <?php foreach ($groupedItems as $categoryName => $categoryData): ?>
        <a href="#category-<?= urlencode($categoryName) ?>" class="category-nav-link popup-category-link">
            <span class="lang-text lang-pl"><?= htmlspecialchars($categoryName) ?></span>
            <span class="lang-text lang-en" style="display: none;"><?= htmlspecialchars($categoryData['name_en'] ?: $categoryName) ?></span>
        </a>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Lightbox -->
<div class="lightbox" id="lightbox" onclick="closeLightbox(event)">
    <button class="lightbox-close" onclick="closeLightbox(event)">&times;</button>
    <div class="lightbox-content" onclick="event.stopPropagation()">
        <img src="" alt="" class="lightbox-image" id="lightboxImage">
        <div class="lightbox-details">
            <div class="lightbox-title" id="lightboxTitle"></div>
            <div class="lightbox-subtitle" id="lightboxSubtitle"></div>
            <div class="lightbox-desc" id="lightboxDesc"></div>
            <div class="lightbox-prices" id="lightboxPrices"></div>
        </div>
    </div>
</div>

<!-- Cart View -->
<div class="cart-view" id="cartView">
    <div class="cart-header">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h1 class="menu-title mb-0">Wybrane pozycje</h1>
                <p class="text-muted mb-0 mt-2" id="cartCount">0 pozycji</p>
            </div>
            <div class="d-flex" style="position: relative;">
                <button class="share-btn" id="shareBtn" onclick="toggleShareMenu()" title="Udostępnij">
                    📤
                </button>
                <div class="share-menu" id="shareMenu">
                    <a href="#" class="share-option" onclick="shareViaWhatsApp(event)">
                        <span class="share-icon">💬</span>
                        <span>WhatsApp</span>
                    </a>
                    <a href="#" class="share-option" onclick="shareViaSMS(event)">
                        <span class="share-icon">📱</span>
                        <span>SMS</span>
                    </a>
                    <a href="#" class="share-option" onclick="shareViaEmail(event)">
                        <span class="share-icon">✉️</span>
                        <span>Email</span>
                    </a>
                    <a href="#" class="share-option" onclick="shareViaMessenger(event)">
                        <span class="share-icon">👥</span>
                        <span>Messenger</span>
                    </a>
                </div>
                <button class="cart-close-btn" onclick="closeCartView()" title="Zamknij">
                    ×
                </button>
            </div>
        </div>
    </div>
    <div id="cartContent"></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/aos@2.3.4/dist/aos.js"></script>
<script>
    AOS.init({
        once: true,
        offset: 60
    });

    // Language toggle
    // Check URL hash first, then localStorage
    function getInitialLanguage() {
        const hash = window.location.hash.substring(1);
        if (hash === 'en' || hash === 'pl') {
            return hash;
        }
        return localStorage.getItem('menuLanguage_<?= $location['id'] ?>') || 'pl';
    }
    
    let currentLang = getInitialLanguage();

    function toggleLanguage() {
        currentLang = currentLang === 'pl' ? 'en' : 'pl';
        localStorage.setItem('menuLanguage_<?= $location['id'] ?>', currentLang);
        
        // Update URL hash
        history.pushState(null, '', '#' + currentLang);
        
        updateLanguage(true);
    }

    function updateLanguage(animate = false) {
        const langFlag = document.getElementById('langFlag');
        const plElements = document.querySelectorAll('.lang-pl');
        const enElements = document.querySelectorAll('.lang-en');
        const menuWrappers = document.querySelectorAll('.menu-wrapper');

        if (animate) {
            // Fade out all cards
            menuWrappers.forEach((wrapper, index) => {
                wrapper.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                wrapper.style.opacity = '0';
                wrapper.style.transform = 'translateY(20px)';
            });

            setTimeout(() => {
                if (currentLang === 'pl') {
                    langFlag.src = 'https://www.cukierniasamanta.pl/sklep/wp-content/uploads/2022/08/Poland_flag_icon_round-copy.svg';
                    langFlag.alt = 'Polish flag';
                    
                    // Switch language text
                    enElements.forEach(el => el.style.display = 'none');
                    plElements.forEach(el => el.style.display = '');
                } else {
                    langFlag.src = 'https://www.cukierniasamanta.pl/sklep/wp-content/uploads/2022/08/United-kingdom_flag_icon_round.svg';
                    langFlag.alt = 'English flag';
                    
                    // Switch language text
                    plElements.forEach(el => el.style.display = 'none');
                    enElements.forEach(el => el.style.display = '');
                }

                // Fade in all cards
                setTimeout(() => {
                    menuWrappers.forEach((wrapper, index) => {
                        setTimeout(() => {
                            wrapper.style.opacity = '1';
                            wrapper.style.transform = 'translateY(0)';
                        }, index * 100);
                    });
                }, 50);
            }, 300);
        } else {
            // No animation - instant switch
            if (currentLang === 'pl') {
                langFlag.src = 'https://www.cukierniasamanta.pl/sklep/wp-content/uploads/2022/08/Poland_flag_icon_round-copy.svg';
                langFlag.alt = 'Polish flag';
                plElements.forEach(el => el.style.display = '');
                enElements.forEach(el => el.style.display = 'none');
            } else {
                langFlag.src = 'https://www.cukierniasamanta.pl/sklep/wp-content/uploads/2022/08/United-kingdom_flag_icon_round.svg';
                langFlag.alt = 'English flag';
                plElements.forEach(el => el.style.display = 'none');
                enElements.forEach(el => el.style.display = '');
            }
        }
        
        // Save to localStorage
        localStorage.setItem('menuLanguage_<?= $location['id'] ?>', currentLang);
    }

    // Handle browser back/forward navigation
    window.addEventListener('hashchange', function() {
        const hash = window.location.hash.substring(1);
        if ((hash === 'en' || hash === 'pl') && hash !== currentLang) {
            currentLang = hash;
            updateLanguage(true);
        }
    });

    // Initialize language on page load
    updateLanguage();
    
    // Set initial hash if not present
    if (!window.location.hash) {
        history.replaceState(null, '', '#' + currentLang);
    }

    // Smooth scroll for category links
    function setupCategoryLinks(selector) {
        document.querySelectorAll(selector).forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const targetId = this.getAttribute('href').substring(1);
                const targetElement = document.getElementById(targetId);
                if (targetElement) {
                    targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    // Hide popup if clicking from popup
                    if (this.classList.contains('popup-category-link')) {
                        document.getElementById('categoryMenuPopup').classList.remove('visible');
                    }
                }
            });
        });
    }

    setupCategoryLinks('.category-nav-link');

    // Scroll to top button
    const scrollTopBtn = document.getElementById('scrollTopBtn');
    const menuBtn = document.getElementById('menuBtn');
    const categoryMenuPopup = document.getElementById('categoryMenuPopup');

    window.addEventListener('scroll', function() {
        if (window.scrollY > 300) {
            scrollTopBtn.classList.add('visible');
            menuBtn.classList.add('visible');
        } else {
            scrollTopBtn.classList.remove('visible');
            menuBtn.classList.remove('visible');
        }
    });

    scrollTopBtn.addEventListener('click', function() {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });

    // Toggle category menu popup
    menuBtn.addEventListener('click', function() {
        categoryMenuPopup.classList.toggle('visible');
    });

    // Close popup when clicking outside
    document.addEventListener('click', function(e) {
        if (categoryMenuPopup && !categoryMenuPopup.contains(e.target) && e.target !== menuBtn) {
            categoryMenuPopup.classList.remove('visible');
        }
    });

    // Cart management
    let cart = JSON.parse(localStorage.getItem('menuCart_<?= $location['id'] ?>') || '[]');

    // Load shared items from URL if present
    function loadSharedItems() {
        const urlParams = new URLSearchParams(window.location.search);
        const encodedItems = urlParams.get('items');
        
        if (encodedItems) {
            try {
                const decodedString = atob(encodedItems); // base64 decode
                const itemIds = decodedString.split(',').filter(id => id);
                if (itemIds.length > 0) {
                    cart = itemIds;
                    saveCart();
                    
                    // Show notification
                    setTimeout(() => {
                        alert(`Załadowano ${itemIds.length} ${itemIds.length === 1 ? 'pozycję' : itemIds.length < 5 ? 'pozycje' : 'pozycji'} z udostępnionego linku!`);
                    }, 500);
                }
            } catch (e) {
                console.error('Failed to decode shared items:', e);
            }
        }
    }

    // Load shared items on page load
    loadSharedItems();

    function updateCartUI() {
        const cartBadge = document.getElementById('cartBadge');
        const cartBtn = document.getElementById('cartBtn');
        
        if (cart.length > 0) {
            cartBadge.textContent = cart.length;
            cartBadge.classList.add('visible');
            cartBtn.classList.add('visible');
        } else {
            cartBadge.classList.remove('visible');
        }

        // Update selected states
        document.querySelectorAll('.menu-item').forEach(item => {
            const itemId = item.dataset.itemId;
            if (cart.includes(itemId)) {
                item.classList.add('selected');
            } else {
                item.classList.remove('selected');
            }
        });
    }

    function saveCart() {
        localStorage.setItem('menuCart_<?= $location['id'] ?>', JSON.stringify(cart));
        updateCartUI();
    }

    function toggleCartItem(element, event) {
        // Prevent toggle if clicking on image or remove button
        if (event.target.classList.contains('menu-item-img') || 
            event.target.classList.contains('remove-item-btn')) {
            return;
        }

        const itemId = element.dataset.itemId;
        const index = cart.indexOf(itemId);
        
        if (index > -1) {
            cart.splice(index, 1);
        } else {
            cart.push(itemId);
        }
        
        saveCart();
    }

    function removeFromCart(button, event) {
        event.stopPropagation();
        const menuItem = button.closest('.menu-item');
        const itemId = menuItem.dataset.itemId;
        const index = cart.indexOf(itemId);
        
        if (index > -1) {
            cart.splice(index, 1);
            saveCart();
        }
    }

    function showCart() {
        const cartView = document.getElementById('cartView');
        const cartContent = document.getElementById('cartContent');
        const cartCount = document.getElementById('cartCount');
        
        if (cart.length === 0) {
            cartContent.innerHTML = `
                <div class="cart-empty">
                    <div class="cart-empty-icon">🛒</div>
                    <h3 style="color: var(--accent-main);">Brak wybranych pozycji</h3>
                    <p class="text-muted">Kliknij na pozycje menu, aby je dodać do wyboru</p>
                </div>
            `;
            cartCount.textContent = '0 pozycji';
        } else {
            // Group cart items by category
            const cartItemsData = [];
            cart.forEach(itemId => {
                const element = document.querySelector(`[data-item-id="${itemId}"]`);
                if (element) {
                    const categoryWrapper = element.closest('.menu-wrapper');
                    const categoryTitle = categoryWrapper ? categoryWrapper.querySelector('.section-title').textContent : 'Inne';
                    
                    cartItemsData.push({
                        id: itemId,
                        category: categoryTitle,
                        html: element.innerHTML
                    });
                }
            });

            // Group by category
            const grouped = {};
            cartItemsData.forEach(item => {
                if (!grouped[item.category]) {
                    grouped[item.category] = [];
                }
                grouped[item.category].push(item);
            });

            // Build HTML
            let html = '';
            Object.keys(grouped).forEach(category => {
                html += `
                    <div class="menu-wrapper" style="animation: fadeIn 0.3s ease;">
                        <h2 class="section-title">${category}</h2>
                        <div class="menu-items">
                `;
                
                grouped[category].forEach(item => {
                    html += `
                        <div class="menu-item selected" data-item-id="${item.id}" onclick="toggleCartItem(this, event)">
                            <button class="remove-item-btn" onclick="removeFromCart(this, event)" title="Usuń z wyboru">×</button>
                            ${item.html}
                        </div>
                    `;
                });
                
                html += `
                        </div>
                    </div>
                `;
            });
            
            cartContent.innerHTML = html;
            cartCount.textContent = `${cart.length} ${cart.length === 1 ? 'pozycja' : cart.length < 5 ? 'pozycje' : 'pozycji'}`;
        }
        
        cartView.classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    function closeCartView() {
        const cartView = document.getElementById('cartView');
        cartView.classList.remove('active');
        document.body.style.overflow = '';
    }

    function toggleShareMenu() {
        const shareMenu = document.getElementById('shareMenu');
        shareMenu.classList.toggle('active');
    }

    function getCartShareText() {
        if (cart.length === 0) {
            return { text: 'Brak wybranych pozycji', url: window.location.href.split('?')[0].split('#')[0] };
        }

        const locationName = '<?= htmlspecialchars($location['name']) ?>';
        const baseUrl = window.location.href.split('?')[0].split('#')[0];
        const itemsString = cart.join(',');
        const encodedItems = btoa(itemsString); // base64 encode
        const shareUrl = `${baseUrl}?items=${encodedItems}#${currentLang}`;
        
        let text = `Sprawdź moje wybrane pozycje z menu - ${locationName}!\n\n`;
        text += shareUrl;
        
        return { text, url: shareUrl };
    }

    function shareViaWhatsApp(event) {
        event.preventDefault();
        const shareData = getCartShareText();
        const url = `https://wa.me/?text=${encodeURIComponent(shareData.text)}`;
        window.open(url, '_blank');
        toggleShareMenu();
    }

    function shareViaSMS(event) {
        event.preventDefault();
        const shareData = getCartShareText();
        const url = `sms:?body=${encodeURIComponent(shareData.text)}`;
        window.location.href = url;
        toggleShareMenu();
    }

    function shareViaEmail(event) {
        event.preventDefault();
        const shareData = getCartShareText();
        const locationName = '<?= htmlspecialchars($location['name']) ?>';
        const subject = `Menu - ${locationName}`;
        const url = `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(shareData.text)}`;
        window.location.href = url;
        toggleShareMenu();
    }

    function shareViaMessenger(event) {
        event.preventDefault();
        const shareData = getCartShareText();
        const url = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareData.url)}`;
        window.open(url, '_blank', 'width=600,height=400');
        toggleShareMenu();
    }

    // Close share menu when clicking outside
    document.addEventListener('click', function(e) {
        const shareMenu = document.getElementById('shareMenu');
        const shareBtn = document.getElementById('shareBtn');
        if (shareMenu && !shareMenu.contains(e.target) && e.target !== shareBtn && !shareBtn.contains(e.target)) {
            shareMenu.classList.remove('active');
        }
    });

    // Initialize cart
    updateCartUI();

    // Cart button click
    document.getElementById('cartBtn').addEventListener('click', showCart);

    // Lightbox functions
    function openLightbox(img, event) {
        if (event) {
            event.stopPropagation();
        }
        
        const lightbox = document.getElementById('lightbox');
        const lightboxImage = document.getElementById('lightboxImage');
        const lightboxTitle = document.getElementById('lightboxTitle');
        const lightboxSubtitle = document.getElementById('lightboxSubtitle');
        const lightboxDesc = document.getElementById('lightboxDesc');
        const lightboxPrices = document.getElementById('lightboxPrices');

        lightboxImage.src = img.src;
        lightboxImage.alt = img.alt;
        lightboxTitle.textContent = img.dataset.lightboxTitle;
        
        if (img.dataset.lightboxSubtitle) {
            lightboxSubtitle.textContent = img.dataset.lightboxSubtitle;
            lightboxSubtitle.style.display = 'block';
        } else {
            lightboxSubtitle.style.display = 'none';
        }

        if (img.dataset.lightboxDesc) {
            lightboxDesc.textContent = img.dataset.lightboxDesc;
            lightboxDesc.style.display = 'block';
        } else {
            lightboxDesc.style.display = 'none';
        }

        // Build prices HTML
        let pricesHTML = '';
        if (img.dataset.lightboxPrice1) {
            pricesHTML += '<div class="lightbox-price-item">';
            if (img.dataset.lightboxPrice1Label) {
                pricesHTML += '<div class="lightbox-price-label">' + img.dataset.lightboxPrice1Label + '</div>';
            }
            pricesHTML += '<div class="lightbox-price">' + img.dataset.lightboxPrice1 + '</div>';
            pricesHTML += '</div>';
        }
        if (img.dataset.lightboxPrice2) {
            pricesHTML += '<div class="lightbox-price-item">';
            if (img.dataset.lightboxPrice2Label) {
                pricesHTML += '<div class="lightbox-price-label">' + img.dataset.lightboxPrice2Label + '</div>';
            }
            pricesHTML += '<div class="lightbox-price">' + img.dataset.lightboxPrice2 + '</div>';
            pricesHTML += '</div>';
        }
        if (img.dataset.lightboxPrice3) {
            pricesHTML += '<div class="lightbox-price-item">';
            if (img.dataset.lightboxPrice3Label) {
                pricesHTML += '<div class="lightbox-price-label">' + img.dataset.lightboxPrice3Label + '</div>';
            }
            pricesHTML += '<div class="lightbox-price">' + img.dataset.lightboxPrice3 + '</div>';
            pricesHTML += '</div>';
        }
        
        lightboxPrices.innerHTML = pricesHTML;
        if (pricesHTML) {
            lightboxPrices.style.display = 'block';
        } else {
            lightboxPrices.style.display = 'none';
        }

        lightbox.classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    function closeLightbox(event) {
        if (event) event.stopPropagation();
        const lightbox = document.getElementById('lightbox');
        lightbox.classList.add('closing');
        
        setTimeout(() => {
            lightbox.classList.remove('active');
            lightbox.classList.remove('closing');
            document.body.style.overflow = '';
        }, 300);
    }

    // Close lightbox with Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeLightbox();
        }
    });
</script>
</body>
</html>
