// ACYLGRAPHIC — Main app

const { useState, useEffect, useRef, useCallback } = React;

const S1000RR_IMAGES = {
  hero: "https://mediapool.bmwgroup.com/cache/P9/202209/P90479706/P90479706-the-new-bmw-s-1000-rr-lightwhite-non-metallic-bmw-m-09-2022-2666px.jpg",
  studio: "https://mediapool.bmwgroup.com/cache/P9/202410/P90573610/P90573610-the-new-bmw-s-1000-rr-10-2024-2666px.jpg",
  front: "https://www.bmwmotorcycles.com/content/dam/bmwmotorradnsc/common/images/models/sport/s1000rr/2024/multigallery/nsc-multigallery-fullscreen-02-s1000rr-P0N3H.jpg.asset.1738587630061.jpg",
  fairing: "https://www.bmwmotorcycles.com/content/dam/bmwmotorradnsc/common/images/models/sport/s1000rr/2024/multigallery/nsc-multigallery-fullscreen-01-s1000rr-P0N3H.jpg.asset.1738587629821.jpg",
  winglet: "https://www.bmwmotorcycles.com/content/dam/bmwmotorradnsc/common/images/models/sport/s1000rr/2024/multigallery/nsc-multigallery-02-s-s1000rr-P0N3H.jpg.asset.1738587627857.jpg",
  detail: "https://www.bmwmotorcycles.com/content/dam/bmwmotorradnsc/common/images/models/sport/s1000rr/2024/multigallery/nsc-multigallery-01-s-s1000rr-P0N3H.jpg.asset.1738587627590.jpg"
};

const CUSTOM_COMPARE_IMAGES = {
  before: "/assets/custom-before.png",
  after: "/assets/custom-after.png"
};
const GARAGE_HERO_IMAGE = "/assets/garage-hero-bike.png";
const SOCIAL_POSTS = {
  a07Mockup: {
    url: "https://www.instagram.com/p/DYNHex8Nx6A/",
    thumbnail: "/assets/instagram-a07-post.png"
  }
};

function RealBikeImage({ src, className = "", alt = "BMW S 1000 RR", draggable }) {
  return <img className={`real-bike-img ${className}`} src={src} alt={alt} loading="lazy" draggable={draggable ?? "true"}/>;
}

const WHATSAPP_PHONE = "905301822601"; // WhatsApp numaranızı buraya girin (örn: 905551234567)
const INSTAGRAM_HANDLE = "acyl.graphics"; // Instagram kullanıcı adınız
const ROUTE_LANGS = ["tr", "en"];

const PAGES = [
  { key: "garaj",    slug: { tr: "garaj",    en: "garage"  }, label: { tr: "Garaj",    en: "Garage"  }, title: { tr: "Garaj",        en: "Garage"  } },
  { key: "magaza",   slug: { tr: "magaza",   en: "shop"    }, label: { tr: "Mağaza",   en: "Shop"    }, title: { tr: "Mağaza",       en: "Shop"    } },
  { key: "ozel",     slug: { tr: "ozel",     en: "custom"  }, label: { tr: "Özel",     en: "Custom"  }, title: { tr: "Özel Tasarım", en: "Custom"  } },
  { key: "akis",     slug: { tr: "akis",     en: "feed"    }, label: { tr: "Akış",     en: "Feed"    }, title: { tr: "Akış",         en: "Feed"    } },
  { key: "studyo",   slug: { tr: "studyo",   en: "studio"  }, label: { tr: "Stüdyo",   en: "Studio"  }, title: { tr: "Stüdyo",       en: "Studio"  } },
  { key: "iletisim", slug: { tr: "iletisim", en: "contact" }, label: { tr: "İletişim", en: "Contact" }, title: { tr: "İletişim",     en: "Contact" } },
];

const INFO_PAGES = [
  { key: "uygulama-kilavuzu", group: "service", slug: { tr: "uygulama-kilavuzu", en: "application-guide" }, label: { tr: "Uygulama Kılavuzu", en: "Application Guide" } },
  { key: "kargo-bilgisi", group: "service", slug: { tr: "kargo-bilgisi", en: "shipping-info" }, label: { tr: "Kargo Bilgisi", en: "Shipping Info" } },
  { key: "iade-politikasi", group: "service", slug: { tr: "iade-politikasi", en: "return-policy" }, label: { tr: "İade Politikası", en: "Return Policy" } },
  { key: "gizlilik-politikasi", group: "legal", slug: { tr: "gizlilik-politikasi", en: "privacy-policy" }, label: { tr: "Gizlilik Politikası", en: "Privacy Policy" } },
  { key: "kullanim-kosullari", group: "legal", slug: { tr: "kullanim-kosullari", en: "terms-of-use" }, label: { tr: "Kullanım Koşulları", en: "Terms of Use" } },
  { key: "satis-kosullari", group: "legal", slug: { tr: "satis-kosullari", en: "sales-terms" }, label: { tr: "Satış Koşulları", en: "Sales Terms" } },
];

const ALL_PAGES = [...PAGES, ...INFO_PAGES];

function getRouteInfo() {
  const parts = window.location.pathname.split("/").filter(Boolean);
  const lang = ROUTE_LANGS.includes(parts[0]) ? parts[0] : "tr";
  const rest = ROUTE_LANGS.includes(parts[0]) ? parts.slice(1) : parts;

  if (rest[0] === "products" && rest[1]) {
    const productId = Number(rest[1]);
    return { lang, page: "magaza", productId: Number.isFinite(productId) ? productId : null };
  }

  const slug = rest[0];
  const found = ALL_PAGES.find(p => p.slug.tr === slug || p.slug.en === slug);
  return { lang, page: found?.key || "garaj", productId: null };
}

function setRouteLang(lang, currentPage) {
  const page = ALL_PAGES.find(p => p.key === currentPage);
  const slug = page?.slug[lang] || "garaj";
  window.history.pushState({}, "", `/${lang}/${slug}`);
  window.dispatchEvent(new Event("languagechange"));
}

function navigate(lang, pageKey) {
  const page = ALL_PAGES.find(p => p.key === pageKey);
  const slug = page?.slug[lang] || pageKey;
  window.history.pushState({}, "", `/${lang}/${slug}`);
  window.dispatchEvent(new Event("routechange"));
}

function buildWhatsappUrl(productTitle) {
  const msg = productTitle
    ? `Merhaba ACYL/GRAPHIC! "${productTitle}" ürünü için sipariş vermek istiyorum.`
    : `Merhaba ACYL/GRAPHIC! Ürünleriniz hakkında bilgi almak istiyorum.`;
  return `https://wa.me/${WHATSAPP_PHONE}?text=${encodeURIComponent(msg)}`;
}

function buildInstagramUrl() {
  return `https://www.instagram.com/${INSTAGRAM_HANDLE}/`;
}

