// Catalog — ana katalog sayfası (Login sonrası gelen sayfa)
// Tam interaktif: kategori filtre, arama, sıralama, sepete ekleme, ızgara/liste toggle

// ─────────── theme helper ───────────
function catalogTheme(dark) {
  return dark
    ? {
        bg: '#0B1220',
        surface: '#0F172A',
        sidebar: '#0B1220',
        header: '#0F172A',
        card: '#0F172A',
        cardHover: '#13213A',
        imgBg: '#0B1220',
        imgStripe: 'rgba(255,255,255,0.04)',
        text: '#F1F5F9',
        muted: '#94A3B8',
        subtle: '#64748B',
        border: '#1F2A3D',
        borderSoft: '#172238',
        chipBg: 'rgba(255,255,255,0.05)',
        inputBg: '#0B1220',
        selectedBg: 'rgba(37,99,235,0.14)',
        selectedText: '#93C5FD',
        primary: '#2563EB',
        success: '#10B981',
        danger: '#EF4444',
      }
    : {
        bg: '#F6F8FB',
        surface: '#FFFFFF',
        sidebar: '#FFFFFF',
        header: '#FFFFFF',
        card: '#FFFFFF',
        cardHover: '#FBFDFF',
        imgBg: '#F1F5F9',
        imgStripe: 'rgba(15,23,42,0.04)',
        text: '#0F172A',
        muted: '#64748B',
        subtle: '#94A3B8',
        border: '#E2E8F0',
        borderSoft: '#EEF2F7',
        chipBg: '#F1F5F9',
        inputBg: '#F8FAFC',
        selectedBg: '#EFF4FF',
        selectedText: '#1D4ED8',
        primary: '#2563EB',
        success: '#10B981',
        danger: '#EF4444',
      };
}

// ─────────── icons ───────────
const CatIcons = {
  monitor: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="4" width="18" height="12" rx="2" /><path d="M8 20h8M12 16v4" />
    </svg>
  ),
  disc: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9" /><circle cx="12" cy="12" r="3" />
    </svg>
  ),
  wrench: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14.7 6.3a4 4 0 0 0-5.4 5.4L3 18l3 3 6.3-6.3a4 4 0 0 0 5.4-5.4l-2.5 2.5-2-2 2.5-2.5Z" />
    </svg>
  ),
  microsoft: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="3" width="8" height="8" rx="1" />
      <rect x="13" y="3" width="8" height="8" rx="1" />
      <rect x="3" y="13" width="8" height="8" rx="1" />
      <rect x="13" y="13" width="8" height="8" rx="1" />
    </svg>
  ),
  remote: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="4" width="20" height="13" rx="2" />
      <path d="M8 21h8M12 17v4" />
      <path d="M9 10l3-3 3 3M12 7v6" />
    </svg>
  ),
};

const UIIcons = {
  search: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" />
    </svg>
  ),
  bell: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" /><path d="M10 21a2 2 0 0 0 4 0" />
    </svg>
  ),
  cart: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="9" cy="20" r="1.5" /><circle cx="18" cy="20" r="1.5" />
      <path d="M2 3h3l2.7 12.2a2 2 0 0 0 2 1.6h7.5a2 2 0 0 0 2-1.5L21 8H6" />
    </svg>
  ),
  grid: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
      <rect x="3" y="3" width="8" height="8" rx="1.5" /><rect x="13" y="3" width="8" height="8" rx="1.5" />
      <rect x="3" y="13" width="8" height="8" rx="1.5" /><rect x="13" y="13" width="8" height="8" rx="1.5" />
    </svg>
  ),
  list: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
      <rect x="3" y="4" width="18" height="4" rx="1" /><rect x="3" y="10" width="18" height="4" rx="1" />
      <rect x="3" y="16" width="18" height="4" rx="1" />
    </svg>
  ),
  chevDown: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 9l6 6 6-6" />
    </svg>
  ),
  check: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20 6L9 17l-5-5" />
    </svg>
  ),
  plus: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 5v14M5 12h14" />
    </svg>
  ),
  emptyBox: (
    <svg width="64" height="64" viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M8 22l24-12 24 12-24 12L8 22Z" />
      <path d="M8 22v22l24 12 24-12V22" />
      <path d="M32 34v22" />
      <path d="M20 16l24 12" strokeDasharray="2 3" />
    </svg>
  ),
};

