// Product Detail — Sayfa 3
// Featured product: Dell Latitude 5550. Aynı header + breadcrumb + 2 sütun + sekmeler.

// ─────────── data: featured product ───────────
const PRODUCT_DETAIL = {
  id: 'p01',
  name: 'Dell Latitude 5550 Business Laptop',
  brand: 'Dell', model: 'Latitude 5550', code: 'DLT-5550-I7-16-512',
  group: 'eu-hw', sub: 'Laptop', groupName: 'Donanım & Aksesuar',
  imgKind: 'laptop', imgFolder: 'DellLatitude5550BusinessLaptop',
  priceNet: 45000, priceUnit: null,
  rating: 4.6, ratingCount: 38,
  stock: 'in-stock', // in-stock | low | order
  stockMsg: 'Stokta mevcut',
  leadTime: '2-3 iş günü içinde teslim',
  galleryLabels: ['ÖNDEN', 'KAPALI', 'KLAVYE DET.', 'PORTLAR'],
  shortDesc: '15.6" FHD ekran · 13. nesil Intel Core i7 · 16 GB RAM · 512 GB NVMe SSD · 3 yıl on-site garanti.',
  approvalDays: 3,
  approvalSteps: ['Yönetici onayı', 'Departman bütçesi', 'IT teknik onay', 'Satınalma'],
  specs: [
    { group: 'İşlemci & Bellek', rows: [
      ['İşlemci', 'Intel® Core™ i7-1355U (12 MB önbellek, 10 çekirdek)'],
      ['Bellek', '16 GB DDR5 5200 MHz (2× 8 GB)'],
      ['Depolama', '512 GB M.2 2280 PCIe NVMe SSD, Class 35'],
      ['Grafik', 'Intel® Iris® Xe Graphics (entegre)'],
    ]},
    { group: 'Ekran & Tasarım', rows: [
      ['Ekran', '15.6" FHD (1920×1080) IPS, parlama önleyici, 250 nits'],
      ['Webcam', 'HD RGB + IR (Windows Hello uyumlu)'],
      ['Klavye', 'Aydınlatmalı, TR Q düzeni, sayısal tuş takımı'],
      ['Ağırlık', '1.62 kg'],
    ]},
    { group: 'Bağlantı & Güç', rows: [
      ['Portlar', '2× Thunderbolt 4 / USB-C, 2× USB-A, HDMI 2.0, RJ-45, 3.5 mm'],
      ['Kablosuz', 'Wi-Fi 6E AX211, Bluetooth 5.3'],
      ['Pil', '54 Whr, ExpressCharge™ (1 saatte %80)'],
      ['Adaptör', '65W USB-C Type-C Adapter'],
    ]},
    { group: 'İşletim Sistemi & Garanti', rows: [
      ['İşletim Sistemi', 'Windows 11 Pro 64-bit (TR)'],
      ['Garanti', '3 yıl ProSupport — sonraki iş günü on-site servis'],
      ['Güvenlik', 'TPM 2.0, parmak izi okuyucu, Kensington kilit yuvası'],
    ]},
  ],
  longDesc: [
    'Latitude 5550, hibrit çalışma düzenine geçiş yapmış profesyoneller için tasarlanmış 15.6" iş laptopudur. ' +
    '13. nesil Intel Core i7 işlemci ve 16 GB DDR5 bellek ile aynı anda çoklu uygulama, video konferans ve büyük tablolar üzerinde rahatça çalışırsınız.',
    'ExpressCharge teknolojisi sayesinde pil 1 saatte %80 doluluğa ulaşır; tüm gün toplantı zincirlerinde kablodan bağımsız çalışabilirsiniz. ' +
    'Standart 65W USB-C adaptör hem laptop hem cep telefonu için kullanılabilir.',
    'Dell ProSupport ile sonraki iş günü on-site servis dahildir — bir sorun yaşandığında IT ekibi cihaz değişimi için ek prosedür yürütmek zorunda kalmaz.',
  ],
  useCases: [
    { title: 'Hibrit ofis profesyoneli',
      body: 'Hafta içi 2-3 gün ofiste, kalan günler evden çalışan, gün boyunca Office uygulamaları, Teams ve tarayıcı ile yoğun çalışan kullanıcılar.' },
    { title: 'Saha & ziyaret odaklı satış',
      body: 'Müşteri ziyaretlerinde sunum yapan, fiyat tabloları üzerinde gerçek zamanlı düzenleme yapan, mobil bağlantı kullanması gereken takımlar.' },
    { title: 'Finans / İK analistleri',
      body: 'Büyük Excel modelleriyle, Power BI raporlarıyla, dijital imza ve PDF onay süreçleriyle çalışan back-office ekipler.' },
    { title: 'Yeni başlayan çalışan standart kit',
      body: 'IT ekibinin yeni işe başlayanlara varsayılan olarak tahsis ettiği, 3 yıllık çevrim için ideal standart bilgisayar.' },
  ],
};