const TRANSLATIONS = {
  tr: {
    title: "ACYL/GRAPHIC — Tasarım Hızı.",
    text: {
      "Garage": "Garaj",
      "Shop": "Mağaza",
      "Custom": "Özel",
      "Feed": "Akış",
      "Studio": "Stüdyo",
      "Contact": "İletişim",
      "EST. 2019 · IT": "KUR. 2019 · TR",
      "Cart": "Sepet",
      "PERFORMANCE GRAPHICS · DROP 07 LIVE": "PERFORMANS GRAFİKLERİ · DROP 07 YAYINDA",
      "N 41.0082° · E 28.9784° / ISTANBUL STUDIO": "İSTANBUL STÜDYO / ÖZEL TASARIM",
      "Builds Wrapped": "Kaplanan Motor",
      "Active Liveries": "Aktif Tasarım",
      "Riders": "Sürücü",
      "Design": "Tasarım",
      "Speed": "Hız",
      "Visualised": "Görselleşti",
      "Aggression": "Agresyon",
      "Velocity": "Hızlanma",
      "engineers cinematic decal kits, racing liveries and helmet graphics for riders who treat their bike like a moving canvas. Cut on cast vinyl. Built for 300 km/h.": "hareket eden bir tuval gibi görülen motosikletler için sinematik sticker kitleri, yarış kaplamaları ve kask grafikleri tasarlar. Cast vinyl kesim. 300 km/h için üretildi.",
      "VINYL · 6Y OUTDOOR": "VİNİL · 6 YIL DIŞ MEKAN",
      "Cast 3M™ 2080": "Cast 3M™ 2080",
      "TURN-AROUND": "TESLİM SÜRESİ",
      "7—14 Days": "7—14 Gün",
      "Explore Collection": "Koleksiyonu İncele",
      "Order Custom": "Özel Sipariş",
      "View Garage": "Garajı Gör",
      "BMW S1000RR · REAL BIKE MOCKUP": "BMW S1000RR · GERÇEK MOTOR MOCKUP",
      "Tank Decal Kit": "Depo Sticker Kiti",
      "Windshield Tint": "Ön Cam Tonu",
      "Tail Stripe": "Kuyruk Şeridi",
      "Front Fairing": "Ön Grenaj",
      "Cast Vinyl": "Cast Vinil",
      "Helmet Wraps": "Kask Kaplama",
      "Racing Liveries": "Yarış Kaplamaları",
      "Fairing Kits": "Grenaj Kitleri",
      "Worldwide Shipping": "Dünya Çapında Kargo",
      "Built In Studio": "Stüdyoda Üretildi",
      "02 · Featured · 18 Active SKUs": "02 · Öne Çıkanlar · 18 Aktif Ürün",
      "Collection": "Koleksiyon",
      "// Drop 07": "// Drop 07",
      "All": "Tümü",
      "Tanks": "Depo",
      "Helmets": "Kask",
      "Liveries": "Kaplama",
      "Fairings": "Grenaj",
      "Sorting": "Sıralama",
      "NEWEST · ↓": "EN YENİ · ↓",
      "DEPO · DROP 07": "DEPO · DROP 07",
      "YENI": "YENİ",
      "KASK": "KASK",
      "YARIS LIVERY": "YARIŞ KAPLAMA",
      "LIMITED": "SINIRLI",
      "GRENAJ": "GRENAJ",
      "ON SIPARIS": "ÖN SİPARİŞ",
      "Tam depo flame kit. Cast vinyl, parlak laminasyon.": "Tam depo alev kiti. Cast vinyl, parlak laminasyon.",
      "AGV / Shoei uyumlu yan sticker seti.": "AGV / Shoei uyumlu yan sticker seti.",
      "Orta hat yaris seridi. 30 numarali set.": "Orta hat yarış şeridi. 30 numaralı set.",
      "Tam kask kaplama seti. Cok parcali, hazir kesim.": "Tam kask kaplama seti. Çok parçalı, hazır kesim.",
      "ACYLGRAPHIC logo sticker, aynali takim.": "ACYLGRAPHIC logo sticker, aynalı takım.",
      "Karbon zeminli geometrik grenaj deseni.": "Karbon zeminli geometrik grenaj deseni.",
      "Sipariş ver →": "Sipariş ver →",
      "03 · Custom Workflow": "03 · Özel Tasarım Akışı",
      "You Design The Idea.": "Fikri Sen Ver.",
      "We Engineer": "Biz Yüzeye",
      "The Surface.": "Uygulayalım.",
      "Every commission is rendered, validated, then plotted on the same cast vinyl factory teams use. No reseller. No middleman. Designer-to-rider, every time.": "Her özel iş önce render edilir, doğrulanır ve fabrika takımlarının kullandığı cast vinyl üzerine kesilir. Aracı yok. Bayi yok. Tasarımcıdan sürücüye.",
      "BEFORE": "ÖNCE",
      "AFTER · A-07": "SONRA · A-07",
      "Brief & Reference": "Brief ve Referans",
      "Drop bike specs, references, target circuit, paint codes. We translate intent into design language within 48h.": "Motor bilgilerini, referansları, hedef pist/renk kodlarını gönder. Fikri 48 saat içinde tasarım diline çeviririz.",
      "Mock-Up Render": "Mockup Render",
      "Side / front / rear photoreal renders on your actual fairing. Two directions, infinite micro-edits.": "Gerçek grenaj üzerinde yan / ön / arka fotogerçekçi render. İki yön, sınırsız mikro revize.",
      "Print & Cut": "Baskı ve Kesim",
      "Cast 3M vinyl, gloss laminate, plotter-cut to silhouette. Quality-controlled per panel.": "Cast 3M vinyl, parlak laminasyon, silüete göre plotter kesim. Panel panel kalite kontrol.",
      "Ship & Apply": "Kargo ve Uygulama",
      "Worldwide tracked shipping with squeegee, primer wipe, full application guide & timelapse video.": "Takipli kargo; rakle, primer mendil, uygulama rehberi ve timelapse video ile gönderim.",
      "04 · The Feed": "04 · Sosyal Akış",
      "Worn In": "Yolda",
      "Worn": "Yüksek",
      "Loud": "Sesli",
      "BMW S1000RR — A-07 Mockup": "BMW S1000RR — A-07 Mockup",
      "Front fairing winglet study": "Ön grenaj winglet çalışması",
      "S1000RR side panel decal zone": "S1000RR yan panel sticker alanı",
      "RR sticker placement breakdown": "RR sticker yerleşim analizi",
      "Layering inferno kit over M trim": "M trim üzerine inferno katmanları",
      "S1000RR full livery direction": "S1000RR tam kaplama yönü",
      "saves": "kaydetme",
      "plays": "izlenme",
      "Watch": "İzle",
      "05 · Behind The Plotter": "05 · Plotter’ın Arkasında",
      "One Designer.": "Tek Tasarımcı.",
      "Every Cut.": "Her Kesim.",
      "From İstanbul.": "İstanbul'dan.",
      "ACYLGRAPHIC is a one-person studio built around a single obsession — making bikes look as fast as they go. No agency. No outsourcing.": "ACYLGRAPHIC, motosikletlerin gittiği kadar hızlı görünmesini sağlamak üzerine kurulu tek kişilik bir stüdyo. Ajans yok. Dış kaynak yok.",
      "Founder / Designer": "Kurucu / Tasarımcı",
      "A bike is a sculpture going": "Motosiklet,",
      "300 km/h": "300 km/h",
      "My job is to make sure that sculpture has a soundtrack.": "giden bir heykeldir. Benim işim o heykele bir ses kazandırmak.",
      "Builds Wrapped": "Kaplanan Motor",
      "Countries Shipped": "Ülkeye Kargo",
      "In Operation": "Yıllık Deneyim",
      "Cut In-House": "Stüdyo Kesim",
      "06 · Rider Logs": "06 · Sürücü Yorumları",
      "Garage": "Garaj",
      "Says": "Ne Diyor",
      "4.97 · 312 reviews": "4.97 · 312 yorum",
      /*"07 · Next Drop · Spring 2026": "07 · Sıradaki Drop · İlkbahar 2026",*/
      "Make Your Bike": "Motorunu",
      "Impossible": "Gözden",
      "To Miss.": "Kaçırılmaz Yap.",
      "Custom commissions open monthly. 14 day turnaround, worldwide tracked shipping, direct from the studio.": "Özel siparişler aylık açılır. 14 gün teslim süresi, takipli kargo ve doğrudan tasarımcıyla iletişim.",
      "Start A Commission": "Özel Tasarıma Başla",
      "Drop A Reference": "Referans Gönder",
      "Studio": "Stüdyo",
      "Commissions": "Siparişler",
      "Shipping": "Kargo",
      "Reply Time": "Yanıt Süresi",
      "Under 24h": "24 Saat İçinde",
      "Mon — Sat": "Pzt — Cmt",
      "Cut In Italy · Shipped Worldwide": "Stüdyoda Kesim · Dünya Çapında Kargo",
      "v0.7 · Drop 07": "v0.7 · Drop 07",
      "Order Now": "Sipariş Ver",
      "View": "İncele",
      "Day 0 — 2": "0 — 2. Gün",
      "Day 3 — 6": "3 — 6. Gün",
      "Day 7 — 9": "7 — 9. Gün",
      "Day 10 — 14": "10 — 14. Gün",
      "Siparis": "Sipariş",
      "Sticker kit sepeti": "Sticker kit sepeti",
      "Sepet bos. Koleksiyondan bir tasarim sec.": "Sepet boş. Koleksiyondan bir tasarım seç.",
      "adet": "adet",
      "Sil": "Sil",
      "Toplam": "Toplam",
      "Gonderiliyor": "Gönderiliyor",
      "Siparis talebi gonder": "Sipariş talebi gönder"
    },
    attrs: {
      "Ad soyad": "Ad soyad",
      "Telefon / WhatsApp": "Telefon / WhatsApp",
      "E-posta": "E-posta",
      "Motor modeli": "Motor modeli",
      "Ozel olcu, renk, teslimat notu": "Özel ölçü, renk, teslimat notu"
    }
  },
  en: {
    title: "ACYL/GRAPHIC — Design Speed.",
    text: {
      "Garaj": "Garage",
      "Mağaza": "Shop",
      "Özel": "Custom",
      "Akış": "Feed",
      "Stüdyo": "Studio",
      "İletişim": "Contact",
      "Sepet": "Cart",
      "Sepet ·": "Cart ·",
      "DEPO · DROP 07": "TANK · DROP 07",
      "YENI": "NEW",
      "YENİ": "NEW",
      "KASK": "HELMET",
      "YARIS LIVERY": "RACE LIVERY",
      "YARIŞ KAPLAMA": "RACE LIVERY",
      "GRENAJ": "FAIRING",
      "ON SIPARIS": "PRE-ORDER",
      "ÖN SİPARİŞ": "PRE-ORDER",
      "Tam depo flame kit. Cast vinyl, parlak laminasyon.": "Full-tank flame kit. Cast vinyl, gloss laminated.",
      "AGV / Shoei uyumlu yan sticker seti.": "Skull side-decal pair. AGV / Shoei compatible.",
      "Orta hat yaris seridi. 30 numarali set.": "Centerline racing stripe. 30 numbered sets.",
      "Orta hat yarış şeridi. 30 numaralı set.": "Centerline racing stripe. 30 numbered sets.",
      "Tam kask kaplama seti. Cok parcali, hazir kesim.": "Full helmet wrap kit. Multi-piece, pre-cut.",
      "Tam kask kaplama seti. Çok parçalı, hazır kesim.": "Full helmet wrap kit. Multi-piece, pre-cut.",
      "ACYLGRAPHIC logo sticker, aynali takim.": "ACYLGRAPHIC nameplate decal, mirrored set.",
      "ACYLGRAPHIC logo sticker, aynalı takım.": "ACYLGRAPHIC nameplate decal, mirrored set.",
      "Karbon zeminli geometrik grenaj deseni.": "Geometric fairing pattern. Carbon backdrop.",
      "Sipariş ver →": "Order now →",
      "Sipariş Ver": "Order Now",
      "Sipariş": "Order",
      "Siparis": "Order",
      "Incele": "View",
      "İncele": "View",
      "0 — 2. Gün": "Day 0 — 2",
      "3 — 6. Gün": "Day 3 — 6",
      "7 — 9. Gün": "Day 7 — 9",
      "10 — 14. Gün": "Day 10 — 14",
      "Sticker kit sepeti": "Sticker kit cart",
      "Sepet bos. Koleksiyondan bir tasarim sec.": "Cart is empty. Pick a design from the collection.",
      "Sepet boş. Koleksiyondan bir tasarım seç.": "Cart is empty. Pick a design from the collection.",
      "adet": "pcs",
      "Sil": "Remove",
      "Toplam": "Total",
      "Gönderiliyor": "Sending",
      "Gonderiliyor": "Sending",
      "Sipariş talebi gönder": "Send order request",
      "Siparis talebi gonder": "Send order request",
      "PERFORMANS GRAFİKLERİ · DROP 07 YAYINDA": "PERFORMANCE GRAPHICS · DROP 07 LIVE",
      "İSTANBUL STÜDYO / ÖZEL TASARIM": "ISTANBUL STUDIO / CUSTOM DESIGN",
      "Kaplanan Motor": "Builds Wrapped",
      "Aktif Tasarım": "Active Liveries",
      "Sürücü": "Riders",
      "Tasarım": "Design",
      "Hız": "Speed",
      "Görselleşti": "Visualised",
      "hareket eden bir tuval gibi görülen motosikletler için sinematik sticker kitleri, yarış kaplamaları ve kask grafikleri tasarlar. Cast vinyl kesim. 300 km/h için üretildi.": "engineers cinematic decal kits, racing liveries and helmet graphics for riders who treat their bike like a moving canvas. Cut on cast vinyl. Built for 300 km/h.",
      "VİNİL · 6 YIL DIŞ MEKAN": "VINYL · 6Y OUTDOOR",
      "TESLİM SÜRESİ": "TURN-AROUND",
      "7—14 Gün": "7—14 Days",
      "Koleksiyonu İncele": "Explore Collection",
      "Özel Sipariş": "Order Custom",
      "Garajı Gör": "View Garage",
      "BMW S1000RR · GERÇEK MOTOR MOCKUP": "BMW S1000RR · REAL BIKE MOCKUP",
      "Depo Sticker Kiti": "Tank Decal Kit",
      "Ön Cam Tonu": "Windshield Tint",
      "Kuyruk Şeridi": "Tail Stripe",
      "Ön Grenaj": "Front Fairing",
      "Cast Vinil": "Cast Vinyl",
      "Kask Kaplama": "Helmet Wraps",
      "Yarış Kaplamaları": "Racing Liveries",
      "Grenaj Kitleri": "Fairing Kits",
      "Dünya Çapında Kargo": "Worldwide Shipping",
      "Stüdyoda Üretildi": "Built In Studio",
      "02 · Öne Çıkanlar · 18 Aktif Ürün": "02 · Featured · 18 Active SKUs",
      "Koleksiyon": "Collection",
      "Tümü": "All",
      "Depo": "Tanks",
      "Kask": "Helmets",
      "Kaplama": "Liveries",
      "Grenaj": "Fairings",
      "Sıralama": "Sorting",
      "EN YENİ · ↓": "NEWEST · ↓",
      "03 · Özel Tasarım Akışı": "03 · Custom Workflow",
      "Fikri Sen Ver.": "You Design The Idea.",
      "Biz Yüzeye": "We Engineer",
      "Uygulayalım.": "The Surface.",
      "Her özel iş önce render edilir, doğrulanır ve fabrika takımlarının kullandığı cast vinyl üzerine kesilir. Aracı yok. Bayi yok. Tasarımcıdan sürücüye.": "Every commission is rendered, validated, then plotted on the same cast vinyl factory teams use. No reseller. No middleman. Designer-to-rider, every time.",
      "ÖNCE": "BEFORE",
      "SONRA · A-07": "AFTER · A-07",
      "Brief ve Referans": "Brief & Reference",
      "Mockup Render": "Mock-Up Render",
      "Baskı ve Kesim": "Print & Cut",
      "Kargo ve Uygulama": "Ship & Apply",
      "04 · Sosyal Akış": "04 · The Feed",
      "Yolda": "Worn In",
      "Yüksek": "Worn",
      "Sesli": "Loud",
      "Ön grenaj winglet çalışması": "Front fairing winglet study",
      "S1000RR yan panel sticker alanı": "S1000RR side panel decal zone",
      "RR sticker yerleşim analizi": "RR sticker placement breakdown",
      "M trim üzerine inferno katmanları": "Layering inferno kit over M trim",
      "S1000RR tam kaplama yönü": "S1000RR full livery direction",
      "kaydetme": "saves",
      "izlenme": "plays",
      "İzle": "Watch",
      "05 · Plotter’ın Arkasında": "05 · Behind The Plotter",
      "Tek Tasarımcı.": "One Designer.",
      "Her Kesim.": "Every Cut.",
      "İstanbul'dan.": "From İstanbul.",
      "Kurucu / Tasarımcı": "Founder / Designer",
      "Ülkeye Kargo": "Countries Shipped",
      "Yıllık Deneyim": "In Operation",
      "Stüdyo Kesim": "Cut In-House",
      "06 · Sürücü Yorumları": "06 · Rider Logs",
      "Garaj": "Garage",
      "Ne Diyor": "Says",
      "4.97 · 312 yorum": "4.97 · 312 reviews",
      "07 · Sıradaki Drop · İlkbahar 2026": "07 · Next Drop · Spring 2026",
      "Motorunu": "Make Your Bike",
      "Gözden": "Impossible",
      "Kaçırılmaz Yap.": "To Miss.",
      "Özel siparişler aylık açılır. 14 gün teslim süresi, takipli kargo ve doğrudan tasarımcıyla iletişim.": "Custom commissions open monthly. 14 day turnaround, worldwide tracked shipping, direct from the studio.",
      "Özel Tasarıma Başla": "Start A Commission",
      "Referans Gönder": "Drop A Reference",
      "Siparişler": "Commissions",
      "Kargo": "Shipping",
      "Yanıt Süresi": "Reply Time",
      "24 Saat İçinde": "Under 24h",
      "Pzt — Cmt": "Mon — Sat",
      "Stüdyoda Kesim · Dünya Çapında Kargo": "Cut In Studio · Shipped Worldwide"
    },
    attrs: {
      "Ad soyad": "Full name",
      "Telefon / WhatsApp": "Phone / WhatsApp",
      "E-posta": "Email",
      "Motor modeli": "Motorcycle model",
      "Özel ölçü, renk, teslimat notu": "Custom size, color, delivery note",
      "Ozel olcu, renk, teslimat notu": "Custom size, color, delivery note"
    }
  }
};