// ─────────── product image placeholder ───────────
// Stripe pattern + monospace etiket — gerçek görsel gelene kadar
function ProductPlaceholder({ kind, c, imgSrc, fit = 'contain' }) {
  const [failed, setFailed] = React.useState(false);
  // Görsel verilmişse ve yüklenebildiyse onu göster; yoksa eski stilize placeholder'a düş.
  if (imgSrc && !failed) {
    return (
      <div style={{
        width: '100%', height: '100%',
        background: c.imgBg,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        overflow: 'hidden',
      }}>
        <img
          src={imgSrc}
          alt=""
          onError={() => setFailed(true)}
          style={{
            width: '100%', height: '100%',
            objectFit: fit,
            display: 'block',
          }}
        />
      </div>
    );
  }

  const labels = {
    laptop: 'LAPTOP', desktop: 'DESKTOP', monitor: 'MONITÖR',
    keyboard: 'KLAVYE', mouse: 'MOUSE', headset: 'KULAKLIK',
    webcam: 'WEB CAM', dock: 'DOCK', speaker: 'HOPARLÖR',
    server: 'SERVER', service: 'SERVİS',
    'software-ms': 'SOFTWARE · MS',
    'software-adobe': 'SOFTWARE · ADOBE',
    'software-tech': 'SOFTWARE',
    software: 'SOFTWARE',
  };
  const label = labels[kind] || 'PRODUCT';
  return (
    <div style={{
      width: '100%', height: '100%',
      position: 'relative',
      background: c.imgBg,
      backgroundImage: `repeating-linear-gradient(45deg, ${c.imgStripe} 0 2px, transparent 2px 14px)`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: c.subtle,
      fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
      fontSize: 10, letterSpacing: '0.18em', fontWeight: 600,
    }}>
      <div style={{
        padding: '5px 9px',
        background: c.surface,
        border: `1px solid ${c.border}`,
        borderRadius: 4,
        boxShadow: '0 1px 0 rgba(15,23,42,0.04)',
      }}>{label}</div>
    </div>
  );
}

// ─────────── HEADER ───────────
function CatalogHeader({ c, dark, onToggleDark, search, setSearch, cartCount, notifCount, initialBellOpen = false, onNavigate }) {
  const go = (page) => {
    if (typeof onNavigate === 'function') onNavigate(page);
    else if (typeof window.__navigate === 'function') window.__navigate(page);
  };
  const [profileOpen, setProfileOpen] = React.useState(false);
  const [bellOpen, setBellOpen] = React.useState(initialBellOpen);
  // Bildirimler paylaşılan state'ten okunur; sayfaların gönderdiği notifCount prop'unu yok say
  const notifs = useNotifSnapshot();
  const liveNotifCount = notifs.filter((n) => !n.read).length;
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 20,
      height: 64,
      background: c.header,
      borderBottom: `1px solid ${c.border}`,
      display: 'flex', alignItems: 'center',
      padding: '0 24px',
      gap: 24,
    }}>
      {/* Search — fills middle */}
      <div style={{ flex: 1, maxWidth: 560, position: 'relative' }}>
        <span style={{
          position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)',
          color: c.muted, display: 'flex', pointerEvents: 'none',
        }}>{UIIcons.search}</span>
        <input
          type="text"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Ürün, yazılım veya hizmet ara..."
          style={{
            width: '100%', boxSizing: 'border-box',
            padding: '10px 14px 10px 40px',
            background: c.inputBg, color: c.text,
            border: `1px solid ${c.border}`, borderRadius: 10,
            fontSize: 13.5, fontFamily: 'inherit', outline: 'none',
            transition: 'border-color 120ms, box-shadow 120ms',
          }}
          onFocus={(e) => { e.target.style.borderColor = c.primary; e.target.style.boxShadow = `0 0 0 3px ${c.primary}22`; }}
          onBlur={(e) => { e.target.style.borderColor = c.border; e.target.style.boxShadow = 'none'; }}
        />
      </div>

      {/* Right cluster */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginLeft: 'auto' }}>
        <div style={{ position: 'relative' }}>
          <HeaderIconButton c={c} title="Bildirimler" badge={liveNotifCount} onClick={() => setBellOpen((x) => !x)}>{UIIcons.bell}</HeaderIconButton>
          {bellOpen && (
            <React.Fragment>
              <div onClick={() => setBellOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 30 }} />
              {window.NotifDropdown && (
                <window.NotifDropdown
                  c={c}
                  items={notifs}
                  onClose={() => setBellOpen(false)}
                  onSeeAll={() => { setBellOpen(false); go('notifications'); }}
                  onMarkAllRead={() => {
                    if (window.__notif && typeof window.__notif.markAll === 'function') window.__notif.markAll();
                    setBellOpen(false);
                  }}
                />
              )}
            </React.Fragment>
          )}
        </div>
        <HeaderIconButton c={c} title="Sepet" badge={cartCount} badgeColor={c.primary} onClick={() => go('cart')}>{UIIcons.cart}</HeaderIconButton>

        <a href="#" onClick={(e) => { e.preventDefault(); go('requests'); }} style={{
          padding: '8px 12px', borderRadius: 8,
          color: c.text, fontSize: 13.5, fontWeight: 500,
          textDecoration: 'none',
          transition: 'background 120ms',
        }}
        onMouseEnter={(e) => e.currentTarget.style.background = c.borderSoft}
        onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
          Taleplerim
        </a>

        <DarkToggle dark={dark} onToggle={onToggleDark} />

        <div style={{ position: 'relative', marginLeft: 6 }}>
          <button onClick={() => setProfileOpen((x) => !x)} style={{
            appearance: 'none', border: 'none', cursor: 'pointer',
            background: 'transparent',
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '4px 10px 4px 4px', borderRadius: 999,
            transition: 'background 120ms',
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = c.borderSoft}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
            <div style={{
              width: 32, height: 32, borderRadius: 999,
              background: 'linear-gradient(135deg, #2563EB, #1D4ED8)',
              color: '#fff', fontSize: 12, fontWeight: 600,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              letterSpacing: '0.02em',
            }}>AK</div>
            <span style={{ fontSize: 13.5, fontWeight: 500, color: c.text }}>Ayşe Kaya</span>
            <span style={{ color: c.muted, display: 'flex' }}>{UIIcons.chevDown}</span>
          </button>

          {profileOpen && (
            <React.Fragment>
              <div onClick={() => setProfileOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 30 }} />
              <div style={{
                position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 31,
                width: 220,
                background: c.surface,
                border: `1px solid ${c.border}`,
                borderRadius: 12,
                boxShadow: '0 10px 30px -8px rgba(15,23,42,0.18)',
                padding: 6,
              }}>
                <div style={{ padding: '10px 12px', borderBottom: `1px solid ${c.borderSoft}` }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: c.text }}>Ayşe Kaya</div>
                  <div style={{ fontSize: 11.5, color: c.muted, marginTop: 2 }}>ayse.kaya@sirket.com</div>
                </div>
                {['Profilim', 'Bütçem & Limitlerim', 'Bildirim Tercihleri'].map((it) => (
                  <button key={it} style={dropdownItemStyle(c)} onClick={() => { setProfileOpen(false); go('profile'); }}>{it}</button>
                ))}
                <div style={{ height: 1, background: c.borderSoft, margin: '4px 0' }} />
                <button
                  onClick={() => { setProfileOpen(false); go('__logout'); }}
                  style={{ ...dropdownItemStyle(c), color: c.danger }}>Çıkış Yap</button>
              </div>
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
  );
}