// ─────────── Dinamik ürün detayı ───────────
// Katalogdaki herhangi bir ürünü, detay sayfasının beklediği zengin formata çevirir.
// Bilinen "p01" (Dell Latitude) için elle yazılmış PRODUCT_DETAIL kullanılır.
// Diğer ürünler için imgKind'a göre uygun (sahte ama tutarlı) teknik özellikler üretilir.
function specsForKind(kind, p) {
  const tpl = {
    laptop: [
      { group: 'İşlemci & Bellek', rows: [
        ['İşlemci', 'Intel® Core™ i7 (12. nesil veya üzeri)'],
        ['Bellek', '16 GB DDR5 5200 MHz'],
        ['Depolama', '512 GB M.2 NVMe SSD'],
        ['Grafik', 'Entegre grafik birimi'],
      ]},
      { group: 'Ekran & Tasarım', rows: [
        ['Ekran', '14"-15.6" FHD (1920×1080) IPS, parlama önleyici'],
        ['Klavye', 'Aydınlatmalı, TR Q düzeni'],
        ['Webcam', 'HD RGB + IR (Windows Hello uyumlu)'],
        ['Ağırlık', '~1.6 kg'],
      ]},
      { group: 'Bağlantı & Güç', rows: [
        ['Portlar', '2× USB-C/Thunderbolt, 2× USB-A, HDMI, 3.5 mm'],
        ['Kablosuz', 'Wi-Fi 6E, Bluetooth 5.3'],
        ['Pil', '~54 Whr, hızlı şarj destekli'],
        ['Adaptör', '65W USB-C Type-C Adapter'],
      ]},
      { group: 'İşletim Sistemi & Garanti', rows: [
        ['İşletim Sistemi', 'Windows 11 Pro 64-bit (TR)'],
        ['Garanti', '3 yıl üretici garantisi — sonraki iş günü servis'],
        ['Güvenlik', 'TPM 2.0, parmak izi okuyucu'],
      ]},
    ],
    desktop: [
      { group: 'İşlemci & Bellek', rows: [
        ['İşlemci', 'Intel® Core™ i5 (14. nesil)'],
        ['Bellek', '16 GB DDR5'],
        ['Depolama', '512 GB NVMe SSD'],
        ['Form Faktör', 'USFF / Mini iş istasyonu'],
      ]},
      { group: 'Bağlantı', rows: [
        ['Portlar', '4× USB-A, 2× USB-C, HDMI, DisplayPort, RJ-45'],
        ['Ağ', 'Gigabit Ethernet, Wi-Fi 6'],
        ['Ses', '3.5 mm combo, entegre hoparlör'],
      ]},
      { group: 'Güç & Garanti', rows: [
        ['Güç', '90W harici adaptör'],
        ['Garanti', '3 yıl on-site servis'],
        ['İşletim Sistemi', 'Windows 11 Pro 64-bit (TR)'],
      ]},
    ],
    monitor: [
      { group: 'Panel', rows: [
        ['Ekran Boyutu', '27"'],
        ['Çözünürlük', '3840×2160 (4K UHD)'],
        ['Panel', 'IPS, %99 sRGB, 400 nits'],
        ['Tazeleme', '60 Hz'],
      ]},
      { group: 'Bağlantı', rows: [
        ['USB-C', 'Güç dağıtımı 90W, video + veri tek kabloda'],
        ['Diğer', 'HDMI 2.0, DisplayPort 1.4, 3× USB-A'],
        ['Özellik', 'KVM, Picture-by-Picture'],
      ]},
      { group: 'Tasarım & Garanti', rows: [
        ['Ayak', 'Yükseklik, eğim, dönme ayarlı; VESA 100×100'],
        ['Garanti', '3 yıl Premium Panel Exchange'],
      ]},
    ],
    keyboard: [
      { group: 'Genel', rows: [
        ['Bağlantı', 'Bluetooth + 2.4 GHz USB alıcı + USB-C kablolu'],
        ['Düzen', 'TR Q tam boy (sayısal tuş takımı dahil)'],
        ['Aydınlatma', 'Beyaz arkadan aydınlatma, otomatik sensör'],
      ]},
      { group: 'Kullanım', rows: [
        ['Pil', 'Şarjla 10 güne kadar (aydınlatma ile)'],
        ['Çoklu cihaz', '3 cihaz arasında tek tuşla geçiş'],
        ['Garanti', '2 yıl üretici garantisi'],
      ]},
    ],
    mouse: [
      { group: 'Sensör & Tasarım', rows: [
        ['DPI', '200 – 8000 DPI'],
        ['Tıklama', 'Sessiz tıklama mekanizması'],
        ['Tasarım', 'Sağ el ergonomik'],
      ]},
      { group: 'Bağlantı & Pil', rows: [
        ['Bağlantı', 'Bluetooth + 2.4 GHz USB alıcı'],
        ['Şarj', 'USB-C, 1 dakika hızlı şarj = 3 saat kullanım'],
        ['Pil ömrü', 'Tek şarjla 70 güne kadar'],
        ['Garanti', '2 yıl üretici garantisi'],
      ]},
    ],
    headset: [
      { group: 'Ses', rows: [
        ['Sürücü', '40 mm dinamik'],
        ['Mikrofon', 'Gürültü engelleyici çift mikrofon, Teams sertifikalı'],
        ['Aktif Gürültü', 'ANC + şeffaf mod'],
      ]},
      { group: 'Bağlantı & Pil', rows: [
        ['Bağlantı', 'Bluetooth 5.2 + USB-A donanım kilidi'],
        ['Pil', '37 saat müzik / 24 saat konuşma'],
        ['Şarj', 'USB-C, 15 dk = 8 saat kullanım'],
        ['Garanti', '2 yıl üretici garantisi'],
      ]},
    ],
    webcam: [
      { group: 'Görüntü', rows: [
        ['Çözünürlük', '1080p / 60 fps veya 4K / 30 fps'],
        ['Lens', 'Cam lens, otomatik odak'],
        ['Görüş Açısı', '78° / 90° (ayarlanabilir)'],
      ]},
      { group: 'Diğer', rows: [
        ['Mikrofon', 'Çift gürültü engelleyici'],
        ['Bağlantı', 'USB-C, tak-çalıştır'],
        ['Güvenlik', 'Fiziksel objektif kapağı'],
        ['Garanti', '2 yıl üretici garantisi'],
      ]},
    ],
    dock: [
      { group: 'Bağlantı', rows: [
        ['Host', 'Thunderbolt 4 / USB-C (90W güç dağıtımı)'],
        ['Video Çıkışı', '2× DisplayPort, 1× HDMI, 1× USB-C (DP Alt)'],
        ['USB', '4× USB-A, 1× USB-C (data)'],
        ['Ağ', '2.5 GbE Ethernet'],
      ]},
      { group: 'Diğer', rows: [
        ['Ses', '3.5 mm combo'],
        ['Adaptör', '180W harici'],
        ['Garanti', '3 yıl üretici garantisi'],
      ]},
    ],
    speaker: [
      { group: 'Ses', rows: [
        ['Sürücü', '360° geniş bant'],
        ['Mikrofon', '4 yönlü mikrofon dizisi, gürültü engelleme'],
        ['Yankı önleme', 'Donanımsal akustik yankı engelleyici'],
      ]},
      { group: 'Bağlantı & Pil', rows: [
        ['Bağlantı', 'Bluetooth + USB-C + dongle'],
        ['Pil', 'Tek şarjla 12 saat'],
        ['Garanti', '2 yıl üretici garantisi'],
      ]},
    ],
    'software-ms': [
      { group: 'Abonelik & Lisans', rows: [
        ['Tür', 'Yıllık abonelik, kullanıcı bazlı'],
        ['Aktivasyon', 'Microsoft 365 yönetim portalı üzerinden'],
        ['Cihaz', 'Kullanıcı başına 5 PC/Mac + 5 mobil + 5 tablet'],
      ]},
      { group: 'Servisler', rows: [
        ['E-posta', 'Exchange Online (50 GB / kullanıcı)'],
        ['Depolama', 'OneDrive 1 TB / kullanıcı'],
        ['Uygulamalar', 'Word, Excel, PowerPoint, Outlook, Teams'],
        ['Destek', '7/24 web ve telefon desteği'],
      ]},
    ],
    'software-adobe': [
      { group: 'Lisans', rows: [
        ['Tür', 'Yıllık taahhütlü abonelik'],
        ['Cihaz', 'Kullanıcı başına 2 cihazda aktif kullanım'],
        ['Yönetim', 'Adobe Admin Console üzerinden'],
      ]},
      { group: 'Özellikler', rows: [
        ['PDF', 'Oluşturma, düzenleme, dönüştürme, e-imza'],
        ['OCR', 'Tarama → aranabilir/düzenlenebilir PDF'],
        ['Bulut', 'Adobe Document Cloud entegrasyonu'],
        ['Destek', 'Üretici destek hattı'],
      ]},
    ],
    software: [
      { group: 'Lisans', rows: [
        ['Tür', 'Yıllık abonelik'],
        ['Aktivasyon', 'Üretici portalı üzerinden'],
        ['Cihaz', 'Kullanıcı/cihaz bazlı'],
      ]},
      { group: 'Destek', rows: [
        ['Güncelleme', 'Sürüm güncellemeleri abonelik süresince ücretsiz'],
        ['Destek', 'Üretici destek hattı'],
      ]},
    ],
    'software-tech': [
      { group: 'Lisans', rows: [
        ['Tür', 'Çekirdek/soket bazlı yıllık lisans'],
        ['Aktivasyon', 'Üretici lisans portalı'],
        ['Kapsam', 'Üretim ortamı kullanımı'],
      ]},
      { group: 'Destek', rows: [
        ['Güncelleme', 'Sürüm güncellemeleri dahildir'],
        ['Destek', 'Üretici 7/24 destek (Production-level)'],
      ]},
    ],
    server: [
      { group: 'Donanım', rows: [
        ['Form', '2U rack server'],
        ['CPU', '2× Intel Xeon Silver / Gold işlemci'],
        ['Bellek', '128 GB DDR5 ECC (genişletilebilir)'],
        ['Depolama', 'NVMe + SAS karışık konfigürasyon'],
      ]},
      { group: 'Yönetim & Garanti', rows: [
        ['Yönetim', 'iDRAC / iLO uzak yönetim'],
        ['Güç', 'Çift redundant PSU'],
        ['Garanti', '5 yıl ProSupport, sonraki iş günü on-site'],
      ]},
    ],
    service: [
      { group: 'Hizmet', rows: [
        ['Kapsam', 'Danışmanlık ve uygulama hizmeti'],
        ['Süre', 'Talep edilen adam-gün üzerinden'],
        ['Çalışma', 'Uzaktan + ihtiyaç halinde yerinde'],
      ]},
      { group: 'Çıktılar', rows: [
        ['Rapor', 'Hizmet sonu özet ve öneri raporu'],
        ['Bilgi Transferi', 'IT ekibine bilgi transferi seansı dahil'],
      ]},
    ],
  };
  return tpl[kind] || tpl.software;
}