function translateText(raw, lang) {
  const value = raw.replace(/\s+/g, " ").trim();
  if (!value) return raw;
  const dict = TRANSLATIONS[lang]?.text || {};
  if (dict[value]) return raw.replace(value, dict[value]);
  if (value.startsWith("Sepet ·")) return raw.replace("Sepet", lang === "en" ? "Cart" : "Sepet");
  if (value.startsWith("Cart ·")) return raw.replace("Cart", lang === "tr" ? "Sepet" : "Cart");
  if (value.startsWith("Siparis alindi:")) return raw.replace("Siparis alindi:", lang === "en" ? "Order received:" : "Sipariş alındı:");
  if (value.startsWith("Sipariş alındı:")) return raw.replace("Sipariş alındı:", lang === "en" ? "Order received:" : "Sipariş alındı:");
  const checkoutText = {
    "Teslimat": lang === "en" ? "Delivery" : "Teslimat",
    "Fatura": lang === "en" ? "Billing" : "Fatura",
    "Bireysel": lang === "en" ? "Individual" : "Bireysel",
    "Kurumsal": lang === "en" ? "Company" : "Kurumsal",
    "Mesafeli satis ve siparis kosullarini kabul ediyorum.": lang === "en" ? "I accept the distance sales and order terms." : "Mesafeli satis ve siparis kosullarini kabul ediyorum.",
    "Kisisel verilerimin siparis sureci icin islenmesini kabul ediyorum.": lang === "en" ? "I accept processing my personal data for the order process." : "Kisisel verilerimin siparis sureci icin islenmesini kabul ediyorum.",
    "WhatsApp ile siparisi takip et": lang === "en" ? "Track order on WhatsApp" : "WhatsApp ile siparisi takip et"
  };
  if (checkoutText[value]) return raw.replace(value, checkoutText[value]);
  return raw;
}

function applyLanguage(lang) {
  document.documentElement.lang = lang;
  document.title = TRANSLATIONS[lang].title;
  const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
    acceptNode(node) {
      const tag = node.parentElement?.tagName;
      if (!tag || ["SCRIPT", "STYLE", "NOSCRIPT"].includes(tag)) return NodeFilter.FILTER_REJECT;
      return node.nodeValue.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
    }
  });
  const nodes = [];
  while (walker.nextNode()) nodes.push(walker.currentNode);
  nodes.forEach(node => { node.nodeValue = translateText(node.nodeValue, lang); });
  const attrs = TRANSLATIONS[lang].attrs || {};
  document.querySelectorAll("[placeholder]").forEach(el => {
    const checkoutAttrs = {
      "Teslimat adresi": lang === "en" ? "Delivery address" : "Teslimat adresi",
      "Il": lang === "en" ? "City" : "Il",
      "Ilce": lang === "en" ? "District" : "Ilce",
      "Posta kodu": lang === "en" ? "Postal code" : "Posta kodu",
      "Fatura unvani": lang === "en" ? "Invoice title" : "Fatura unvani",
      "Vergi dairesi": lang === "en" ? "Tax office" : "Vergi dairesi",
      "Vergi / T.C. no": lang === "en" ? "Tax / ID number" : "Vergi / T.C. no"
    };
    const placeholder = el.getAttribute("placeholder");
    const next = attrs[placeholder] || checkoutAttrs[placeholder];
    if (next) el.setAttribute("placeholder", next);
  });
}

function useLanguageRuntime(lang) {
  useEffect(() => {
    applyLanguage(lang);
    const raf = requestAnimationFrame(() => applyLanguage(lang));
    return () => cancelAnimationFrame(raf);
  });
}

/* ---------- Cursor ---------- */
function Cursor() {
  const dot = useRef(null), ring = useRef(null);
  useEffect(() => {
    let tx = 0, ty = 0, rx = 0, ry = 0;
    const move = e => { tx = e.clientX; ty = e.clientY; if (dot.current) { dot.current.style.transform = `translate(${tx-3}px, ${ty-3}px)`; } };
    const tick = () => { rx += (tx - rx) * 0.18; ry += (ty - ry) * 0.18; if (ring.current) ring.current.style.transform = `translate(${rx-18}px, ${ry-18}px)`; requestAnimationFrame(tick); };
    const enter = e => { if (e.target.closest && e.target.closest("a, button, [data-hover]")) ring.current?.classList.add("hover"); };
    const leave = e => { if (e.target.closest && e.target.closest("a, button, [data-hover]")) ring.current?.classList.remove("hover"); };
    window.addEventListener("mousemove", move);
    document.addEventListener("mouseover", enter);
    document.addEventListener("mouseout", leave);
    tick();
    return () => { window.removeEventListener("mousemove", move); document.removeEventListener("mouseover", enter); document.removeEventListener("mouseout", leave); };
  }, []);
  return <React.Fragment>
    <div ref={dot} className="cursor-dot"></div>
    <div ref={ring} className="cursor-ring"></div>
  </React.Fragment>;
}

/* ---------- CountUp ---------- */
function CountUp({ end, duration = 1500, suffix = "", flash = false }) {
  const [val, setVal] = useState(0);
  const [flashing, setFlashing] = useState(false);
  const ref = useRef(null);
  const isFloat = !Number.isInteger(end);
  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      if (!entry.isIntersecting) return;
      observer.disconnect();
      const startTime = performance.now();
      const tick = now => {
        const p = Math.min((now - startTime) / duration, 1);
        const eased = 1 - Math.pow(1 - p, 3);
        const cur = eased * end;
        setVal(isFloat ? parseFloat(cur.toFixed(1)) : Math.floor(cur));
        if (p < 1) requestAnimationFrame(tick);
        else { setVal(end); if (flash) { setFlashing(true); setTimeout(() => setFlashing(false), 750); } }
      };
      requestAnimationFrame(tick);
    }, { threshold: 0.3 });
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, [end, duration, isFloat, flash]);
  return <span ref={ref} className={flashing ? "count-flash" : ""}>{val}{suffix}</span>;
}

/* ---------- Logo ---------- */
function AcylLogo({ size = "nav" }) {
  const styles = size === "footer"
    ? { height: "72px", width: "auto", display: "block", objectFit: "contain" }
    : { height: "48px", width: "auto", display: "block", objectFit: "contain" };
  return (
    <div className={`acyl-logo acyl-logo--${size}`}>
      <img src="/assets/acylsite_300x.png" alt="ACYL" draggable="false" style={styles}/>
    </div>
  );
}

