<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'lang.php';
require_once 'tracker.php';
require_once __DIR__ . '/../config/db.php';

function e($str) {
    return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8');
}

function translate_field($item, $field, $lang) {
    return ($lang !== 'en' && !empty($item["{$field}_{$lang}"]))
        ? $item["{$field}_{$lang}"]
        : ($item[$field] ?? '');
}

function get_eur_usd_rate() {
    $cache = sys_get_temp_dir() . '/eur_rate.json';
    if (file_exists($cache) && (time() - filemtime($cache)) < 21600) {
        return json_decode(file_get_contents($cache), true)['rate'] ?? 1.08;
    }
    return 1.08;
}

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$db->set_charset("utf8mb4");

$slug = isset($_GET['slug']) ? preg_replace('/[^a-z0-9\-]/', '', strtolower(trim($_GET['slug']))) : '';
$id   = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT) ?: 0;

$columns = "id, slug, name, name_fr, name_de, name_es, name_hu,
            description, description_fr, description_de, description_es, description_hu,
            price, price_huf, image_name, image_hidden, image_order,
            available, wip, size, frame_size, year";

if ($slug) {
    $stmt = $db->prepare("SELECT $columns FROM listings WHERE slug = ?");
    $stmt->bind_param("s", $slug);
} else {
    $stmt = $db->prepare("SELECT $columns FROM listings WHERE id = ?");
    $stmt->bind_param("i", $id);
}

$stmt->execute();
$item = $stmt->get_result()->fetch_assoc();

if (!$item) {
    http_response_code(404);
    echo "404 - Not Found";
    exit;
}

$display_name        = translate_field($item, 'name', $lang);
$display_description = translate_field($item, 'description', $lang);

// Gallery
$gallery_images = [];
if (!empty($item['image_name'])) {
    $base_name  = pathinfo($item['image_name'], PATHINFO_FILENAME);
    $cache_file = __DIR__ . "/cache/gallery_{$base_name}.json";

    if (file_exists($cache_file)) {
        $gallery_images = json_decode(file_get_contents($cache_file), true) ?: [];
    } else {
        $all_files = glob("img/" . $base_name . "/*.{jpg,jpeg,png,webp}", GLOB_BRACE) ?: [];
        if ($all_files) {
            sort($all_files);
            $files_by_suffix = [];
            foreach ($all_files as $f) {
                $bn          = basename($f);
                $without_ext = pathinfo($bn, PATHINFO_FILENAME);
                $suffix      = substr($without_ext, strlen($base_name));
                if ($suffix === '') $suffix = $bn;
                $files_by_suffix[$suffix] = $f;
            }
            $hidden_list = !empty($item['image_hidden'])
                ? array_filter(array_map('trim', explode(',', $item['image_hidden'])))
                : [];
            $ordered = [];
            if (!empty($item['image_order'])) {
                $order_list = array_filter(array_map('trim', explode(',', $item['image_order'])));
                foreach ($order_list as $sfx) {
                    if (isset($files_by_suffix[$sfx]) && !in_array($sfx, $hidden_list)) {
                        $ordered[] = $files_by_suffix[$sfx];
                        unset($files_by_suffix[$sfx]);
                    }
                }
            }
            foreach ($files_by_suffix as $sfx => $f) {
                if (!in_array($sfx, $hidden_list)) $ordered[] = $f;
            }
            $gallery_images = array_slice($ordered, 0, 12);
            if (!is_dir(__DIR__ . '/cache')) mkdir(__DIR__ . '/cache', 0755, true);
            file_put_contents($cache_file, json_encode($gallery_images));
        }
    }
}

$is_available = (int)$item['available'] === 1;
$rate         = get_eur_usd_rate();
$usd_price    = !empty($item['price']) ? number_format((float)$item['price'] * $rate, 0) : null;