function detailFromCatalog(cp) {
  const isSoftware = (cp.group || '').startsWith('sw-') || cp.imgKind.startsWith('software');
  const isService = cp.imgKind === 'service';
  const groupName = (window.CATALOG_CATEGORIES.find((g) => g.id === cp.group) || {}).name || '';
  const code = (cp.brand + '-' + cp.model).toUpperCase().replace(/[^A-Z0-9]+/g, '-').replace(/-+$/g, '');

  return {
    id: cp.id,
    name: cp.name,
    brand: cp.brand,
    model: cp.model,
    code,
    group: cp.group,
    sub: cp.sub,
    groupName,
    imgKind: cp.imgKind,
    imgFolder: cp.imgFolder,
    imgExt: cp.imgExt,
    priceNet: cp.priceNet,
    priceUnit: null,
    rating: 4.4,
    ratingCount: Math.max(8, Math.round((cp.requestCount || 20) / 6)),
    stock: isSoftware || isService ? 'order' : 'in-stock',
    stockMsg: isSoftware ? 'Lisans temin edilebilir' : isService ? 'Hizmet planlanabilir' : 'Stokta mevcut',
    leadTime: isSoftware
      ? '1-2 iş günü içinde lisans atanır'
      : isService
        ? 'Plana göre 1-2 hafta içinde başlatılır'
        : '2-5 iş günü içinde teslim',
    galleryLabels: isSoftware || isService
      ? ['LİSANS', 'PORTAL', 'YÖNETİM', 'DESTEK']
      : ['ÖNDEN', 'YANDAN', 'DETAY', 'PORTLAR'],
    shortDesc: cp.desc,
    approvalDays: isService ? 5 : isSoftware ? 2 : 3,
    approvalSteps: ['Yönetici onayı', 'Departman bütçesi', 'IT teknik onay', 'Satınalma'],
    specs: specsForKind(cp.imgKind, cp),
    longDesc: [
      `${cp.brand} ${cp.model}, şirketimizin standart katalogunda yer alan ${cp.sub.toLowerCase()} ürünüdür. ${cp.desc}`,
      isSoftware
        ? 'Lisans yönetim portalı üzerinden kullanıcıya atanır; ilgili çalışan giriş yaptığında uygulamalar otomatik olarak aktive olur. IT ekibinin önceden tanımladığı politikalar bu lisansa da otomatik uygulanır.'
        : isService
          ? 'Bu hizmet, talep onaylandıktan sonra IT ekibi ve tedarikçinin ortak planlaması ile başlatılır. Çalışma süresince düzenli durum raporları paylaşılır ve hizmet sonunda bilgi transferi yapılır.'
          : 'Cihaz, IT ekibi tarafından şirket standartlarına göre kurulmuş ve gerekli kurumsal yazılımları yüklenmiş şekilde teslim edilir. Garanti süresince destek IT üzerinden tek noktadan yürütülür.',
      'Onay süreci tamamlandığında bu talep otomatik olarak satınalma listesine eklenir; teslim tarihi belirlendiğinde ilgili çalışana bildirim gönderilir.',
    ],
    useCases: [
      { title: 'Standart kullanım',
        body: `${cp.sub} ihtiyacı duyan tüm çalışanlar için varsayılan tercih. Şirket içinde en yaygın kullanılan modeldir.` },
      { title: 'Hibrit ofis kullanıcısı',
        body: 'Hafta içi ofis ve evden çalışmayı dönüşümlü yürüten, taşıma ve dayanıklılık önemli olan kullanıcılar için uygundur.' },
      { title: 'Yeni başlayan çalışan',
        body: 'IT ekibinin yeni işe başlayanlara varsayılan olarak tahsis ettiği standart kit kapsamındadır.' },
      { title: 'Yenileme döngüsü',
        body: '3-4 yılını dolduran cihazların yerine geçecek standart modeldir; envanter ve garanti yönetimi kolaylaşır.' },
    ],
  };
}