/* ---------- Loader (Splash) ---------- */
function Loader({ onDone }) {
  const [done, setDone] = useState(false);
  useEffect(() => {
    const t1 = setTimeout(() => setDone(true), 2000);
    const t2 = setTimeout(onDone, 2650);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [onDone]);
  return (
    <div className="splash" data-done={done}>
      <div className="splash-content">
        <img className="splash-logo" src="/assets/acylsite_300x.png" alt="ACYL" draggable="false"
          style={{ width: "380px", height: "auto", objectFit: "contain", display: "block" }}/>
      </div>
      <div className="splash-bar-wrap">
        <div className="splash-bar-fill"></div>
      </div>
    </div>
  );
}

/* ---------- Nav ---------- */
function Nav({ onContact, lang, page, onNavigate, mobileOpen, onMobileToggle }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <React.Fragment>
      <nav className="nav" style={scrolled ? {
        background: "rgba(8,8,10,0.94)",
        borderColor: "rgba(255,255,255,0.14)",
        boxShadow: "0 8px 32px rgba(0,0,0,0.5)"
      } : undefined}>
        <div className="nav-brand" onClick={() => onNavigate("garaj")} data-hover>
          <AcylLogo size="nav"/>
        </div>
        <div className="nav-links">
          {PAGES.map(p => (
            <a
              key={p.key}
              className={page === p.key ? "active" : ""}
              href={`/${lang}/${p.slug[lang]}`}
              onClick={e => { e.preventDefault(); onNavigate(p.key); }}
              data-hover
            >
              {p.label[lang]}
            </a>
          ))}
        </div>
        <div className="nav-right">
          <div className="lang-switch" aria-label="Language switch">
            <button className={lang === "tr" ? "active" : ""} onClick={() => setRouteLang("tr", page)} data-hover>TR</button>
            <button className={lang === "en" ? "active" : ""} onClick={() => setRouteLang("en", page)} data-hover>EN</button>
          </div>
          <button className="nav-cart" data-hover onClick={onContact}>
            <i></i> {lang === "en" ? "Order Now" : "Sipariş Ver"}
          </button>
          <button className={`nav-hamburger${mobileOpen ? " open" : ""}`} onClick={onMobileToggle} aria-label="Menü" data-hover>
            <span></span><span></span><span></span>
          </button>
        </div>
      </nav>
      {mobileOpen && (
        <div className="mobile-menu" onClick={onMobileToggle}>
          <div className="mobile-menu-inner" onClick={e => e.stopPropagation()}>
            {PAGES.map((p, i) => (
              <a
                key={p.key}
                className={`mobile-nav-link${page === p.key ? " active" : ""}`}
                href={`/${lang}/${p.slug[lang]}`}
                onClick={e => { e.preventDefault(); onNavigate(p.key); onMobileToggle(); }}
                data-hover
              >
                <span className="mobile-num">{String(i + 1).padStart(2, "0")}</span>
                {p.label[lang]}
              </a>
            ))}
            <button className="btn btn-primary mobile-order-btn" onClick={() => { onContact(); onMobileToggle(); }} data-hover>
              <span>{lang === "en" ? "Order Now" : "Sipariş Ver"}</span><span className="arrow"></span>
            </button>
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

/* ---------- Magnetic button ---------- */
function Magnetic({ children, className, ...p }) {
  const ref = useRef(null);
  const move = e => {
    const r = ref.current.getBoundingClientRect();
    const x = e.clientX - r.left - r.width / 2;
    const y = e.clientY - r.top - r.height / 2;
    ref.current.style.transform = `translate(${x * 0.18}px, ${y * 0.28}px)`;
  };
  const leave = () => { if (ref.current) ref.current.style.transform = ""; };
  return <button ref={ref} className={className} onMouseMove={move} onMouseLeave={leave} {...p}>{children}</button>;
}

/* ---------- Hero ---------- */
function Hero({ t, onContact, onNavigate }) {
  const stageRef = useRef(null);
  useEffect(() => {
    const handle = e => {
      if (!stageRef.current) return;
      const r = stageRef.current.getBoundingClientRect();
      const x = (e.clientX - r.left) / r.width - 0.5;
      const y = (e.clientY - r.top) / r.height - 0.5;
      const svg = stageRef.current.querySelector("svg");
      if (svg) svg.style.transform = `translate3d(${x * 18}px, ${y * 10}px, 0) rotateY(${x * 4}deg) rotateX(${-y * 3}deg)`;
    };
    window.addEventListener("mousemove", handle);
    return () => window.removeEventListener("mousemove", handle);
  }, []);
  return (
    <section className="hero" id="hero">
      <div className="hero-grid"></div>
      <div className="hero-glow"></div>
      <div className="hero-inner">
        <div className="hero-top reveal in">
          <div className="hero-top-left">
            <span className="kicker"><span className="dot"></span> PERFORMANCE GRAPHICS · DROP 07 LIVE</span>
            <span className="eyebrow">N 41.0082° · E 28.9784° / ISTANBUL STUDIO</span>
          </div>
          <div className="hero-top-right">
            {/*<div className="hud-stat"><span className="v"><CountUp end={412} duration={1600}/></span><span className="l">Builds Wrapped</span></div>*/}
            {/*<div className="hud-stat"><span className="v"><CountUp end={18} duration={1200}/></span><span className="l">Active Liveries</span></div>*/}
            {/*<div className="hud-stat"><span className="v"><CountUp end={7.2} duration={1400} suffix="k"/></span><span className="l">Riders</span></div>*/}
          </div>
        </div>

        <h1 className="hero-title reveal in d-1">
          <span className="l1">Design</span>
          <span className="l2 red">Speed</span>
          <span className="l3 outlined">{t.hero || "Visualised"}</span>
        </h1>

        <div className="hero-sub-row reveal in d-2">
          <p className="hero-lede">
            <strong>ACYLGRAPHIC</strong> engineers cinematic decal kits, racing liveries and helmet graphics for riders who treat their bike like a moving canvas. Cut on cast vinyl. Built for 300&nbsp;km/h.
          </p>
          {/*<div className="hero-spec">*/}
          {/*  <span className="label">VINYL · 6Y OUTDOOR</span>*/}
          {/*  <span className="value">Cast 3M™ 2080</span>*/}
          {/*  <div className="row">*/}
          {/*    <i className="pip"></i><i className="pip"></i><i className="pip"></i><i className="pip"></i><i className="pip dim"></i>*/}
          {/*  </div>*/}
          {/*</div>*/}
          <div className="hero-spec">
            <span className="label">TURN-AROUND</span>
            <span className="value">7—14 Days</span>
            <div className="row">
              <i className="pip"></i><i className="pip"></i><i className="pip"></i><i className="pip dim"></i><i className="pip dim"></i>
            </div>
          </div>
        </div>

        <div className="hero-cta-row reveal in d-3">
          <Magnetic className="btn btn-primary" data-hover onClick={() => onNavigate?.("magaza")}>
            <span>Explore Collection</span><span className="arrow"></span>
          </Magnetic>
          <Magnetic className="btn" data-hover onClick={onContact}>
            <span>Order Custom</span><span className="arrow"></span>
          </Magnetic>
          <Magnetic className="btn btn-ghost" data-hover onClick={() => onNavigate?.("studyo")}>
            <span>View Garage</span><span className="arrow"></span>
          </Magnetic>
        </div>

        <div className="hero-bike-wrap" ref={stageRef}>
          <div className="hero-bike-rings">
            <div className="ring"></div><div className="ring"></div><div className="ring"></div>
          </div>
          <div className="hero-bike-floor"></div>
          <div className="hero-bike-photo-wrap" data-hover>
            <RealBikeImage src={GARAGE_HERO_IMAGE} className="hero-bike-photo" alt="ACYLGRAPHIC blue Yamaha R7 custom decal concept"/>
            <div className="hero-bike-photo-overlay"></div>
          </div>
          <div className="hero-bike-tag t1"><span>Tank Decal Kit</span><span className="v">BLUE GRID</span></div>
          <div className="hero-bike-tag t2"><span>Windshield Detail</span><span className="v">STRIPE / GLOSS</span></div>
          <div className="hero-bike-tag t3"><span>Tail Graphic</span><span className="v">R7 CUSTOM</span></div>
          <div className="hero-bike-tag t4"><span>Front Fairing</span><span className="v">SERPENT / ICE</span></div>
        </div>
      </div>

      <div className="hero-marquee">
        <div className="hero-marquee-track">
          {Array.from({length:2}).map((_,k) => (
            <span key={k}>
              Cast Vinyl <i className="star"></i> Helmet Wraps <i className="star"></i> <span className="red">Racing Liveries</span> <i className="star"></i> Fairing Kits <i className="star"></i> Worldwide Shipping <i className="star"></i> Drop 07 Live <i className="star"></i> Built In Studio <i className="star"></i>{" "}
            </span>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Featured products ---------- */

function ProductCard({ p, onOrder, lang }) {
  const ref = useRef(null);
  const inStock = (p.stock ?? 1) > 0;
  const move = e => {
    if (!ref.current) return;
    const r = ref.current.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width - 0.5;
    const y = (e.clientY - r.top) / r.height - 0.5;
    ref.current.style.transform = `perspective(1200px) rotateY(${x * 6}deg) rotateX(${-y * 5}deg)`;
  };
  const leave = () => { if (ref.current) ref.current.style.transform = ""; };
  return (
    <article ref={ref} className={`product ${p.size} ${inStock ? "" : "is-sold-out"}`} onMouseMove={move} onMouseLeave={leave} data-hover>
      <span className="corner tl"></span><span className="corner tr"></span><span className="corner bl"></span><span className="corner br"></span>
      <div className="product-tilt">
        <div className="bg-pattern"></div>
        <div className="product-art">
          {p.imageUrl ? <img src={p.imageUrl} alt={p.title} className="product-photo"/> : <StickerArt kind={p.art}/>}
        </div>
      </div>
      <header className="product-head">
        <span className="product-tag">{p.tag}</span>
        {p.pill && <span className="product-pill">{p.pill}</span>}
      </header>
      <footer className="product-foot">
        <h3 className="product-title">{p.title}</h3>
        <p className="product-sub">{p.sub}</p>
        <div className="product-price-row">
          <span className="product-price">{p.price}{p.old && <small><s>{p.old}</s></small>}</span>
          <div className="product-actions">
            <a className="product-detail-link" href={`/${lang}/products/${p.id}`} data-hover>{lang === "en" ? "View" : "İncele"}</a>
            <button className="product-quick" onClick={() => onOrder(p)} data-hover>Sipariş ver →</button>
          </div>
        </div>
      </footer>
    </article>
  );
}

function Featured({ onOrder, products, lang }) {
  const [tab, setTab] = useState("all");
  const tabs = [
    { key: "all",      label: "All"      },
    { key: "tanks",    label: "Tanks"    },
    { key: "helmets",  label: "Helmets"  },
    { key: "liveries", label: "Liveries" },
    { key: "fairings", label: "Fairings" },
  ];
  const base = Array.isArray(products) ? products : [];
  const visibleProducts = tab === "all" ? base : base.filter(p => {
    const tag = (p.tag || "").toUpperCase();
    if (tab === "tanks")    return tag.includes("DEPO");
    if (tab === "helmets")  return tag.includes("KASK");
    if (tab === "liveries") return tag.includes("YARIS") || tag.includes("LIVERY");
    if (tab === "fairings") return tag.includes("GRENAJ");
    return true;
  });
  const skuLabel = lang === "en" ? `${base.length} Active SKUs` : `${base.length} Aktif Ürün`;
  return (
    <section className="featured" id="shop">
      <header className="featured-head">
        <div>
          <span className="kicker"><span className="dot"></span> 02 · Featured · {skuLabel}</span>
          <h2 className="h-mid" style={{marginTop:12}}>Collection<br/><span style={{color:"var(--accent)"}}>// Drop 07</span></h2>
          <div className="featured-tabs">
            {tabs.map(t => <button key={t.key} className={`tab ${tab === t.key ? "active":""}`} onClick={() => setTab(t.key)} data-hover>{t.label}</button>)}
          </div>
        </div>
        <div className="meta">
          <span className="eyebrow">Sorting</span>
          <span className="nav-mini" style={{color:"var(--ink)"}}>NEWEST · ↓</span>
        </div>
      </header>
      {products === null ? (
        <div className="empty-state" style={{padding:"80px 0", textAlign:"center", color:"var(--ink-2)", fontFamily:"var(--f-mono)", fontSize:13, letterSpacing:"0.1em"}}>Yükleniyor...</div>
      ) : visibleProducts.length > 0 ? (
        <div key={tab} className="product-grid">
          {visibleProducts.map(p => <ProductCard key={p.id} p={p} onOrder={onOrder} lang={lang}/>)}
        </div>
      ) : (
        <div className="empty-state" style={{padding:"80px 0", textAlign:"center", color:"var(--ink-2)", fontFamily:"var(--f-mono)", fontSize:13, letterSpacing:"0.1em"}}>
          {lang === "en" ? "No products available yet." : "Henüz yayında ürün bulunmuyor."}
        </div>
      )}
    </section>
  );
}

/* ---------- Custom design ---------- */
function CustomSection() {
  const [cx, setCx] = useState(52);
  const ref = useRef(null);
  const dragging = useRef(false);
  useEffect(() => {
    const up = () => dragging.current = false;
    const move = e => {
      if (!dragging.current || !ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const t = e.touches?.[0] || e;
      const pct = Math.max(4, Math.min(96, ((t.clientX - r.left) / r.width) * 100));
      setCx(pct);
    };
    window.addEventListener("mouseup", up);
    window.addEventListener("mousemove", move);
    window.addEventListener("touchmove", move);
    window.addEventListener("touchend", up);
    return () => { window.removeEventListener("mouseup", up); window.removeEventListener("mousemove", move); window.removeEventListener("touchmove", move); window.removeEventListener("touchend", up); };
  }, []);
  const steps = [
    { n: "01", t: "Brief & Reference", d: "Drop bike specs, references, target circuit, paint codes. We translate intent into design language within 48h.", dur: "Day 0 — 2" },
    { n: "02", t: "Mock-Up Render", d: "Side / front / rear photoreal renders on your actual fairing. Two directions, infinite micro-edits.", dur: "Day 3 — 6" },
    { n: "03", t: "Print & Cut", d: "Cast 3M vinyl, gloss laminate, plotter-cut to silhouette. Quality-controlled per panel.", dur: "Day 7 — 9" },
    { n: "04", t: "Ship & Apply", d: "Worldwide tracked shipping with squeegee, primer wipe, full application guide & timelapse video.", dur: "Day 10 — 14" },
  ];
  return (
    <section className="custom" id="custom">
      <header className="custom-head">
        <div>
          <span className="kicker"><span className="dot"></span> 03 · Custom Workflow</span>
          <h2 className="h-mid" style={{marginTop:14}}>You Design The Idea.<br/><span style={{color:"var(--accent)"}}>We Engineer</span> The Surface.</h2>
        </div>
        <p style={{color:"var(--ink-2)", maxWidth:"40ch", fontSize:15, lineHeight:1.6}}>
          Every commission is rendered, validated, then plotted on the same cast vinyl factory teams use. No reseller. No middleman. Designer-to-rider, every time.
        </p>
      </header>
      <div className="custom-body">
        <div className="compare" ref={ref} onMouseDown={e => e.preventDefault()}>
          <span className="compare-label l">BEFORE</span>
          <span className="compare-label r">AFTER · A-07</span>
          <div className="compare-img before">
            <RealBikeImage src={CUSTOM_COMPARE_IMAGES.before} className="compare-photo" alt="Yamaha R7 before custom decal design" draggable="false"/>
          </div>
          <div className="compare-img after after-clip" style={{"--cx": `${cx}%`}}>
            <RealBikeImage src={CUSTOM_COMPARE_IMAGES.after} className="compare-photo compare-photo-after" alt="Yamaha R7 after custom decal design" draggable="false"/>
          </div>
          <div className="compare-handle" style={{left: `${cx}%`}} onMouseDown={e => { e.preventDefault(); dragging.current = true; }} onTouchStart={() => dragging.current = true}>
            <div className="knob" data-hover>↔</div>
          </div>
        </div>
        <div className="steps">
          {steps.map((s, i) => (
            <div key={s.n} className={`step reveal d-${i+1} ${i===1 ? "active":""}`} data-hover>
              <span className="num">{s.n}</span>
              <div>
                <h4>{s.t}</h4>
                <p>{s.d}</p>
              </div>
              <span className="dur">{s.dur}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Social ---------- */
function Social() {
  const [apiItems, setApiItems] = useState(null);

  useEffect(() => {
    fetch("/api/social-posts", { cache: "no-store" })
      .then(r => r.ok ? r.json() : Promise.reject())
      .then(data => { if (Array.isArray(data)) setApiItems(data); })
      .catch(() => { setApiItems([]); });
  }, []);

  const items = (apiItems || []).map(post => ({
    p: post.platform,
    n: post.handle,
    img: post.thumbnailUrl || null,
    k: post.kind || undefined,
    h: post.headline,
    m: post.meta,
    size: post.isTall ? "tall" : "",
    url: post.postUrl || undefined,
  }));

  return (
    <section className="social" id="feed">
      <header className="social-head">
        <div>
          <span className="kicker"><span className="dot"></span> 04 · The Feed</span>
          <h2 className="h-mid" style={{marginTop:12}}>Worn In<br/>Worn <span style={{color:"var(--accent)"}}>Loud</span></h2>
        </div>
        <div className="social-platforms">
          {["IG · 184K", "TT · 92K", "YT · 21K"].map(p => <span key={p} className="tab" data-hover>{p}</span>)}
        </div>
      </header>
      {apiItems === null ? (
        <div style={{padding:"60px 0", textAlign:"center", color:"var(--ink-2)", fontFamily:"var(--f-mono)", fontSize:13, letterSpacing:"0.1em"}}>Yükleniyor...</div>
      ) : items.length > 0 ? (
        <div className="social-grid">
          {items.map((it, i) => (
            <a
              key={i}
              className={`social-card ${it.size}${it.url ? "" : " pending"}`}
              href={it.url || "#"}
              target={it.url ? "_blank" : undefined}
              rel={it.url ? "noreferrer" : undefined}
              onClick={e => { if (!it.url) e.preventDefault(); }}
              aria-label={`${it.p}: ${it.h}`}
              data-hover
            >
              <div className="media">
                {it.img ? <RealBikeImage src={it.img} className="social-photo" alt={it.h}/> : <SocialThumb kind={it.k}/>}
              </div>
              <div className="scrim"></div>
              <span className="plat"><span className="icon"></span>{it.p}</span>
              <span className="num">/{String(i+1).padStart(2,"0")}</span>
              {(it.url || it.k === "reel" || it.k === "flame" || it.p === "YOUTUBE") && <div className="play"></div>}
              <div className="info">
                <div>
                  <div className="h">{it.h}</div>
                  <div className="meta">{it.n} · {it.m}</div>
                </div>
              </div>
            </a>
          ))}
        </div>
      ) : (
        <div style={{padding:"60px 0", textAlign:"center", color:"var(--ink-2)", fontFamily:"var(--f-mono)", fontSize:13, letterSpacing:"0.1em"}}>Henüz yayında içerik bulunmuyor.</div>
      )}
    </section>
  );
}

/* ---------- About designer ---------- */
function About({ lang = "tr" }) {
  const portraitRef = useRef(null);
  useEffect(() => {
    const el = portraitRef.current;
    if (!el) return;
    const move = e => {
      const r = el.getBoundingClientRect();
      const x = (e.clientX - r.left) / r.width - 0.5;
      const y = (e.clientY - r.top) / r.height - 0.5;
      el.style.transform = `perspective(900px) rotateY(${x * 9}deg) rotateX(${-y * 7}deg) scale(1.02)`;
    };
    const leave = () => { el.style.transform = ""; };
    el.addEventListener("mousemove", move);
    el.addEventListener("mouseleave", leave);
    return () => { el.removeEventListener("mousemove", move); el.removeEventListener("mouseleave", leave); };
  }, []);
  return (
    <section className="about" id="designer">
      <header className="custom-head" style={{marginBottom:60}}>
        <div>
          <span className="kicker"><span className="dot"></span> 05 · Behind The Plotter</span>
          <h2 className="h-mid" style={{marginTop:14}}>One Designer.<br/>Every Cut.<br/><span style={{color:"var(--accent)"}}>From İstanbul.</span></h2>
        </div>
        <p style={{color:"var(--ink-2)", maxWidth:"40ch", fontSize:15, lineHeight:1.6}}>
          ACYLGRAPHIC is a one-person studio built around a single obsession — making bikes look as fast as they go. No agency. No outsourcing.
        </p>
      </header>
      <div className="about-grid">
        <div className="about-portrait" ref={portraitRef}>
          <SocialThumb kind="portrait"/>
          <div className="about-corners"><span></span><span></span><span></span><span></span></div>
          <div className="scrim"></div>
          <div className="about-portrait-tag">
            <div>
              <div className="ro">Founder / Designer</div>
              <div className="nm">ACYL Studio</div>
            </div>
            <div style={{fontFamily:"var(--f-mono)", fontSize:10, color:"var(--ink-2)", letterSpacing:"0.18em", textAlign:"right"}}>EST.<br/><span style={{color:"var(--accent)", fontSize:14}}>2019</span></div>
          </div>
        </div>
        <div>
          {lang === "tr"
            ? <p className="about-quote">"Motosiklet, <em>300 km/h</em> giden bir heykeldir. Benim işim o heykele bir ses kazandırmak."</p>
            : <p className="about-quote">"A bike is a sculpture going <em>300 km/h</em>. My job is to make sure that sculpture has a soundtrack."</p>
          }
          {lang === "tr" ? (
            <React.Fragment>
              <p className="about-bio">İstanbul'dan çalışan ACYLGRAPHIC, motorsport grafiği, yarış kaplaması ve kask tasarımı alanında tek kişilik bir stüdyo. Her proje doğrudan tasarımcı tarafından yürütülür; aracı, bayi ya da dış kaynak yoktur.</p>
              <p className="about-bio">Her kit stüdyo içinde çizilir, motorunuzun gerçek 3D mockup'ları üzerinde doğrulanır ve fabrika takımlarının kullandığı aynı cast vinyl üzerine plotter ile kesilir. Özel siparişler iki haftanın altında teslim edilir; dünya genelinde kargo.</p>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <p className="about-bio">Based in Istanbul, ACYLGRAPHIC is a one-person studio specialising in motorsport graphics, race liveries and helmet design. Every project is handled directly by the designer — no middleman, no reseller, no outsourcing.</p>
              <p className="about-bio">Every kit is drawn in-studio, validated on rendered 3D mockups of your actual model, then plotter-cut on the same cast vinyl used by factory teams. Custom commissions turn around in under two weeks, shipped worldwide.</p>
            </React.Fragment>
          )}
          <div className="about-stats">
            <div className="about-stat reveal d-1"><div className="v"><CountUp end={412} duration={1800} suffix="+" flash/></div><div className="l">Builds Wrapped</div></div>
            <div className="about-stat reveal d-2"><div className="v"><CountUp end={38} duration={1400} flash/></div><div className="l">Countries Shipped</div></div>
            <div className="about-stat reveal d-3"><div className="v"><CountUp end={6} duration={1200} suffix="y" flash/></div><div className="l">In Operation</div></div>
            <div className="about-stat reveal d-4"><div className="v"><CountUp end={100} duration={1600} suffix="%" flash/></div><div className="l">Cut In-House</div></div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Testimonials ---------- */
function Testimonials() {
  const [items, setItems] = useState(null);

  useEffect(() => {
    fetch("/api/testimonials", { cache: "no-store" })
      .then(r => r.ok ? r.json() : Promise.reject())
      .then(data => { if (Array.isArray(data)) setItems(data.map(t => ({ q: t.quote, n: t.name, r: t.role, meta: t.meta, stars: t.stars }))); })
      .catch(() => { setItems([]); });
  }, []);

  return (
    <section className="testimonials">
      <header className="test-head">
        <div>
          <span className="kicker"><span className="dot"></span> 06 · Rider Logs</span>
          <h2 className="h-mid" style={{marginTop:12}}><span style={{color:"var(--accent)"}}>Garage</span> Says</h2>
        </div>
        {items && items.length > 0 && <span className="nav-mini" style={{color:"var(--ink)"}}>{items.length} yorum</span>}
      </header>
      {items === null ? null : items.length > 0 ? (
        <div className="test-track">
          {items.map((t,i) => (
            <article key={i} className={`test-card reveal d-${i+1}`} data-hover>
              <div className="test-stars">{Array.from({length: t.stars || 5}).map((_,s) => <span key={s} className="test-star">★</span>)}</div>
              <p className="test-quote">"{t.q}"</p>
              <div className="test-foot">
                <div className="test-author">
                  <div className="avi">{(t.n || "?")[0]}</div>
                  <div className="info">
                    <div className="n">{t.n}</div>
                    <div className="r">{t.r}</div>
                  </div>
                </div>
                <div className="test-meta">{t.meta}</div>
              </div>
            </article>
          ))}
        </div>
      ) : (
        <div style={{padding:"40px 0", textAlign:"center", color:"var(--ink-2)", fontFamily:"var(--f-mono)", fontSize:13, letterSpacing:"0.1em"}}>Henüz yayında yorum bulunmuyor.</div>
      )}
    </section>
  );
}

/* ---------- Final CTA ---------- */
function Final({ onContact }) {
  return (
    <section className="final" id="contact">
      <div className="final-grid"></div>
      <div className="final-bg"></div>
      <div className="final-inner">
        <span className="kicker reveal in" style={{justifyContent:"center"}}><span className="dot"></span> 07 · Next Drop · Spring 2026</span>
        <h2 className="final-title reveal in d-1" style={{marginTop:20}}>
          <div>Make Your Bike</div>
          <div>Impossible</div>
          <div className="red">To Miss.</div>
        </h2>
        <p className="final-sub reveal in d-2">Custom commissions open monthly. 14 day turnaround, worldwide tracked shipping, direct from the studio.</p>
        <div className="final-cta-row reveal in d-3">
          <Magnetic className="btn btn-primary" data-hover onClick={onContact}><span>Start A Commission</span><span className="arrow"></span></Magnetic>
          <Magnetic className="btn" data-hover onClick={onContact}><span>Drop A Reference</span><span className="arrow"></span></Magnetic>
        </div>
        <div className="final-meta">
          <div className="col"><div className="l">Studio</div><div className="v">İstanbul<br/>Türkiye</div></div>
          <div className="col"><div className="l">WhatsApp</div><div className="v"><a href={buildWhatsappUrl()} target="_blank" rel="noreferrer" style={{color:"var(--accent)"}}>Sipariş ver →</a></div></div>
          <div className="col"><div className="l">Instagram</div><div className="v"><a href={buildInstagramUrl()} target="_blank" rel="noreferrer" style={{color:"var(--accent)"}}>@{INSTAGRAM_HANDLE} →</a></div></div>
          <div className="col"><div className="l">Reply Time</div><div className="v">Under 24h<br/>Mon — Sat</div></div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Site Footer ---------- */
const INFO_PAGE_CONTENT = {
  "uygulama-kilavuzu": {
    tr: {
      eyebrow: "Musteri Hizmetleri",
      title: "Uygulama Kılavuzu",
      intro: "Sticker ve kaplama kitlerinin temiz, uzun omurlu ve profesyonel durmasi icin uygulama oncesi hazirlik en az tasarim kadar onemlidir.",
      sections: [
        ["Yuzey hazirligi", "Motosiklet yuzeyi oda sicakliginda, kuru ve tozsuz olmalidir. Wax, polish ve yag kalintilari izopropil alkol ile temizlenmelidir."],
        ["Konumlandirma", "Parcayi yapistirmadan once maskeleme bandi ile prova edin. Simetri, panel bosluklari ve vida noktalarini kontrol edin."],
        ["Uygulama", "Ortadan disari dogru rakle ile ilerleyin. Kavisli bolgelerde dusuk isi kullanin, malzemeyi gereksiz germeyin."],
        ["Son kontrol", "Kenarlar uygulama sonrasi tekrar bastirilir. Ilk 48 saat basincli yikama ve yogun yagmurdan uzak tutulur."]
      ],
      note: "Her sipariste urune uygun kisa uygulama notu ve gerekiyorsa video yonlendirmesi paylasilir."
    },
    en: {
      eyebrow: "Customer Service",
      title: "Application Guide",
      intro: "Preparation matters as much as design. A clean, warm and dry panel gives the decal kit the best chance to sit sharp and last.",
      sections: [
        ["Surface prep", "Panels must be dry, dust-free and at room temperature. Remove wax, polish and oil residue with isopropyl alcohol."],
        ["Placement", "Dry-fit each piece with masking tape before applying. Check symmetry, panel gaps and bolt positions."],
        ["Application", "Work from the center outward with a squeegee. Use gentle heat on curves and avoid overstretching the vinyl."],
        ["Final check", "Press all edges again after application. Avoid pressure washing and heavy rain for the first 48 hours."]
      ],
      note: "Each order includes product-specific guidance and, where needed, a short video reference."
    }
  },
  "kargo-bilgisi": {
    tr: {
      eyebrow: "Teslimat",
      title: "Kargo Bilgisi",
      intro: "Urunler siparise gore hazirlanir, koruyucu ambalajla paketlenir ve takip numarasi ile gonderilir.",
      sections: [
        ["Hazirlik suresi", "Stok urunlerde 1-3 is gunu, ozel tasarimlarda onay sonrasi ortalama 7-14 is gunu hazirlik planlanir."],
        ["Paketleme", "Sticker setleri kivrilmeye karsi sert karton ve neme dayanikli ambalajla korunur."],
        ["Takip", "Kargoya teslim edildiginde musteriye takip numarasi WhatsApp veya e-posta ile iletilir."],
        ["Uluslararasi gonderim", "Yurt disi teslimatlarda gumruk vergileri ve yerel masraflar aliciya ait olabilir."]
      ],
      note: "Teslimat adresi siparis onayindan once mutlaka kontrol edilmelidir."
    },
    en: {
      eyebrow: "Delivery",
      title: "Shipping Info",
      intro: "Products are prepared per order, packed in protective material and shipped with tracking.",
      sections: [
        ["Preparation time", "In-stock products usually ship in 1-3 business days. Custom work is prepared in roughly 7-14 business days after approval."],
        ["Packaging", "Decal sets are protected with rigid board and moisture-resistant packing."],
        ["Tracking", "A tracking number is sent by WhatsApp or email when the parcel is handed to the carrier."],
        ["International shipping", "Customs duties and local import costs may be charged to the buyer for international deliveries."]
      ],
      note: "The delivery address should be checked carefully before order approval."
    }
  },
  "iade-politikasi": {
    tr: {
      eyebrow: "Destek",
      title: "İade Politikası",
      intro: "Standart stok urunlerde iade sureci mumkundur; kisiye ozel tasarim ve modele gore uretilen urunlerde iade kosullari farklidir.",
      sections: [
        ["Stok urunler", "Kullanilmamis, hasarsiz ve orijinal ambalajindaki stok urunler teslimden sonra 14 gun icinde degerlendirmeye alinabilir."],
        ["Ozel uretim", "Musteriye, modele, olcuye veya onaylanan tasarima gore hazirlanan urunlerde uretim basladiktan sonra iade kabul edilmez."],
        ["Hasar bildirimi", "Kargo hasari varsa paket fotografi ile birlikte teslim gunu bildirim yapilmalidir."],
        ["Degisim", "Uretim hatasi tespit edilirse ayni urun tekrar uretilir veya uygun cozum sunulur."]
      ],
      note: "Iade/degerlendirme icin siparis numarasi ve fotografli aciklama gerekir."
    },
    en: {
      eyebrow: "Support",
      title: "Return Policy",
      intro: "Standard stock products can be reviewed for return. Custom-made and model-specific products follow different conditions.",
      sections: [
        ["Stock products", "Unused, undamaged stock products in original packaging may be reviewed within 14 days of delivery."],
        ["Custom production", "Items produced for a specific customer, bike model, measurement or approved design cannot be returned once production starts."],
        ["Damage report", "Carrier damage must be reported on the delivery day with clear photos of the package."],
        ["Replacement", "If a production defect is confirmed, the same item is reproduced or a suitable solution is offered."]
      ],
      note: "Return reviews require the order number and a photo-based explanation."
    }
  },
  "gizlilik-politikasi": {
    tr: {
      eyebrow: "Yasal",
      title: "Gizlilik Politikası",
      intro: "Siparis, iletisim ve teslimat sureclerinde yalnizca gerekli bilgiler alinir ve hizmeti tamamlamak icin kullanilir.",
      sections: [
        ["Toplanan bilgiler", "Ad soyad, telefon, e-posta, adres, motosiklet modeli, siparis notlari ve odeme durum bilgileri islenebilir."],
        ["Kullanim amaci", "Bilgiler siparis hazirlama, teslimat, destek ve yasal yukumlulukler icin kullanilir."],
        ["Paylasim", "Bilgiler yalnizca kargo, odeme ve teknik hizmet saglayicilariyla gerekli oldugu kadar paylasilir."],
        ["Saklama", "Siparis kayitlari muhasebe ve musteri destegi gerekleri icin makul sureyle saklanir."]
      ],
      note: "Bilgi guncelleme veya silme talepleri WhatsApp ya da e-posta uzerinden iletilebilir."
    },
    en: {
      eyebrow: "Legal",
      title: "Privacy Policy",
      intro: "Only the information needed for orders, communication and delivery is collected and used to complete the service.",
      sections: [
        ["Data collected", "Name, phone, email, address, motorcycle model, order notes and payment status data may be processed."],
        ["Purpose", "Data is used for order preparation, delivery, support and legal obligations."],
        ["Sharing", "Data is shared only with shipping, payment and technical providers when required."],
        ["Retention", "Order records are kept for a reasonable period for accounting and customer support."]
      ],
      note: "Requests to update or delete information can be sent through WhatsApp or email."
    }
  },
  "kullanim-kosullari": {
    tr: {
      eyebrow: "Yasal",
      title: "Kullanım Koşulları",
      intro: "Siteyi kullanarak urun bilgilerini, tasarim surecini ve siparis akisini bu kosullar cercevesinde kabul etmis olursunuz.",
      sections: [
        ["Icerik", "Gorseller, tasarimlar, metinler ve marka sunumu ACYLGRAPHIC'e veya ilgili hak sahiplerine aittir."],
        ["Siparis bilgileri", "Musteri dogru model, adres ve iletisim bilgisi vermekten sorumludur."],
        ["Tasarim onayi", "Ozel tasarimlarda uretim, musteri onayi alinmadan baslatilmaz."],
        ["Degisiklik", "Site icerigi, fiyatlar ve hizmet kosullari gerektiğinde guncellenebilir."]
      ],
      note: "Bu sayfa bilgilendirme amaclidir; canli yayindan once resmi hukuk metniyle son kontrol onerilir."
    },
    en: {
      eyebrow: "Legal",
      title: "Terms of Use",
      intro: "By using the site, you accept the product information, design process and order flow under these terms.",
      sections: [
        ["Content", "Images, designs, text and brand presentation belong to ACYLGRAPHIC or their respective rights holders."],
        ["Order information", "The customer is responsible for providing accurate model, address and contact details."],
        ["Design approval", "Custom production does not start before customer approval."],
        ["Changes", "Site content, prices and service terms may be updated when necessary."]
      ],
      note: "This page is informational; a final legal review is recommended before launch."
    }
  },
  "satis-kosullari": {
    tr: {
      eyebrow: "Yasal",
      title: "Satış Koşulları",
      intro: "Urunler stok veya ozel uretim olarak satilir. Fiyat, odeme, teslimat ve onay surecleri siparis ekraninda netlestirilir.",
      sections: [
        ["Fiyatlandirma", "Urun fiyatlari vitrindeki tutar uzerinden hesaplanir. Ozel tasarimlarda ek iscilik ve revizyon bedeli olabilir."],
        ["Odeme", "EFT/havale veya entegre odeme sistemiyle tahsilat yapilabilir. Siparis odeme durumuna gore isleme alinir."],
        ["Uretim", "Ozel sipariste tasarim onayi alindiktan sonra baski/kesim sureci baslar."],
        ["Teslimat ve sorumluluk", "Kargo tesliminden sonra uygulama hatalari musteri sorumlulugundadir; uretim hatalari ayrica degerlendirilir."]
      ],
      note: "Canli odeme entegrasyonu aktif edildiginde bu kosullar odeme saglayicisi metinleriyle uyumlu hale getirilmelidir."
    },
    en: {
      eyebrow: "Legal",
      title: "Sales Terms",
      intro: "Products are sold as stock items or custom production. Price, payment, delivery and approval steps are clarified during checkout.",
      sections: [
        ["Pricing", "Product prices are calculated from the showcase amount. Custom work may include additional design and revision fees."],
        ["Payment", "Payment may be collected by bank transfer or an integrated payment provider. Orders are processed according to payment status."],
        ["Production", "For custom orders, print/cut production starts after design approval."],
        ["Delivery and responsibility", "After delivery, application mistakes are the customer responsibility; production defects are reviewed separately."]
      ],
      note: "When live payment integration is activated, these terms should be aligned with provider documents."
    }
  }
};

function InfoPage({ pageKey, lang, onContact }) {
  const page = INFO_PAGES.find(p => p.key === pageKey) || INFO_PAGES[0];
  const content = INFO_PAGE_CONTENT[page.key]?.[lang] || INFO_PAGE_CONTENT[page.key]?.tr;
  return (
    <main className="info-page">
      <section className="info-hero">
        <span className="kicker"><span className="dot"></span> {content.eyebrow}</span>
        <h1>{content.title}</h1>
        <p>{content.intro}</p>
      </section>
      <section className="info-grid">
        {content.sections.map(([title, body], index) => (
          <article className="info-card" key={title} data-hover>
            <span>{String(index + 1).padStart(2, "0")}</span>
            <h2>{title}</h2>
            <p>{body}</p>
          </article>
        ))}
      </section>
      <section className="info-note">
        <strong>{lang === "tr" ? "Not" : "Note"}</strong>
        <p>{content.note}</p>
        <button className="btn btn-primary" onClick={() => onContact()} data-hover>
          <span>{lang === "tr" ? "Destek Al" : "Get Support"}</span><span className="arrow"></span>
        </button>
      </section>
    </main>
  );
}

function SocialIcon({ type }) {
  const common = { viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", focusable: "false" };
  if (type === "instagram") {
    return (
      <svg {...common}>
        <rect x="4.5" y="4.5" width="15" height="15" rx="4.2"></rect>
        <circle cx="12" cy="12" r="3.6"></circle>
        <circle cx="16.8" cy="7.2" r="1"></circle>
      </svg>
    );
  }
  if (type === "tiktok") {
    return (
      <svg {...common}>
        <path d="M13.8 4.5v10.1a4.1 4.1 0 1 1-3.2-4"></path>
        <path d="M13.8 4.5c.8 2.8 2.6 4.4 5.2 4.8"></path>
        <path d="M13.8 8.4c1.1 1.2 2.4 1.9 4.1 2.1"></path>
      </svg>
    );
  }
  return (
    <svg {...common}>
      <path d="M6.8 18.2 5 21l3.4-.9a8 8 0 1 0-2.3-2.2"></path>
      <path d="M9.2 8.8c.2-.5.4-.5.7-.5h.5c.2 0 .4.1.5.4l.7 1.7c.1.3 0 .5-.1.7l-.4.5c.7 1.2 1.7 2.1 3 2.8l.6-.7c.2-.2.4-.3.7-.2l1.7.8c.3.1.4.3.4.6 0 .6-.3 1.3-.8 1.7-.5.4-1.8.6-3.8-.4-2.5-1.2-4.2-3-5.1-5.1-.7-1.5.2-2.2.4-2.3Z"></path>
    </svg>
  );
}

/* ---------- Site Footer ---------- */
function SiteFooter({ lang, page, onNavigate }) {
  return (
    <footer className="site-footer">
      <div className="site-footer-top">
        <div className="footer-brand">
          <AcylLogo size="footer"/>
          <p className="footer-desc">
            {lang === "tr"
              ? "Motosiklet grafikleri, yarış kaplamaları ve kask tasarımı için tek kişilik stüdyo. Cast vinyl. Stüdyoda üretildi."
              : "One-person studio for motorsport graphics, race liveries and helmet design. Cast vinyl. Built in-studio."}
          </p>
          <div className="footer-social">
            <a className="footer-social-link" href={buildInstagramUrl()} target="_blank" rel="noreferrer" aria-label="Instagram" title="Instagram" data-hover><SocialIcon type="instagram"/></a>
            <a className="footer-social-link" href="https://tiktok.com/@acylgraphics" target="_blank" rel="noreferrer" aria-label="TikTok" title="TikTok" data-hover><SocialIcon type="tiktok"/></a>
            <a className="footer-social-link" href={buildWhatsappUrl()} target="_blank" rel="noreferrer" aria-label="WhatsApp" title="WhatsApp" data-hover><SocialIcon type="whatsapp"/></a>
          </div>
        </div>

        <div className="footer-col">
          <div className="footer-col-title">{lang === "tr" ? "Hızlı Bağlantılar" : "Quick Links"}</div>
          {PAGES.map(p => (
            <a key={p.key} className="footer-link" href={`/${lang}/${p.slug[lang]}`}
              onClick={e => { e.preventDefault(); onNavigate(p.key); }} data-hover>
              {p.label[lang]}
            </a>
          ))}
        </div>

        <div className="footer-col">
          <div className="footer-col-title">{lang === "tr" ? "Müşteri Hizmetleri" : "Customer Service"}</div>
          <a className="footer-link" href={buildWhatsappUrl()} target="_blank" rel="noreferrer" data-hover>WhatsApp</a>
          <a className="footer-link" href={buildInstagramUrl()} target="_blank" rel="noreferrer" data-hover>Instagram DM</a>
          {INFO_PAGES.filter(p => p.group === "service").map(p => (
            <a key={p.key} className="footer-link" href={`/${lang}/${p.slug[lang]}`}
              onClick={e => { e.preventDefault(); onNavigate(p.key); }} data-hover>
              {p.label[lang]}
            </a>
          ))}
          <a className="footer-link" href="#" data-hover>{lang === "tr" ? "Uygulama Kılavuzu" : "Application Guide"}</a>
          <a className="footer-link" href="#" data-hover>{lang === "tr" ? "Kargo Bilgisi" : "Shipping Info"}</a>
          <a className="footer-link" href="#" data-hover>{lang === "tr" ? "İade Politikası" : "Return Policy"}</a>
        </div>

        <div className="footer-col">
          <div className="footer-col-title">{lang === "tr" ? "Yasal" : "Legal"}</div>
          {INFO_PAGES.filter(p => p.group === "legal").map(p => (
            <a key={p.key} className="footer-link" href={`/${lang}/${p.slug[lang]}`}
              onClick={e => { e.preventDefault(); onNavigate(p.key); }} data-hover>
              {p.label[lang]}
            </a>
          ))}
          <a className="footer-link" href="#" data-hover>{lang === "tr" ? "Gizlilik Politikası" : "Privacy Policy"}</a>
          <a className="footer-link" href="#" data-hover>{lang === "tr" ? "Kullanım Koşulları" : "Terms of Use"}</a>
          <a className="footer-link" href="#" data-hover>{lang === "tr" ? "Satış Koşulları" : "Sales Terms"}</a>
          <div className="footer-col-divider"></div>
          <div className="footer-col-title">{lang === "tr" ? "Dil" : "Language"}</div>
          <div className="footer-lang">
            <button className={lang === "tr" ? "active" : ""} onClick={() => setRouteLang("tr", page)} data-hover>TR</button>
            <button className={lang === "en" ? "active" : ""} onClick={() => setRouteLang("en", page)} data-hover>EN</button>
          </div>
        </div>
      </div>

      <div className="site-footer-bottom">
        <span>© 2026 ACYLGRAPHIC · Türkiye · {lang === "tr" ? "Tüm hakları saklıdır" : "All rights reserved"}</span>
        <div className="footer-payments">
          <a className="footer-credit" href="https://www.linkedin.com/in/emre-odemis/" target="_blank" rel="noreferrer" data-hover>
            Created by Emre Ödemiş
          </a>
          {/*<span className="payment-badge">EFT</span>*/}
          {/*<span className="payment-badge">Havale</span>*/}
          {/*<span className="payment-badge">3M™ Cast</span>*/}
          {/*<span className="payment-badge">Drop 07</span>*/}
        </div>
      </div>
    </footer>
  );
}

/* ---------- Reveal observer ---------- */
function useReveal() {
  useEffect(() => {
    const io = new IntersectionObserver(entries => {
      entries.forEach(en => { if (en.isIntersecting) en.target.classList.add("in"); });
    }, { threshold: 0.12 });
    document.querySelectorAll(".reveal:not(.in)").forEach(el => io.observe(el));
    return () => io.disconnect();
  });
}

/* ---------- Speed lines canvas ---------- */
function ParticleField() {
  const ref = useRef(null);
  useEffect(() => {
    const c = ref.current; if (!c) return;
    const ctx = c.getContext("2d");
    let w = c.width = window.innerWidth, h = c.height = window.innerHeight;
    const onResize = () => { w = c.width = window.innerWidth; h = c.height = window.innerHeight; };
    window.addEventListener("resize", onResize);
    const lines = Array.from({length: 40}, () => ({ x: Math.random()*w, y: Math.random()*h, l: Math.random()*120+40, v: Math.random()*3+1, a: Math.random()*0.4+0.05 }));
    let raf;
    const tick = () => {
      const rgb = getComputedStyle(document.documentElement).getPropertyValue("--accent-rgb").trim() || "168,168,184";
      ctx.clearRect(0,0,w,h);
      lines.forEach(p => {
        p.x += p.v;
        if (p.x > w + p.l) { p.x = -p.l; p.y = Math.random()*h; }
        const g = ctx.createLinearGradient(p.x - p.l, p.y, p.x, p.y);
        g.addColorStop(0, `rgba(${rgb},0)`);
        g.addColorStop(1, `rgba(${rgb},${p.a})`);
        ctx.strokeStyle = g; ctx.lineWidth = 1;
        ctx.beginPath(); ctx.moveTo(p.x - p.l, p.y); ctx.lineTo(p.x, p.y); ctx.stroke();
      });
      raf = requestAnimationFrame(tick);
    };
    tick();
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", onResize); };
  }, []);
  return <canvas ref={ref} style={{position:"fixed", inset:0, zIndex:1, pointerEvents:"none", opacity:0.5}}/>;
}

function parseJsonList(value) {
  if (!value) return [];
  try {
    const parsed = typeof value === "string" ? JSON.parse(value) : value;
    return Array.isArray(parsed) ? parsed.filter(Boolean) : [];
  } catch {
    return String(value).split(/\r?\n|,/).map(x => x.trim()).filter(Boolean);
  }
}

function ProductDetail({ product, products, lang, onOrder }) {
  const gallery = [product?.imageUrl, ...parseJsonList(product?.galleryJson)].filter(Boolean);
  const specs = parseJsonList(product?.specsJson);
  const related = products.filter(p => p.id !== product?.id).slice(0, 3);

  if (!product) {
    return (
      <main className="product-detail product-detail-empty">
        <span className="kicker"><span className="dot"></span> 404</span>
        <h1>{lang === "en" ? "Product Not Found" : "Ürün Bulunamadı"}</h1>
        <a className="btn btn-primary" href={`/${lang}/magaza`}><span>{lang === "en" ? "Back To Shop" : "Mağazaya Dön"}</span><span className="arrow"></span></a>
      </main>
    );
  }

  return (
    <main className="product-detail">
      <section className="detail-hero">
        <div className="detail-copy">
          <span className="kicker"><span className="dot"></span> {product.tag} {product.pill ? `· ${product.pill}` : ""}</span>
          <h1>{product.title}</h1>
          <p className="detail-lede">{product.detail || product.sub}</p>
          <div className="detail-price-row">
            <strong>{product.price}</strong>
            {product.old && <s>{product.old}</s>}
            <span>{product.stock > 0 ? `${product.stock} ${lang === "en" ? "in stock" : "adet"}` : (lang === "en" ? "pre-order" : "ön sipariş")}</span>
          </div>
          <div className="detail-actions">
            <button className="btn btn-primary" onClick={() => onOrder(product)} data-hover><span>{lang === "en" ? "Order Now" : "Sipariş Ver"}</span><span className="arrow"></span></button>
            <a className="btn" href={`/${lang}/magaza`} data-hover><span>{lang === "en" ? "Collection" : "Koleksiyon"}</span><span className="arrow"></span></a>
          </div>
        </div>
        <div className="detail-media">
          {gallery.length ? <img src={gallery[0]} alt={product.title}/> : <StickerArt kind={product.art}/>}
          <div className="detail-media-grid"></div>
        </div>
      </section>

      <section className="detail-body">
        <div className="detail-panel">
          <span className="eyebrow">{lang === "en" ? "Application Notes" : "Uygulama Notları"}</span>
          <p>{product.sub}</p>
          <p>{product.detail || (lang === "en" ? "Cast vinyl, gloss laminate and plotter-cut panels prepared for sport motorcycle surfaces." : "Sport motosiklet yüzeyleri için cast vinyl, parlak laminasyon ve plotter kesim paneller.")}</p>
        </div>
        <div className="detail-panel">
          <span className="eyebrow">{lang === "en" ? "Specs" : "Özellikler"}</span>
          <ul>
            {(specs.length ? specs : (lang === "en" ? ["Cast vinyl", "Gloss laminate", "Designer-direct support"] : ["Cast vinyl", "Parlak laminasyon", "Tasarımcıdan direkt destek"])).map(item => <li key={item}>{item}</li>)}
          </ul>
        </div>
        <div className="detail-panel gallery-panel">
          <span className="eyebrow">{lang === "en" ? "Gallery" : "Galeri"}</span>
          <div>
            {gallery.slice(0, 4).map(src => <img key={src} src={src} alt={product.title}/>)}
          </div>
        </div>
      </section>

      <section className="detail-related">
        <header>
          <span className="kicker"><span className="dot"></span> {lang === "en" ? "Related Kits" : "Benzer Ürünler"}</span>
          <h2 className="h-mid">{lang === "en" ? "More From" : "Aynı Drop'tan"}<br/><span style={{color:"var(--accent)"}}>{lang === "en" ? "The Drop" : "Diğerleri"}</span></h2>
        </header>
        <div className="product-grid">
          {related.map(p => <ProductCard key={p.id} p={p} onOrder={onOrder} lang={lang}/>)}
        </div>
      </section>
    </main>
  );
}

/* ---------- Contact / order popup ---------- */
function ContactPopup({ open, product, onClose, lang = "tr" }) {
  if (!open) return null;
  const waUrl = buildWhatsappUrl(product?.title);
  const igUrl = buildInstagramUrl();
  const c = lang === "en" ? {
    kicker: "Order Now",
    desc1: "Order via WhatsApp or Instagram DM.",
    desc2: "We'll get back to you as soon as possible.",
    wa: "Order via WhatsApp",
    ig: "Order via Instagram DM",
    note: "Payment: EFT / Wire Transfer · Shipping: 7—14 days",
  } : {
    kicker: "Sipariş Ver",
    desc1: "WhatsApp veya Instagram DM üzerinden sipariş verin.",
    desc2: "Size en kısa sürede dönüş yaparız.",
    wa: "WhatsApp ile Sipariş Ver",
    ig: "Instagram DM ile Sipariş Ver",
    note: "Ödeme: EFT / Havale · Kargo: 7—14 gün",
  };
  return (
    <div className="contact-overlay" onClick={onClose}>
      <div className="contact-popup" onClick={e => e.stopPropagation()}>
        <button className="order-close" onClick={onClose} data-hover>×</button>
        <span className="kicker"><span className="dot"></span> {c.kicker}</span>
        {product && <h3 className="contact-product-name">{product.title}</h3>}
        <p className="contact-desc">{c.desc1}<br/>{c.desc2}</p>
        <a className="btn btn-primary contact-btn" href={waUrl} target="_blank" rel="noreferrer" data-hover>
          <span>{c.wa}</span><span className="arrow"></span>
        </a>
        <a className="btn contact-btn" href={igUrl} target="_blank" rel="noreferrer" data-hover>
          <span>{c.ig}</span><span className="arrow"></span>
        </a>
        <p className="contact-note">{c.note}</p>
      </div>
    </div>
  );
}

/* ---------- Floating WhatsApp ---------- */
function FloatingWA() {
  return (
    <a
      className="floating-wa"
      href={buildWhatsappUrl()}
      target="_blank"
      rel="noreferrer"
      aria-label="WhatsApp ile iletişim"
      data-hover
    >
      <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
        <path d="M20.52 3.449C18.245 1.165 15.21 0 12.02 0 5.458 0 .103 5.354.1 11.918c0 2.1.548 4.147 1.59 5.957L0 24l6.304-1.654a11.91 11.91 0 0 0 5.71 1.452h.005c6.556 0 11.91-5.354 11.913-11.918.002-3.183-1.237-6.175-3.412-8.431zm-8.5 18.336h-.004a9.89 9.89 0 0 1-5.036-1.379l-.362-.215-3.743.982.998-3.648-.235-.374A9.862 9.862 0 0 1 2.12 11.92c.002-5.455 4.445-9.896 9.903-9.896 2.646 0 5.13 1.03 7.001 2.903a9.848 9.848 0 0 1 2.896 7 9.886 9.886 0 0 1-9.9 9.858zm5.43-7.403c-.297-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.457.13-.605.134-.133.297-.347.446-.521.15-.173.198-.297.297-.495.1-.198.05-.371-.025-.52-.074-.149-.669-1.612-.916-2.207-.241-.579-.487-.5-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/>
      </svg>
      <span>WhatsApp</span>
    </a>
  );
}

/* ---------- Scroll to top ---------- */
function ScrollTop() {
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 400);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <button
      className={`scroll-top${visible ? " visible" : ""}`}
      style={{ pointerEvents: visible ? "auto" : "none" }}
      aria-label="Başa dön"
      data-hover
      onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
    >
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <polyline points="18 15 12 9 6 15"/>
      </svg>
    </button>
  );
}

/* ---------- KVKK Cookie Banner ---------- */
function KvkkBanner({ lang = "tr" }) {
  const [visible, setVisible] = useState(() => !localStorage.getItem("kvkk_ok"));
  if (!visible) return null;
  const accept = () => { localStorage.setItem("kvkk_ok", "1"); setVisible(false); };
  const reject = () => setVisible(false);
  const tr = lang === "tr";
  return (
    <div className="kvkk-banner" role="dialog" aria-label={tr ? "Çerez bildirimi" : "Cookie notice"}>
      <div className="kvkk-text">
        <p style={{margin:"0 0 6px", fontSize:11, color:"var(--ink-1)", fontFamily:"var(--f-mono)", letterSpacing:"0.08em", textTransform:"uppercase"}}>
          {tr ? "Çerez Bildirimi" : "Cookie Notice"}
        </p>
        <p style={{margin:0, fontSize:11, color:"var(--ink-2)", lineHeight:1.7, fontFamily:"var(--f-mono)"}}>
          {tr
            ? <>Bu site yalnızca zorunlu <strong>localStorage</strong> kullanır: dil tercihi, tema ayarı ve bu bildirimin durumu. Analitik, reklam veya üçüncü taraf çerezler <strong>kullanılmaz</strong>. Reddetseniz de site tam işlevsel çalışır; yalnızca tercihleriniz kaydedilmez.</>
            : <>This site uses only essential <strong>localStorage</strong>: language preference, theme setting, and this notice state. No analytics, advertising, or third-party cookies are used. Declining still allows full functionality; your preferences simply won't be saved.</>}
        </p>
      </div>
      <div className="kvkk-actions">
        <button className="kvkk-close" onClick={accept} data-hover>
          {tr ? "Kabul Et" : "Accept"}
        </button>
        <button className="kvkk-reject" onClick={reject} data-hover>
          {tr ? "Reddet" : "Decline"}
        </button>
      </div>
    </div>
  );
}

/* ---------- TWEAKS ---------- */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#a8a8b8",
  "heroWord": "Visualised",
  "particles": true,
  "intensity": 1
}/*EDITMODE-END*/;

function applyAccent(hex) {
  const r = parseInt(hex.slice(1,3),16), g = parseInt(hex.slice(3,5),16), b = parseInt(hex.slice(5,7),16);
  document.documentElement.style.setProperty("--accent", hex);
  document.documentElement.style.setProperty("--accent-rgb", `${r}, ${g}, ${b}`);
}

function App() {
  const [booted, setBooted] = useState(false);
  const [contact, setContact] = useState({ open: false, product: null });
  const [products, setProducts] = useState(null);
  const [route, setRoute] = useState(getRouteInfo);
  const [mobileOpen, setMobileOpen] = useState(false);
  const lang = route.lang;
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffect(() => { applyAccent(t.accent); }, [t.accent]);

  useEffect(() => {
    let alive = true;
    fetch("/api/products", { cache: "no-store" })
      .then(r => r.ok ? r.json() : Promise.reject())
      .then(data => { if (alive && Array.isArray(data)) setProducts(data); })
      .catch(() => { if (alive) setProducts([]); });
    return () => { alive = false; };
  }, []);

  useEffect(() => {
    const parts = window.location.pathname.split("/").filter(Boolean);
    if (!ROUTE_LANGS.includes(parts[0])) {
      const found = PAGES.find(p => p.slug.tr === parts[0] || p.slug.en === parts[0]);
      window.history.replaceState({}, "", `/tr/${found?.slug.tr || "garaj"}`);
    }
    const sync = () => { setRoute(getRouteInfo()); setMobileOpen(false); };
    window.addEventListener("popstate", sync);
    window.addEventListener("languagechange", sync);
    window.addEventListener("routechange", sync);
    return () => {
      window.removeEventListener("popstate", sync);
      window.removeEventListener("languagechange", sync);
      window.removeEventListener("routechange", sync);
    };
  }, []);

  useEffect(() => {
    const pg = PAGES.find(p => p.key === route.page);
    const title = pg?.title[lang];
    document.title = title ? `${title} | ACYLGRAPHIC` : "ACYL/GRAPHIC — Tasarım Hızı.";
  }, [route.page, lang]);

  useReveal();
  useLanguageRuntime(lang);

  const openContact = useCallback((product = null) => {
    setContact({ open: true, product: product || null });
  }, []);

  const onNavigate = useCallback((pageKey) => {
    navigate(lang, pageKey);
  }, [lang]);

  const detailProduct = route.productId ? products.find(p => p.id === route.productId) : null;

  const renderPage = () => {
    if (route.productId) {
      return (
        <div key={`product-${route.productId}`} className="page-transition">
          <ProductDetail product={detailProduct} products={products} lang={lang} onOrder={openContact}/>
        </div>
      );
    }
    if (INFO_PAGES.some(p => p.key === route.page)) {
      return (
        <div key={route.page} className="page-transition">
          <InfoPage pageKey={route.page} lang={lang} onContact={openContact}/>
        </div>
      );
    }
    switch (route.page) {
      case "magaza": return (
        <div key="magaza" className="page-transition">
          <Featured onOrder={openContact} products={products} lang={lang}/>
        </div>
      );
      case "ozel": return (
        <div key="ozel" className="page-transition">
          <CustomSection/>
        </div>
      );
      case "akis": return (
        <div key="akis" className="page-transition">
          <Social/>
        </div>
      );
      case "studyo": return (
        <div key="studyo" className="page-transition">
          <About lang={lang}/>
        </div>
      );
      case "iletisim": return (
        <div key="iletisim" className="page-transition">
          <Final onContact={openContact}/>
        </div>
      );
      default: return (
        <div key="garaj" className="page-transition">
          <Hero t={{hero: t.heroWord}} onContact={openContact} onNavigate={onNavigate}/>
          <Testimonials/>
        </div>
      );
    }
  };

  return (
    <React.Fragment>
      {!booted && <Loader onDone={() => setBooted(true)}/>}
      <Cursor/>
      <div className="bg-stack"></div>
      {t.particles && <ParticleField/>}
      <div className="noise"></div>
      <Nav
        onContact={openContact}
        lang={lang}
        page={route.page}
        onNavigate={onNavigate}
        mobileOpen={mobileOpen}
        onMobileToggle={() => setMobileOpen(prev => !prev)}
      />
      {renderPage()}
      <ContactPopup
        open={contact.open}
        product={contact.product}
        onClose={() => setContact({ open: false, product: null })}
        lang={lang}
      />
      <SiteFooter lang={lang} page={route.page} onNavigate={onNavigate}/>
      <FloatingWA/>
      <ScrollTop/>
      <KvkkBanner lang={lang}/>
      <TweaksPanel title="Tweaks">
        <TweakSection title="Brand Accent">
          <TweakColor label="Accent color" value={t.accent} onChange={v => setTweak("accent", v)}
            options={["#a8a8b8", "#ff2840", "#2bd4ff", "#d4ff00", "#ff7a00", "#b388ff"]}/>
        </TweakSection>
        <TweakSection title="Hero">
          <TweakRadio label="Outlined word" value={t.heroWord} onChange={v => setTweak("heroWord", v)}
            options={[{label:"Visualised", value:"Visualised"}, {label:"Aggression", value:"Aggression"}, {label:"Velocity", value:"Velocity"}]}/>
        </TweakSection>
        <TweakSection title="Motion FX">
          <TweakToggle label="Speed-line particles" value={t.particles} onChange={v => setTweak("particles", v)}/>
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