$ui = [
    'en' => [
        'back'           => '← Back',
        'free_shipping'  => 'Free Worldwide Shipping',
        'customs_btn'    => 'Shipping to USA? — Original Artwork 0% Customs — Get 2026 info',
        'sold'           => '— Sold —',
        'description'    => 'Description',
        'details'        => 'Details',
        'dimensions'     => 'Dimensions',
        'frame'          => 'Frame Dimensions',
        'year'           => 'Year',
        'shipping_title' => 'Shipping & Delivery',
        'shipping_text'  => 'Free worldwide shipping included via FedEx. Each sculpture is securely packed in a custom crate to ensure safe arrival. A tracking number is provided immediately after dispatch. Shipping from Hungary with a typical delivery time of approximately 5–10 business days.',
        'more_info'      => 'More Info',
        'privacy'        => 'Privacy Policy',
        'add_to_cart'    => 'Add to Cart',
        'cart_sub'       => 'Choose payment at checkout',
        'subscribe'      => 'Subscribe',
        'save_wishlist'  => 'Save to Wishlist',
        'saved_wishlist' => 'Saved!',
    ],
    'fr' => [
        'back'           => '← Retour',
        'free_shipping'  => 'Livraison mondiale gratuite',
        'customs_btn'    => 'Envoi USA? — Œuvre originale 0% de douane — Infos 2026',
        'sold'           => '— Vendu —',
        'description'    => 'Description',
        'details'        => 'Détails',
        'dimensions'     => 'Dimensions',
        'frame'          => 'Dimensions du cadre',
        'year'           => 'Année',
        'shipping_title' => 'Expédition & Livraison',
        'shipping_text'  => 'Livraison mondiale gratuite via FedEx. Chaque sculpture est emballée dans une caisse sur mesure. Un numéro de suivi est fourni immédiatement après l\'expédition. Délai de livraison : 5 à 10 jours ouvrés.',
        'more_info'      => 'Plus d\'infos',
        'privacy'        => 'Politique de confidentialité',
        'add_to_cart'    => 'Ajouter au panier',
        'cart_sub'       => 'Choisissez le paiement à la caisse',
        'subscribe'      => 'S\'abonner',
    ],
    'de' => [
        'back'           => '← Zurück',
        'free_shipping'  => 'Kostenloser weltweiter Versand',
        'customs_btn'    => 'Versand USA? — Originalkunstwerk 0% Zoll — Infos 2026',
        'sold'           => '— Verkauft —',
        'description'    => 'Beschreibung',
        'details'        => 'Details',
        'dimensions'     => 'Abmessungen',
        'frame'          => 'Rahmenmaße',
        'year'           => 'Jahr',
        'shipping_title' => 'Versand & Lieferung',
        'shipping_text'  => 'Kostenloser weltweiter Versand per FedEx. Jede Skulptur wird sicher verpackt. Sendungsverfolgung sofort nach Versand. Lieferzeit ca. 5–10 Werktage.',
        'more_info'      => 'Mehr Infos',
        'privacy'        => 'Datenschutz',
        'add_to_cart'    => 'In den Warenkorb',
        'cart_sub'       => 'Zahlungsmethode an der Kasse wählen',
        'subscribe'      => 'Abonnieren',
        'save_wishlist'  => 'Zur Wunschliste',
        'saved_wishlist' => 'Gespeichert!',
    ],
    'es' => [
        'back'           => '← Volver',
        'free_shipping'  => 'Envío mundial gratuito',
        'customs_btn'    => '¿Envío a EE.UU.? — Obra original 0% aduana — Info 2026',
        'sold'           => '— Vendido —',
        'description'    => 'Descripción',
        'details'        => 'Detalles',
        'dimensions'     => 'Dimensiones',
        'frame'          => 'Dimensiones del marco',
        'year'           => 'Año',
        'shipping_title' => 'Envío y entrega',
        'shipping_text'  => 'Envío mundial gratuito incluido por FedEx. Cada escultura se empaqueta de forma segura. Número de seguimiento inmediatamente después del envío. Plazo de entrega: 5–10 días hábiles.',
        'more_info'      => 'Más información',
        'privacy'        => 'Política de privacidad',
        'add_to_cart'    => 'Añadir al carrito',
        'cart_sub'       => 'Elige el pago en caja',
        'subscribe'      => 'Suscribirse',
        'save_wishlist'  => 'Guardar en favoritos',
        'saved_wishlist' => 'Guardado!',
    ],
    'hu' => [
        'back'           => '← Vissza',
        'free_shipping'  => 'Ingyenes világszintű szállítás',
        'customs_btn'    => 'USA-ba küldés? — Eredeti műtárgy 0% vám — 2026-os infók',
        'sold'           => '— Elkelt —',
        'description'    => 'Leírás',
        'details'        => 'Részletek',
        'dimensions'     => 'Méretek',
        'frame'          => 'Keret méretei',
        'year'           => 'Év',
        'shipping_title' => 'Szállítás & Kézbesítés',
        'shipping_text'  => 'Ingyenes worldwide szállítás FedEx-en keresztül. Minden tárgyat egyedi ládában csomagolunk a biztonságos megérkezés érdekében. A nyomkövetési szám az elküldés után azonnal megérkezik. Magyarországról szállítunk, a szokásos kézbesítési idő kb. 5–10 munkanap.',
        'more_info'      => 'További info',
        'privacy'        => 'Adatvédelmi szabályzat',
        'add_to_cart'    => 'Kosárba',
        'cart_sub'       => 'Fizetési mód a pénztárnál',
        'subscribe'      => 'Feliratkozás',
        'save_wishlist'  => 'Mentés kedvencekbe',
        'saved_wishlist' => 'Mentve!',
    ],
];