function getProductDetail(productId) {
  if (productId === 'p01' || !productId) return PRODUCT_DETAIL;
  const cp = (window.CATALOG_PRODUCTS || []).find((x) => x.id === productId);
  if (!cp) return null;
  return detailFromCatalog(cp);
}

// ─────────── small UI atoms ───────────
function StarRating({ value, count, c }) {
  const full = Math.floor(value);
  const half = value - full >= 0.4 && value - full < 0.9;
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
      <div style={{ display: 'inline-flex', gap: 2 }}>
        {[0, 1, 2, 3, 4].map((i) => {
          const filled = i < full;
          const isHalf = i === full && half;
          return (
            <svg key={i} width="14" height="14" viewBox="0 0 24 24" aria-hidden="true">
              <defs>
                <linearGradient id={`half-${i}`} x1="0" x2="1" y1="0" y2="0">
                  <stop offset="50%" stopColor="#F59E0B" />
                  <stop offset="50%" stopColor={c.border} />
                </linearGradient>
              </defs>
              <path
                d="M12 2.5l2.95 5.98 6.6.96-4.78 4.66 1.13 6.57L12 17.6l-5.9 3.07 1.13-6.57L2.45 9.44l6.6-.96L12 2.5z"
                fill={isHalf ? `url(#half-${i})` : (filled ? '#F59E0B' : c.border)}
              />
            </svg>
          );
        })}
      </div>
      <span style={{ fontSize: 12.5, fontWeight: 600, color: c.text }}>{value.toFixed(1)}</span>
      <span style={{ fontSize: 12, color: c.muted }}>({count} değerlendirme)</span>
    </div>
  );
}