function dropdownItemStyle(c) {
  return {
    width: '100%', textAlign: 'left',
    appearance: 'none', border: 'none', cursor: 'pointer',
    background: 'transparent', color: c.text,
    padding: '9px 12px', borderRadius: 8,
    fontSize: 13, fontFamily: 'inherit', fontWeight: 500,
    transition: 'background 120ms',
  };
}

function HeaderIconButton({ c, title, badge, badgeColor = '#EF4444', children, onClick }) {
  return (
    <button title={title} onClick={onClick} style={{
      position: 'relative',
      appearance: 'none', border: 'none', cursor: 'pointer',
      background: 'transparent', color: c.text,
      width: 38, height: 38, borderRadius: 10,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      transition: 'background 120ms',
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = c.borderSoft}
    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
      {children}
      {badge > 0 && (
        <span style={{
          position: 'absolute', top: 4, right: 4,
          minWidth: 17, height: 17, padding: '0 4px', boxSizing: 'border-box',
          background: badgeColor, color: '#fff',
          fontSize: 10.5, fontWeight: 700, lineHeight: '17px',
          borderRadius: 999,
          textAlign: 'center',
          border: `2px solid ${c.header}`,
        }}>{badge}</span>
      )}
    </button>
  );
}

// ─────────── Paylaşılan sepete abone olan hook ───────────
// Sepet App seviyesinde tutulur, window.__cart üzerinden expose edilir.
// Bu hook 'cartchange' olayını dinleyip güncel items dizisini döner.
function useCartSnapshot() {
  const [items, setItems] = React.useState(() => (window.__cart && window.__cart.items) || []);
  React.useEffect(() => {
    const sync = () => setItems((window.__cart && window.__cart.items) || []);
    window.addEventListener('cartchange', sync);
    sync(); // mount sırasında, App'in setup'ı tamamlanmış olabilir
    return () => window.removeEventListener('cartchange', sync);
  }, []);
  return items;
}

// Paylaşılan bildirimleri abone ol — App seviyesinde tutulan items
function useNotifSnapshot() {
  const [items, setItems] = React.useState(() => (window.__notif && window.__notif.items) || []);
  React.useEffect(() => {
    const sync = () => setItems((window.__notif && window.__notif.items) || []);
    window.addEventListener('notifchange', sync);
    sync();
    return () => window.removeEventListener('notifchange', sync);
  }, []);
  return items;
}

// Paylaşılan talepler abonesi
function useRequestsSnapshot() {
  const [items, setItems] = React.useState(() => (window.__requests && window.__requests.items) || []);
  React.useEffect(() => {
    const sync = () => setItems((window.__requests && window.__requests.items) || []);
    window.addEventListener('requestschange', sync);
    sync();
    return () => window.removeEventListener('requestschange', sync);
  }, []);
  return items;
}

Object.assign(window, { catalogTheme, CatIcons, UIIcons, ProductPlaceholder, CatalogHeader, useCartSnapshot, useNotifSnapshot, useRequestsSnapshot });