$u = $ui[$lang] ?? $ui['en'];

$canonical_url = 'https://www.woboohome.com/items/' . $item['slug'];
$og_image      = !empty($gallery_images[0])
    ? 'https://www.woboohome.com/' . $gallery_images[0]
    : 'https://www.woboohome.com/img/og-image.jpg';
$meta_desc     = !empty($display_description)
    ? mb_substr(strip_tags($display_description), 0, 155) . '...'
    : e($display_name) . ' — Vintage item by WobooHome. Free worldwide shipping.';

$availability = 'https://schema.org/InStock';
if ($item['wip'])       $availability = 'https://schema.org/PreOrder';
elseif (!$is_available) $availability = 'https://schema.org/SoldOut';
?>
<!DOCTYPE html>
<html lang="<?= e($lang) ?>">
<head>
    <base href="/">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title><?= e($display_name) ?> - WobooHome</title>
    <?php render_gtag(); ?>
    <meta name="description" content="<?= e($meta_desc) ?>">
    <meta name="robots" content="index, follow">
    <link rel="canonical" href="<?= $canonical_url ?>">
    <link rel="alternate" hreflang="en"        href="<?= $canonical_url ?>?lang=en">
    <link rel="alternate" hreflang="fr"        href="<?= $canonical_url ?>?lang=fr">
    <link rel="alternate" hreflang="de"        href="<?= $canonical_url ?>?lang=de">
    <link rel="alternate" hreflang="es"        href="<?= $canonical_url ?>?lang=es">
    <link rel="alternate" hreflang="hu"        href="<?= $canonical_url ?>?lang=hu">
    <link rel="alternate" hreflang="x-default" href="<?= $canonical_url ?>">
    <meta property="og:title"       content="<?= e($display_name) ?> - WobooHome">
    <meta property="og:description" content="<?= e($meta_desc) ?>">
    <meta property="og:url"         content="<?= $canonical_url ?>">
    <meta property="og:type"        content="product">
    <meta property="og:image"       content="<?= e($og_image) ?>">
    <script type="application/ld+json">
    {
      "@context": "https://schema.org/",
      "@type": "Product",
      "name": "<?= e($display_name) ?>",
      "category": "Vintage",
      "image": "<?= e($og_image) ?>",
      "description": <?= json_encode(strip_tags($meta_desc)) ?>,
      "brand": { "@type": "Brand", "name": "WobooHome" },
      "offers": {
        "@type": "Offer",
        "priceCurrency": "EUR",
        "price": "<?= e($item['price']) ?>",
        "availability": "<?= $availability ?>",
        "url": "<?= $canonical_url ?>",
        "shippingDetails": {
          "@type": "OfferShippingDetails",
          "shippingRate": { "@type": "MonetaryAmount", "value": "0", "currency": "EUR" },
          "shippingDestination": {
            "@type": "DefinedRegion",
            "addressCountry": ["HU","DE","GB","US","FR","AT","IT","ES","NL","BE","PL","SE","DK","NO","FI","PT","IE","CZ","SK","RO","CA","AU","NZ","JP","SG","CH"]
          },
          "deliveryTime": {
            "@type": "ShippingDeliveryTime",
            "handlingTime": { "@type": "QuantitativeValue", "minValue": 1, "maxValue": 3,  "unitCode": "DAY" },
            "transitTime":  { "@type": "QuantitativeValue", "minValue": 5, "maxValue": 10, "unitCode": "DAY" }
          }
        },
        "hasMerchantReturnPolicy": {
          "@type": "MerchantReturnPolicy",
          "applicableCountry": ["HU","DE","GB","US","FR","AT","IT","ES","NL","BE","PL","SE","DK","NO","FI","PT","IE","CZ","SK","RO","CA","AU","NZ","JP","SG","CH"],
          "returnPolicyCategory": "https://schema.org/MerchantReturnFiniteReturnWindow",
          "merchantReturnDays": 14,
          "returnMethod": "https://schema.org/ReturnByMail",
          "returnFees": "https://schema.org/FreeReturn"
        }
      }
    }
    </script>
    <link rel="stylesheet" href="/style10.css">
    <link rel="stylesheet" href="/wishlist.css">
    <style>
        body.lightbox-open { overflow: hidden; position: fixed; width: 100%; height: 100%; }

        .product-topbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 0 10px;
        }

        .btn-back {
            text-transform: uppercase;
            letter-spacing: 3px;
            color: #94a3b8;
            text-decoration: none;
            font-size: 13px;
            transition: color 0.2s;
        }
        .btn-back:hover { color: #d4a017; }

        /* ===== PRODUCT GRID ===== */
        .product-grid {
            display: flex;
            gap: 40px;
            padding: 20px 0 40px;
            align-items: flex-start;
        }
        .product-col-left  { flex: 1; min-width: 0; }
        .product-col-right { width: 340px; flex-shrink: 0; position: sticky; top: 20px; }

        @media (max-width: 900px) {
            .product-grid { flex-direction: column; gap: 0; }
            .product-col-right { width: 100%; position: static; }
        }

        /* ===== PURCHASE BOX ===== */
        .purchase-box {
            border: 1px solid #e2e8f0;
            background: #fafafa;
            padding: 24px;
            text-align: center;
            margin-bottom: 20px;
            border-radius: 16px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .pb-title {
            font-size: 17px;
            font-weight: 600;
            letter-spacing: 1px;
            color: #0f172a;
            margin-bottom: 12px;
            line-height: 1.4;
        }
        .price-primary {
            font-size: 32px;
            font-weight: 700;
            color: #d4a017;
            display: block;
            line-height: 1;
        }
        .price-usd {
            font-size: 14px;
            color: #94a3b8;
            display: block;
            margin-top: 4px;
        }
        .shipping-text {
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: #0f172a;
            margin: 12px 0;
        }
        .btn-pay {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            border-radius: 14px;
            padding: 10px 16px;
            text-decoration: none;
            margin: 6px 0;
            transition: transform 0.15s, background 0.2s, border-color 0.2s;
            cursor: pointer;
            width: 100%;
            box-sizing: border-box;
            font-family: inherit;
        }
        .btn-pay:hover { transform: translateY(-1px); }
        .btn-pay-left { display: flex; flex-direction: column; gap: 2px; text-align: left; }
        .btn-pay-title { font-size: 16px; font-weight: 600; white-space: nowrap; }
        .btn-pay-sub   { font-size: 12px; white-space: nowrap; }
        .btn-pay-stripe { background: #e8f4fd; border: 1.5px solid #b3d9f5; }
        .btn-pay-stripe:hover { background: #d4ecfa; border-color: #7fc4ef; }
        .btn-pay-stripe .btn-pay-title { color: #1a6fa8; }
        .btn-pay-stripe .btn-pay-sub   { color: #5a9fc7; }
        .btn-info-outline {
            display: block;
            border: 1px solid #e2e8f0;
            color: #94a3b8;
            padding: 8px 12px;
            text-decoration: none;
            font-size: 11px;
            font-weight: 500;
            border-radius: 8px;
            width: 100%;
            box-sizing: border-box;
            margin-top: 10px;
            letter-spacing: 0.5px;
            text-align: center;
        }
        .btn-info-outline:hover { border-color: #94a3b8; color: #64748b; }
        .sold-badge {
            font-size: 20px;
            font-weight: 700;
            color: #94a3b8;
            letter-spacing: 4px;
            text-transform: uppercase;
            padding: 16px 0;
        }

        /* ===== GALÉRIA ===== */
        .gallery-main-wrap {
            position: relative;
            width: 100%;
            padding-top: 100%;
            background: #f8fafc;
            border-radius: 14px;
            overflow: hidden;
            margin-bottom: 10px;
            cursor: zoom-in;
        }
        .gallery-main-wrap img {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 14px;
            transition: opacity 0.2s;
        }
        .gallery-arrow {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(255,255,255,0.88);
            border: none;
            border-radius: 50%;
            width: 38px;
            height: 38px;
            font-size: 18px;
            cursor: pointer;
            z-index: 2;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.2s;
            box-shadow: 0 2px 8px rgba(0,0,0,0.10);
        }
        .gallery-arrow:hover { background: #fff; }
        .gallery-arrow.prev { left: 10px; }
        .gallery-arrow.next { right: 10px; }

        .gallery-thumbs {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            gap: 6px;
            margin-bottom: 0;
        }
        @media (max-width: 600px) {
            .gallery-thumbs { grid-template-columns: repeat(5, 1fr); }
        }
        .gallery-thumb {
            aspect-ratio: 1;
            border-radius: 7px;
            overflow: hidden;
            cursor: pointer;
            border: 2px solid transparent;
            opacity: 0.65;
            transition: opacity 0.15s, border-color 0.15s;
        }
        .gallery-thumb:hover { opacity: 0.9; }
        .gallery-thumb.active {
            border-color: #d4a017;
            opacity: 1;
        }
        .gallery-thumb img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
        }

        /* ===== INFO SECTIONS ===== */
        .info-grid {
            display: flex;
            gap: 40px;
            border-top: 1px solid #f1f5f9;
            padding: 40px 0;
        }
        .info-block { flex: 1; min-width: 0; }
        @media (max-width: 768px) {
            .info-grid { flex-direction: column; gap: 24px; }
        }
        .info-title {
            text-transform: uppercase;
            letter-spacing: 3px;
            font-size: 12px;
            font-weight: 700;
            color: #94a3b8;
            margin-bottom: 16px;
        }
        .info-content {
            font-size: 15px;
            color: #475569;
            line-height: 1.8;
        }
        .info-section-full {
            border-top: 1px solid #f1f5f9;
            padding: 40px 0;
        }
        .tech-list { list-style: none; padding: 0; }
        .tech-list li {
            margin-bottom: 10px;
            border-bottom: 1px solid #f8fafc;
            padding-bottom: 8px;
            font-size: 14px;
            color: #475569;
        }
        .tech-list b { color: #0f172a; display: inline-block; width: 160px; }

        /* ===== MORE INFO ===== */
        .more-info-section {
            border-top: 1px solid #f1f5f9;
            padding: 40px 0;
            text-align: center;
        }
        .btn-more-info {
            display: inline-block;
            padding: 16px 40px;
            border: 2px solid #d4a017;
            color: #d4a017;
            font-size: 18px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 2px;
            text-decoration: none;
            border-radius: 50px;
            transition: 0.3s;
        }
        .btn-more-info:hover { background: #d4a017; color: #fff; }

        /* ===== LIGHTBOX ===== */
        #custom-lightbox {
            display: none;
            position: fixed;
            z-index: 999999;
            left: 0; top: 0;
            width: 100%; height: 100%;
            background: #fff;
            overflow: hidden;
            touch-action: none;
        }
        .slider-container {
            display: flex;
            height: 100%;
            width: 100%;
            will-change: transform;
            touch-action: pan-x;
        }
        .slide {
            min-width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0 10px;
            box-sizing: border-box;
        }
        .slide img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            cursor: pointer;
            border-radius: 10px;
            -webkit-user-drag: none;
        }
        .lb-close {
            position: absolute;
            top: 20px; right: 40px;
            font-size: 40px;
            cursor: pointer;
            color: #000;
            opacity: 0.5;
            z-index: 1000001;
            transition: opacity 0.2s;
        }
        .lb-close:hover { opacity: 1; }
        .lb-nav {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            font-size: 40px;
            color: #666;
            cursor: pointer;
            padding: 30px;
            z-index: 1000000;
            transition: color 0.2s;
        }
        .lb-nav:hover { color: #000; }
        @media (max-width: 768px) { .lb-nav { display: none; } }

        /* ===== PRODUCT FOOTER ===== */
        .product-footer {
            border-top: 1px solid #f1f5f9;
            padding: 28px 0;
            text-align: center;
            color: #cbd5e1;
            font-size: 13px;
        }
        .product-footer a {
            color: #cbd5e1;
            font-size: 12px;
            text-decoration: none;
            letter-spacing: 1px;
            text-transform: uppercase;
        }
        .product-footer a:hover { color: #94a3b8; }
    </style>
</head>
<body>

<?php include 'cookie-banner.php'; ?>

<!-- Lightbox -->
<div id="custom-lightbox">
    <div class="lb-close" onclick="closeLightbox()">&times;</div>
    <div class="lb-nav" style="left:0" onclick="changeSlide(-1)">❮</div>
    <div class="lb-nav" style="right:0" onclick="changeSlide(1)">❯</div>
    <div class="slider-container" id="slider"></div>
</div>

<div class="container">

    <!-- Top bar -->
    <div class="product-topbar">
        <a href="/" class="btn-back"><?= e($u['back']) ?></a>
        <div class="lang-switcher" id="langSwitcher">
            <button class="lang-btn" onclick="toggleLang(event)">
                <span><?= $all_languages[$lang]['flag'] ?></span>
                <span><?= $all_languages[$lang]['label'] ?></span>
                <span class="arrow">▼</span>
            </button>
            <div class="lang-dropdown">
                <?php foreach ($all_languages as $code => $info): ?>
                    <a href="/items/<?= $item['slug'] ?>?lang=<?= $code ?>"
                       class="<?= $lang === $code ? 'active' : '' ?>">
                        <span><?= $info['flag'] ?></span>
                        <span><?= $info['label'] ?></span>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Product grid: bal = galéria, jobb = vásárlás -->
    <div class="product-grid">

        <!-- BAL OSZLOP: Galéria -->
        <div class="product-col-left">
            <?php if (!empty($gallery_images)): ?>
                <!-- Főkép -->
                <div class="gallery-main-wrap" id="galleryMain" onclick="openLightbox(currentThumb)">
                    <img id="mainImg"
                         src="<?= e($gallery_images[0]) ?>"
                         alt="<?= e($display_name) ?>"
                         fetchpriority="high" loading="eager">
                    <?php if (count($gallery_images) > 1): ?>
                        <button class="gallery-arrow prev" onclick="event.stopPropagation(); thumbNav(-1)">❮</button>
                        <button class="gallery-arrow next" onclick="event.stopPropagation(); thumbNav(1)">❯</button>
                    <?php endif; ?>
                </div>
                <!-- Thumbok -->
                <?php if (count($gallery_images) > 1): ?>
                <div class="gallery-thumbs">
                    <?php foreach ($gallery_images as $i => $img): ?>
                        <div class="gallery-thumb <?= $i === 0 ? 'active' : '' ?>"
                             onclick="setThumb(<?= $i ?>)">
                            <img src="<?= e($img) ?>"
                                 alt="<?= e($display_name) ?> <?= $i + 1 ?>"
                                 loading="<?= $i < 6 ? 'eager' : 'lazy' ?>">
                        </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- JOBB OSZLOP: Vásárlás (sticky) -->
        <div class="product-col-right">
            <div class="purchase-box">
                <p class="pb-title"><?= e($display_name) ?></p>

                <?php if ($is_hu && !empty($item['price_huf'])): ?>
                    <span class="price-primary"><?= number_format($item['price_huf']) ?> Ft</span>
                <?php else: ?>
                    <span class="price-primary">&euro; <?= e($item['price']) ?></span>
                    <?php if ($usd_price): ?>
                        <span class="price-usd">≈ $<?= e($usd_price) ?> USD</span>
                    <?php endif; ?>
                <?php endif; ?>

                <?php if ($is_available): ?>
                    <div class="shipping-text"><?= e($u['free_shipping']) ?></div>
                    <div style="width:100%">
                        <form method="POST" action="/cart-add.php">
                            <input type="hidden" name="id" value="<?= (int)$item['id'] ?>">
                            <button type="submit" class="btn-pay btn-pay-stripe">
                                <div class="btn-pay-left">
                                    <span class="btn-pay-title">🛒 <?= e($u['add_to_cart']) ?></span>
                                    <span class="btn-pay-sub"><?= e($u['cart_sub']) ?></span>
                                </div>
                            </button>
                        </form>
                    </div>
                    <a href="customs-info.html" class="btn-info-outline"><?= e($u['customs_btn']) ?></a>
                <?php else: ?>
                    <div class="sold-badge"><?= e($u['sold']) ?></div>
                <?php endif; ?>
            </div>

            <!-- Details -->
            <?php if (!empty($item['size']) || !empty($item['frame_size']) || !empty($item['year'])): ?>
            <div style="padding: 0 0 20px;">
                <h2 class="info-title"><?= e($u['details']) ?></h2>
                <ul class="tech-list info-content">
                    <?php if (!empty($item['size'])): ?>
                        <li><b><?= e($u['dimensions']) ?>:</b> <?= e($item['size']) ?></li>
                    <?php endif; ?>
                    <?php if (!empty($item['frame_size'])): ?>
                        <li><b><?= e($u['frame']) ?>:</b> <?= e($item['frame_size']) ?></li>
                    <?php endif; ?>
                    <?php if (!empty($item['year'])): ?>
                        <li><b><?= e($u['year']) ?>:</b> <?= e($item['year']) ?></li>
                    <?php endif; ?>
                </ul>
            </div>
            <?php endif; ?>

            <!-- Shipping info -->
            <div>
                <h2 class="info-title"><?= e($u['shipping_title']) ?></h2>
                <div class="info-content" style="font-size:14px;">
                    <p><?= e($u['shipping_text']) ?></p>
                </div>
            </div>
        </div>

    </div>

    <!-- Description -->
    <?php if (!empty($display_description)): ?>
    <div class="info-section-full">
        <h2 class="info-title"><?= e($u['description']) ?></h2>
        <div class="info-content">
            <p><?= nl2br(e($display_description)) ?></p>
        </div>
    </div>
    <?php endif; ?>
	
	
	<div class="info-section-full" style="background: #f8fafc; border-radius: 16px; padding: 30px; margin-top: 20px;">
    <h2 class="info-title" style="margin-bottom: 10px;">Kérdésed van a tárgyról?</h2>
    <p class="info-content" style="font-size: 14px; margin-bottom: 20px;">
        Írj közvetlenül az eladónak! Szívesen válaszolok bármilyen technikai vagy szállítási kérdésre.
    </p>
    
    <form id="contact-seller-form" action="send-message.php" method="POST" style="display: flex; flex-direction: column; gap: 12px;">
        <input type="hidden" name="product_name" value="<?= e($display_name) ?>">
        <input type="hidden" name="product_slug" value="<?= e($item['slug']) ?>">

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
            <input type="text" name="name" placeholder="Neved" required 
                   style="padding: 12px; border: 1px solid #e2e8f0; border-radius: 8px; font-family: inherit;">
            <input type="email" name="email" placeholder="E-mail címed" required 
                   style="padding: 12px; border: 1px solid #e2e8f0; border-radius: 8px; font-family: inherit;">
        </div>
        
        <textarea name="message" placeholder="Üzeneted az eladónak..." required rows="4" 
                  style="padding: 12px; border: 1px solid #e2e8f0; border-radius: 8px; font-family: inherit; resize: vertical;"></textarea>
        
        <button type="submit" class="btn-pay" style="background: #0f172a; color: white; justify-content: center; border: none;">
            <span class="btn-pay-title">Üzenet küldése</span>
        </button>
    </form>
    <div id="form-response" style="margin-top: 10px; font-size: 14px; text-align: center; display: none;"></div>
</div>
	
	
	
	
	
    <!-- More info -->
    <div class="more-info-section">
        <a href="more-info.html" class="btn-more-info"><?= e($u['more_info']) ?></a>
    </div>

</div>

<!-- Footer -->
<div class="product-footer">
    <p>&copy; 2026 WobooHome</p>
    <a href="privacy-policy.php"><?= e($u['privacy']) ?></a>
</div>

<!-- Subscribe gomb -->
<a href="contact.php#newsletter" id="subscribe-btn"
   style="position:fixed;bottom:24px;right:24px;background:#0f172a;color:#fff;text-decoration:none;padding:12px 22px;border-radius:30px;font-size:12px;font-weight:600;letter-spacing:1px;text-transform:uppercase;box-shadow:0 4px 20px rgba(0,0,0,0.25);z-index:99;display:flex;align-items:center;gap:8px;opacity:0;transform:translateY(12px);transition:opacity 0.4s,transform 0.4s;pointer-events:none;">
    ✉ <?= e($u['subscribe']) ?>
</a>

<script>
// Subscribe scroll
window.addEventListener('scroll', function() {
    var btn = document.getElementById('subscribe-btn');
    if (window.scrollY > 300) {
        btn.style.opacity = '1';
        btn.style.transform = 'translateY(0)';
        btn.style.pointerEvents = 'auto';
    } else {
        btn.style.opacity = '0';
        btn.style.transform = 'translateY(12px)';
        btn.style.pointerEvents = 'none';
    }
});

// Lang switcher
function toggleLang(e) {
    e.stopPropagation();
    document.getElementById('langSwitcher').classList.toggle('open');
}
document.addEventListener('click', function() {
    document.getElementById('langSwitcher').classList.remove('open');
});

// ===== GALÉRIA =====
const galleryImages = <?= json_encode(array_values($gallery_images)) ?>;
let currentThumb = 0;

function setThumb(index) {
    currentThumb = index;
    const mainImg = document.getElementById('mainImg');
    mainImg.style.opacity = '0';
    setTimeout(() => {
        mainImg.src = galleryImages[index];
        mainImg.style.opacity = '1';
    }, 150);
    document.querySelectorAll('.gallery-thumb').forEach((t, i) => {
        t.classList.toggle('active', i === index);
    });
}

function thumbNav(dir) {
    let next = currentThumb + dir;
    if (next < 0) next = galleryImages.length - 1;
    if (next >= galleryImages.length) next = 0;
    setThumb(next);
}

// Billentyűzet navigáció
document.addEventListener('keydown', function(e) {
    if (document.getElementById('custom-lightbox').style.display === 'block') return;
    if (e.key === 'ArrowLeft')  thumbNav(-1);
    if (e.key === 'ArrowRight') thumbNav(1);
});

// ===== LIGHTBOX =====
let currentIndex = 1;
const slider = document.getElementById('slider');
let startX = 0, startY = 0, currentTranslate = 0, prevTranslate = 0, isDragging = false;

function initLightbox() {
    if (!galleryImages.length) return;
    const images = [galleryImages[galleryImages.length - 1], ...galleryImages, galleryImages[0]];
    slider.innerHTML = images.map(src =>
        `<div class="slide"><img src="${src}" onclick="closeLightbox()" style="user-select:none;"></div>`
    ).join('');
}
initLightbox();

function openLightbox(index) {
    currentIndex = index + 1;
    document.getElementById('custom-lightbox').style.display = 'block';
    document.body.classList.add('lightbox-open');
    updateSlider(false);
}

function closeLightbox() {
    document.getElementById('custom-lightbox').style.display = 'none';
    document.body.classList.remove('lightbox-open');
}

function changeSlide(n) {
    currentIndex += n;
    updateSlider(true);
    setTimeout(() => {
        if (currentIndex >= galleryImages.length + 1) { currentIndex = 1; updateSlider(false); }
        if (currentIndex <= 0) { currentIndex = galleryImages.length; updateSlider(false); }
    }, 300);
}

function updateSlider(withAnimation) {
    slider.style.transition = withAnimation ? 'transform 0.4s cubic-bezier(0.25,0.46,0.45,0.94)' : 'none';
    currentTranslate = currentIndex * -window.innerWidth;
    prevTranslate = currentTranslate;
    slider.style.transform = `translateX(${currentTranslate}px)`;
}

document.addEventListener('keydown', function(e) {
    if (document.getElementById('custom-lightbox').style.display !== 'block') return;
    if (e.key === 'ArrowLeft')  changeSlide(-1);
    if (e.key === 'ArrowRight') changeSlide(1);
    if (e.key === 'Escape') closeLightbox();
});

slider.addEventListener('touchstart', e => {
    startX = e.touches[0].clientX;
    startY = e.touches[0].clientY;
    isDragging = true;
    slider.style.transition = 'none';
}, { passive: true });

slider.addEventListener('touchmove', e => {
    if (!isDragging) return;
    const diffX = e.touches[0].clientX - startX;
    const diffY = e.touches[0].clientY - startY;
    if (Math.abs(diffX) > Math.abs(diffY)) {
        if (e.cancelable) e.preventDefault();
        slider.style.transform = `translateX(${prevTranslate + diffX}px)`;
    }
}, { passive: false });

slider.addEventListener('touchend', e => {
    isDragging = false;
    const diff = e.changedTouches[0].clientX - startX;
    if (Math.abs(diff) > 50) {
        diff > 0 ? changeSlide(-1) : changeSlide(1);
    } else {
        updateSlider(true);
    }
});

window.addEventListener('resize', () => updateSlider(false));
</script>

<script src='/wishlist.js'></script>
<?php include 'tracker_js.php'; ?>
</body>
</html>