function StockBadge({ stock, msg, leadTime, c }) {
  const colors = {
    'in-stock': { bg: 'rgba(16,185,129,0.10)', dot: c.success, text: c.success },
    'low':      { bg: 'rgba(245,158,11,0.10)', dot: '#F59E0B', text: '#B45309' },
    'order':    { bg: 'rgba(59,130,246,0.10)', dot: c.primary, text: c.primary },
  };
  const s = colors[stock];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
      <div style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        padding: '6px 12px', borderRadius: 999,
        background: s.bg, color: s.text,
        fontSize: 12.5, fontWeight: 600,
      }}>
        <span style={{ width: 7, height: 7, borderRadius: 999, background: s.dot }} />
        {msg}
      </div>
      <span style={{ fontSize: 12.5, color: c.muted }}>{leadTime}</span>
    </div>
  );
}

function QuantitySelector({ qty, setQty, c }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center',
      border: `1px solid ${c.border}`, borderRadius: 10,
      overflow: 'hidden',
    }}>
      <button onClick={() => setQty(Math.max(1, qty - 1))} style={qtyBtn(c)} aria-label="Azalt">−</button>
      <div style={{
        minWidth: 56, textAlign: 'center',
        fontSize: 15, fontWeight: 600, color: c.text,
        padding: '8px 0', userSelect: 'none',
      }}>{qty}</div>
      <button onClick={() => setQty(Math.min(99, qty + 1))} style={qtyBtn(c)} aria-label="Arttır">+</button>
    </div>
  );
}
function qtyBtn(c) {
  return {
    appearance: 'none', cursor: 'pointer',
    width: 40, height: 40,
    background: 'transparent', color: c.text,
    border: 'none',
    fontSize: 18, fontWeight: 500, fontFamily: 'inherit',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  };
}

// ─────────── Image gallery ───────────
function ImageGallery({ p, c }) {
  const [active, setActive] = React.useState(0);
  const folder = p.imgFolder ? `images/products/${p.imgFolder}` : null;
  const ext = p.imgExt || 'jpg';
  // 1.<ext> → ana resim, 2-4.<ext> → diğer açılar. Galeri etiketi sayısı kadar resim varsayılıyor.
  const imgFor = (i) => folder ? `${folder}/${i + 1}.${ext}` : null;
  return (
    <div>
      {/* Main image */}
      <div style={{
        height: 460, borderRadius: 16, overflow: 'hidden',
        border: `1px solid ${c.border}`,
        background: c.imgBg,
        position: 'relative',
      }}>
        <ProductPlaceholder kind={p.imgKind} c={c} imgSrc={imgFor(active)} />
        <div style={{
          position: 'absolute', top: 14, left: 14,
          padding: '5px 10px', borderRadius: 999,
          background: c.surface, color: c.muted,
          border: `1px solid ${c.border}`,
          fontSize: 10.5, fontWeight: 600, letterSpacing: '0.06em',
          fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
        }}>
          {p.galleryLabels[active]}
        </div>
      </div>
      {/* Thumbnails */}
      <div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
        {p.galleryLabels.map((lbl, i) => (
          <button
            key={i}
            onClick={() => setActive(i)}
            style={{
              flex: 1, height: 86,
              padding: 0, appearance: 'none', cursor: 'pointer',
              background: c.imgBg,
              border: `2px solid ${i === active ? c.primary : c.border}`,
              borderRadius: 10,
              overflow: 'hidden',
              transition: 'border-color 120ms',
            }}>
            <div style={{ width: '100%', height: '100%' }}>
              <ProductPlaceholder kind={p.imgKind} c={c} imgSrc={imgFor(i)} />
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

// ─────────── Tabs ───────────
function DetailTabs({ p, c }) {
  const [tab, setTab] = React.useState('specs');
  const tabs = [
    { id: 'specs', label: 'Teknik Özellikler' },
    { id: 'desc',  label: 'Açıklama' },
    { id: 'use',   label: 'Kullanım Senaryoları' },
  ];
  return (
    <div style={{ marginTop: 40 }}>
      {/* Tab bar */}
      <div style={{ display: 'flex', gap: 4, borderBottom: `1px solid ${c.border}` }}>
        {tabs.map((t) => {
          const active = tab === t.id;
          return (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              appearance: 'none', cursor: 'pointer',
              background: 'transparent', color: active ? c.text : c.muted,
              border: 'none',
              padding: '12px 16px', marginBottom: -1,
              borderBottom: `2px solid ${active ? c.primary : 'transparent'}`,
              fontSize: 14, fontWeight: active ? 600 : 500, fontFamily: 'inherit',
              transition: 'color 120ms, border-color 120ms',
            }}>{t.label}</button>
          );
        })}
      </div>

      {/* Content */}
      <div style={{ padding: '28px 0' }}>
        {tab === 'specs' && <SpecsTable specs={p.specs} c={c} />}
        {tab === 'desc'  && <DescContent paras={p.longDesc} c={c} />}
        {tab === 'use'   && <UseCasesGrid items={p.useCases} c={c} />}
      </div>
    </div>
  );
}

function SpecsTable({ specs, c }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 1fr',
      gap: 24,
    }}>
      {specs.map((g) => (
        <div key={g.group} style={{
          background: c.card, border: `1px solid ${c.border}`, borderRadius: 12,
          overflow: 'hidden',
        }}>
          <div style={{
            padding: '12px 16px',
            background: c.borderSoft,
            fontSize: 12, fontWeight: 600, color: c.text,
            letterSpacing: '0.02em',
          }}>{g.group}</div>
          <div>
            {g.rows.map(([k, v], i) => (
              <div key={k} style={{
                display: 'grid', gridTemplateColumns: '140px 1fr',
                gap: 16, padding: '11px 16px',
                borderTop: i === 0 ? 'none' : `1px solid ${c.borderSoft}`,
                fontSize: 13, lineHeight: 1.5,
              }}>
                <div style={{ color: c.muted, fontWeight: 500 }}>{k}</div>
                <div style={{ color: c.text }}>{v}</div>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function DescContent({ paras, c }) {
  return (
    <div style={{ maxWidth: 760 }}>
      {paras.map((p, i) => (
        <p key={i} style={{
          margin: i === 0 ? '0 0 14px' : '0 0 14px',
          fontSize: 14, lineHeight: 1.65, color: c.text,
        }}>{p}</p>
      ))}
    </div>
  );
}

function UseCasesGrid({ items, c }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16,
    }}>
      {items.map((u, i) => (
        <div key={i} style={{
          background: c.card, border: `1px solid ${c.border}`, borderRadius: 12,
          padding: 18,
        }}>
          <div style={{
            width: 32, height: 32, borderRadius: 8,
            background: c.selectedBg, color: c.selectedText,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 13, fontWeight: 700,
            marginBottom: 12,
          }}>{i + 1}</div>
          <div style={{ fontSize: 14, fontWeight: 600, color: c.text, marginBottom: 6 }}>
            {u.title}
          </div>
          <p style={{ margin: 0, fontSize: 13, lineHeight: 1.55, color: c.muted }}>
            {u.body}
          </p>
        </div>
      ))}
    </div>
  );
}

// ─────────── Approval info box ───────────
function ApprovalInfoBox({ p, c }) {
  return (
    <div style={{
      background: c.card,
      border: `1px solid ${c.border}`,
      borderRadius: 14,
      padding: 20,
      marginTop: 20,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
        <div style={{
          width: 34, height: 34, borderRadius: 10,
          background: c.selectedBg, color: c.selectedText,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" />
          </svg>
        </div>
        <div>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: c.text }}>
            Onay süreci ortalama <strong style={{ color: c.primary }}>{p.approvalDays} iş günü</strong>
          </div>
          <div style={{ fontSize: 12, color: c.muted, marginTop: 2 }}>
            Bu ürün için tipik onay aşamaları
          </div>
        </div>
      </div>
      <ol style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {p.approvalSteps.map((step, i) => (
          <li key={step} style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 12.5, color: c.text }}>
            <span style={{
              width: 22, height: 22, borderRadius: 999,
              background: c.borderSoft, color: c.muted,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 11, fontWeight: 700, flexShrink: 0,
            }}>{i + 1}</span>
            {step}
          </li>
        ))}
      </ol>
    </div>
  );
}

// ─────────── MAIN PAGE ───────────
function ProductDetailPage({ initialDark = false, productId = 'p01' }) {
  const [dark, setDark] = React.useState(initialDark);
  React.useEffect(() => { setDark(initialDark); }, [initialDark]);

  const [qty, setQty] = React.useState(1);
  const cart = useCartSnapshot();
  const [justAdded, setJustAdded] = React.useState(false);
  const [savedForLater, setSavedForLater] = React.useState(false);
  const [search, setSearch] = React.useState('');

  const c = catalogTheme(dark);
  const p = getProductDetail(productId);

  function goCatalog() {
    if (typeof window.__navigate === 'function') window.__navigate('catalog');
  }

  if (!p) {
    return (
      <div style={{
        width: '100%', height: '100%',
        background: c.bg, color: c.text,
        fontFamily: 'Inter, system-ui, sans-serif',
        display: 'flex', flexDirection: 'column',
      }}>
        <CatalogHeader
          c={c} dark={dark}
          onToggleDark={() => setDark((x) => !x)}
          search={search} setSearch={setSearch}
          cartCount={0} notifCount={3}
        />
        <div style={{
          flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 32,
        }}>
          <div style={{
            maxWidth: 420, textAlign: 'center',
            background: c.surface, border: `1px dashed ${c.border}`,
            borderRadius: 16, padding: '40px 28px',
          }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: c.text }}>Ürün bulunamadı</h2>
            <p style={{ margin: '10px 0 22px', fontSize: 13.5, color: c.muted, lineHeight: 1.55 }}>
              Aradığınız ürün katalogda artık yer almıyor olabilir. Kataloğa dönüp güncel listeyi görüntüleyebilirsiniz.
            </p>
            <button onClick={goCatalog} style={{
              appearance: 'none', cursor: 'pointer', border: 'none',
              padding: '10px 18px', borderRadius: 10,
              background: c.primary, color: '#fff',
              fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
            }}>Kataloğa dön</button>
          </div>
        </div>
      </div>
    );
  }

  function addToCart() {
    if (window.__cart && typeof window.__cart.add === 'function') window.__cart.add(p.id, qty);
    setJustAdded(true);
    setTimeout(() => setJustAdded(false), 1500);
  }

  return (
    <div style={{
      width: '100%', height: '100%',
      background: c.bg, color: c.text,
      fontFamily: 'Inter, system-ui, sans-serif',
      display: 'flex', flexDirection: 'column',
    }}>
      <CatalogHeader
        c={c} dark={dark}
        onToggleDark={() => setDark((x) => !x)}
        search={search} setSearch={setSearch}
        cartCount={cart.length}
        notifCount={3}
      />

      {/* Breadcrumb */}
      <div style={{
        padding: '16px 32px 0',
        display: 'flex', alignItems: 'center', gap: 8,
        fontSize: 12.5, color: c.muted,
      }}>
        <a href="#" onClick={(e) => { e.preventDefault(); goCatalog(); }}
          style={{ color: 'inherit', textDecoration: 'none', cursor: 'pointer' }}>Tüm Ürünler</a>
        <span style={{ color: c.subtle }}>/</span>
        <a href="#" onClick={(e) => { e.preventDefault(); goCatalog(); }}
          style={{ color: 'inherit', textDecoration: 'none', cursor: 'pointer' }}>{p.groupName}</a>
        <span style={{ color: c.subtle }}>/</span>
        <a href="#" onClick={(e) => { e.preventDefault(); goCatalog(); }}
          style={{ color: 'inherit', textDecoration: 'none', cursor: 'pointer' }}>{p.sub}</a>
        <span style={{ color: c.subtle }}>/</span>
        <span style={{ color: c.text, fontWeight: 500 }}>{p.brand} {p.model}</span>
      </div>

      {/* Main content */}
      <div style={{
        padding: '24px 32px 40px',
        display: 'grid', gridTemplateColumns: 'minmax(0, 1.25fr) minmax(0, 1fr)',
        gap: 40,
      }}>
        {/* LEFT — gallery */}
        <div>
          <ImageGallery p={p} c={c} />
        </div>

        {/* RIGHT — buy box */}
        <div>
          <div style={{
            display: 'inline-block',
            fontSize: 10.5, fontWeight: 600, letterSpacing: '0.08em',
            color: c.muted, background: c.chipBg,
            padding: '4px 8px', borderRadius: 4,
            textTransform: 'uppercase',
            marginBottom: 12,
          }}>{p.brand}</div>

          <h1 style={{
            margin: 0, fontSize: 26, fontWeight: 600,
            letterSpacing: '-0.015em', lineHeight: 1.25,
            color: c.text,
          }}>{p.name}</h1>

          <div style={{
            display: 'flex', alignItems: 'center', gap: 14,
            marginTop: 10, flexWrap: 'wrap',
          }}>
            <div style={{ fontSize: 12.5, color: c.muted }}>
              Model: <strong style={{ color: c.text, fontWeight: 600 }}>{p.model}</strong>
            </div>
            <div style={{ width: 4, height: 4, borderRadius: 999, background: c.subtle }} />
            <div style={{ fontSize: 12.5, color: c.muted, fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace' }}>
              {p.code}
            </div>
          </div>

          <div style={{ marginTop: 14 }}>
            <StarRating value={p.rating} count={p.ratingCount} c={c} />
          </div>

          <p style={{
            margin: '20px 0 0', fontSize: 14, lineHeight: 1.6, color: c.muted,
          }}>{p.shortDesc}</p>

          {/* Price block */}
          <div style={{
            marginTop: 22, paddingTop: 22,
            borderTop: `1px solid ${c.border}`,
          }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
              <span style={{
                fontSize: 32, fontWeight: 700, color: c.text,
                letterSpacing: '-0.02em', lineHeight: 1,
              }}>{formatTL(p.priceNet)}</span>
              <span style={{ fontSize: 13, color: c.muted, fontWeight: 500 }}>KDV hariç</span>
            </div>
            <div style={{ fontSize: 12.5, color: c.subtle, marginTop: 6 }}>
              KDV dahil <strong style={{ color: c.text, fontWeight: 600 }}>{formatTL(Math.round(p.priceNet * 1.2))}</strong> · birim fiyat
            </div>
          </div>

          {/* Stock */}
          <div style={{ marginTop: 18 }}>
            <StockBadge stock={p.stock} msg={p.stockMsg} leadTime={p.leadTime} c={c} />
          </div>

          {/* Qty + buttons */}
          <div style={{
            marginTop: 22, display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap',
          }}>
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 500, color: c.muted, marginBottom: 6, letterSpacing: '0.02em' }}>
                Adet
              </div>
              <QuantitySelector qty={qty} setQty={setQty} c={c} />
            </div>
            <div style={{ flex: 1, minWidth: 220 }}>
              <div style={{ fontSize: 11.5, fontWeight: 500, color: 'transparent', marginBottom: 6 }}>—</div>
              <button
                onClick={addToCart}
                disabled={justAdded}
                style={{
                  width: '100%', boxSizing: 'border-box',
                  appearance: 'none', cursor: 'pointer',
                  padding: '12px 18px', height: 40,
                  borderRadius: 10,
                  background: justAdded ? c.success : c.primary, color: '#fff',
                  border: 'none',
                  fontSize: 14, fontWeight: 600, fontFamily: 'inherit',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  boxShadow: justAdded
                    ? `0 6px 14px -4px ${c.success}55`
                    : `0 6px 14px -4px ${c.primary}55`,
                  transition: 'background 160ms',
                }}>
                {justAdded ? UIIcons.check : UIIcons.plus}
                {justAdded ? `${qty} adet sepete eklendi` : 'Sepete Ekle'}
              </button>
            </div>
          </div>

          <button
            onClick={() => setSavedForLater(true)}
            style={{
              marginTop: 10, width: '100%', boxSizing: 'border-box',
              appearance: 'none', cursor: 'pointer',
              padding: '11px 18px', borderRadius: 10,
              background: 'transparent', color: c.text,
              border: `1px solid ${c.border}`,
              fontSize: 13.5, fontWeight: 500, fontFamily: 'inherit',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              transition: 'background 120ms',
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = c.borderSoft}
            onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
            {savedForLater ? (
              <React.Fragment>
                <span style={{ color: c.success, display: 'flex' }}>{UIIcons.check}</span>
                Taleplerime kaydedildi
              </React.Fragment>
            ) : (
              <React.Fragment>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z" />
                </svg>
                Taleplerime Ekle <span style={{ color: c.muted, fontWeight: 400 }}>· sonra karar vereceğim</span>
              </React.Fragment>
            )}
          </button>

          {/* Approval info — sağ köşede sabit kutu */}
          <ApprovalInfoBox p={p} c={c} />
        </div>
      </div>

      {/* Tabs */}
      <div style={{ padding: '0 32px 40px' }}>
        <DetailTabs p={p} c={c} />
      </div>
    </div>
  );
}

Object.assign(window, {
  PRODUCT_DETAIL, ProductDetailPage,
  StarRating, StockBadge, QuantitySelector, ImageGallery,
  DetailTabs, SpecsTable, DescContent, UseCasesGrid, ApprovalInfoBox,
});
