// Catalog — sidebar + filter bar + product card + empty state + main page

// ─────────── SIDEBAR ───────────
function CatalogSidebar({ c, dark, selectedSub, selectedGroup, onSelectAll, onSelectGroup, onSelectSub }) {
  // İlk açılışta tüm kategoriler kapalı; aynı anda yalnız biri açık (akordiyon)
  const [expanded, setExpanded] = React.useState({});
  const toggleGroup = (id) => setExpanded((e) => (e[id] ? {} : { [id]: true }));

  const allActive = !selectedSub && !selectedGroup;

  return (
    <aside style={{
      width: 300, flexShrink: 0,
      borderRight: `1px solid ${c.border}`,
      background: c.sidebar,
      padding: '22px 0 32px',
      overflow: 'visible',
    }}>
      {/* "ANA KATEGORİLER" başlığı */}
      <div style={{
        padding: '0 22px 12px',
        fontSize: 10.5, fontWeight: 700, letterSpacing: '0.16em',
        color: c.subtle, textTransform: 'uppercase',
      }}>Ana Kategoriler</div>

      {/* Tüm ürünler */}
      <SidebarRow
        c={c}
        active={allActive}
        onClick={onSelectAll}
        label="Tüm Ürünler"
        bold
        countBadge={CATALOG_PRODUCTS.length}
      />

      <div style={{ height: 8 }} />

      {/* Groups */}
      {CATALOG_CATEGORIES.map((g) => {
        const isGroupActive = selectedGroup === g.id && !selectedSub;
        const groupHasSelected = selectedGroup === g.id;
        const groupCount = CATALOG_PRODUCTS.filter((p) => p.group === g.id).length;
        const isExpanded = expanded[g.id];
        return (
          <div key={g.id} style={{ marginTop: 4 }}>
            <SidebarRow
              c={c}
              active={isGroupActive}
              accent={groupHasSelected && !isGroupActive}
              onClick={() => onSelectGroup(g.id)}
              onChevronClick={() => toggleGroup(g.id)}
              icon={CatIcons[g.iconKey]}
              label={g.name}
              bold
              expanded={isExpanded}
              chevron
              countBadge={groupCount}
            />
            {isExpanded && (
              <div style={{ padding: '4px 0 10px' }}>
                {g.subs.map((s) => {
                  const subCount = CATALOG_PRODUCTS.filter((p) => p.sub === s).length;
                  const subActive = selectedSub === s;
                  return (
                    <SidebarRow
                      key={s}
                      c={c}
                      indent
                      active={subActive}
                      onClick={() => onSelectSub(g.id, s)}
                      label={s}
                      muted={subCount === 0}
                      countBadge={subCount > 0 ? subCount : null}
                    />
                  );
                })}
              </div>
            )}
          </div>
        );
      })}
    </aside>
  );
}

function SidebarRow({ c, active, accent, onClick, onChevronClick, icon, label, bold, expanded, chevron, indent, muted, countBadge }) {
  return (
    <div style={{ position: 'relative' }}>
      {active && (
        <span style={{
          position: 'absolute', left: 0, top: 6, bottom: 6, width: 3,
          background: c.primary, borderRadius: '0 3px 3px 0',
        }} />
      )}
      <button
        onClick={onClick}
        style={{
          boxSizing: 'border-box',
          textAlign: 'left',
          appearance: 'none', border: 'none', cursor: 'pointer',
          background: active ? c.selectedBg : 'transparent',
          color: active ? c.selectedText : (muted ? c.subtle : c.text),
          fontWeight: bold ? 600 : 500,
          fontSize: bold ? 13 : 12.5,
          fontFamily: 'inherit',
          padding: indent ? '6px 16px 6px 42px' : '8px 18px',
          margin: '0 8px',
          width: 'calc(100% - 16px)',
          borderRadius: 8,
          display: 'flex', alignItems: 'center', gap: 10,
          transition: 'background 120ms',
        }}
        onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = c.borderSoft; }}
        onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
        {icon && <span style={{ color: active ? c.selectedText : (accent ? c.primary : c.muted), display: 'flex', flexShrink: 0 }}>{icon}</span>}
        <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
        {countBadge != null && (
          <span style={{
            fontSize: 10.5, fontWeight: 600,
            color: active ? c.selectedText : c.subtle,
            background: active ? 'transparent' : c.chipBg,
            padding: '2px 7px', borderRadius: 999,
            minWidth: 18, textAlign: 'center',
          }}>{countBadge}</span>
        )}
        {chevron && (
          <span
            onClick={(e) => { e.stopPropagation(); onChevronClick && onChevronClick(); }}
            style={{
              color: c.muted, display: 'flex',
              transform: expanded ? 'rotate(0deg)' : 'rotate(-90deg)',
              transition: 'transform 160ms',
              padding: 2, marginRight: -2,
            }}>
            {UIIcons.chevDown}
          </span>
        )}
      </button>
    </div>
  );
}

// ─────────── FILTER BAR ───────────
function FilterBar({ c, count, sort, setSort, viewMode, setViewMode, title, subtitle }) {
  const [sortOpen, setSortOpen] = React.useState(false);
  const sortLabels = {
    popular: 'En çok talep edilen',
    priceAsc: 'Fiyat (artan)',
    priceDesc: 'Fiyat (azalan)',
    az: 'Alfabetik (A → Z)',
  };
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 16, padding: '20px 28px 14px',
    }}>
      <div>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em', color: c.text }}>
          {title}
        </h1>
        <p style={{ margin: '4px 0 0', fontSize: 13, color: c.muted }}>
          {subtitle && <span>{subtitle} · </span>}
          <strong style={{ color: c.text, fontWeight: 600 }}>{count}</strong> ürün gösteriliyor
        </p>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        {/* Sort dropdown */}
        <div style={{ position: 'relative' }}>
          <button onClick={() => setSortOpen((x) => !x)} style={{
            appearance: 'none', cursor: 'pointer',
            background: c.surface, color: c.text,
            border: `1px solid ${c.border}`, borderRadius: 10,
            padding: '8px 12px',
            fontSize: 12.5, fontWeight: 500, fontFamily: 'inherit',
            display: 'inline-flex', alignItems: 'center', gap: 8,
          }}>
            <span style={{ color: c.muted }}>Sırala:</span>
            <span>{sortLabels[sort]}</span>
            <span style={{ color: c.muted, display: 'flex' }}>{UIIcons.chevDown}</span>
          </button>
          {sortOpen && (
            <React.Fragment>
              <div onClick={() => setSortOpen(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,
              }}>
                {Object.entries(sortLabels).map(([k, lbl]) => (
                  <button key={k}
                    onClick={() => { setSort(k); setSortOpen(false); }}
                    style={{
                      ...dropdownItemStyle(c),
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                      background: sort === k ? c.selectedBg : 'transparent',
                      color: sort === k ? c.selectedText : c.text,
                    }}>
                    <span>{lbl}</span>
                    {sort === k && <span style={{ display: 'flex' }}>{UIIcons.check}</span>}
                  </button>
                ))}
              </div>
            </React.Fragment>
          )}
        </div>

        {/* View toggle */}
        <div style={{
          display: 'inline-flex',
          background: c.surface, border: `1px solid ${c.border}`, borderRadius: 10,
          padding: 3,
        }}>
          {[
            { v: 'grid', icon: UIIcons.grid, title: 'Izgara' },
            { v: 'list', icon: UIIcons.list, title: 'Liste' },
          ].map((opt) => (
            <button key={opt.v}
              title={opt.title}
              onClick={() => setViewMode(opt.v)}
              style={{
                appearance: 'none', cursor: 'pointer',
                width: 32, height: 30,
                background: viewMode === opt.v ? c.selectedBg : 'transparent',
                color: viewMode === opt.v ? c.selectedText : c.muted,
                border: 'none', borderRadius: 8,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                transition: 'background 120ms',
              }}>
              {opt.icon}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─────────── PRODUCT CARD (grid) ───────────
function ProductCard({ p, c, onAdd, onOpen, justAdded }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div
      onClick={onOpen}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', flexDirection: 'column',
        background: c.card,
        border: `1px solid ${c.border}`,
        borderRadius: 14,
        overflow: 'hidden',
        transition: 'transform 160ms, box-shadow 160ms, border-color 160ms',
        transform: hover ? 'translateY(-2px)' : 'none',
        boxShadow: hover
          ? '0 14px 30px -16px rgba(15,23,42,0.20)'
          : '0 1px 0 rgba(15,23,42,0.02)',
        cursor: 'pointer',
      }}>
      {/* Image area */}
      <div style={{ height: 160, position: 'relative', overflow: 'hidden' }}>
        <ProductPlaceholder kind={p.imgKind} c={c} imgSrc={p.imgFolder ? `images/products/${p.imgFolder}/1.${p.imgExt || 'jpg'}` : null} />
      </div>

      {/* Body */}
      <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 10, flex: 1 }}>
        <div>
          <div style={{
            display: 'inline-block',
            fontSize: 10.5, fontWeight: 600, letterSpacing: '0.06em',
            color: c.muted,
            background: c.chipBg,
            padding: '3px 7px', borderRadius: 4,
            textTransform: 'uppercase',
          }}>{p.brand} · {p.model}</div>
        </div>

        <h3 style={{
          margin: 0, fontSize: 14, fontWeight: 600, lineHeight: 1.35,
          color: c.text,
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
          minHeight: 38,
        }}>{p.name}</h3>

        <p style={{
          margin: 0, fontSize: 12.5, lineHeight: 1.5, color: c.muted,
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
          minHeight: 38,
        }}>{p.desc}</p>

        {/* Price */}
        <div style={{ marginTop: 'auto', paddingTop: 4 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <span style={{ fontSize: 19, fontWeight: 700, color: c.text, letterSpacing: '-0.01em' }}>
              {formatTL(p.priceNet)}
            </span>
            {p.priceUnit && (
              <span style={{ fontSize: 11.5, color: c.muted, fontWeight: 500 }}>/ {p.priceUnit}</span>
            )}
          </div>
          <div style={{ fontSize: 11, color: c.subtle, marginTop: 2 }}>
            KDV hariç · KDV dahil {formatTL(Math.round(p.priceNet * 1.2))}
          </div>
        </div>

        {/* Add to cart */}
        <AddToCartButton c={c} justAdded={justAdded} onAdd={onAdd} />
      </div>
    </div>
  );
}

function AddToCartButton({ c, justAdded, onAdd }) {
  return (
    <button
      onClick={(e) => { e.stopPropagation(); onAdd(); }}
      disabled={justAdded}
      style={{
        marginTop: 6,
        width: '100%', boxSizing: 'border-box',
        appearance: 'none', cursor: 'pointer',
        padding: '10px 14px', borderRadius: 10,
        background: justAdded ? c.success : c.primary,
        color: '#fff', border: 'none',
        fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        transition: 'background 160ms',
        boxShadow: justAdded
          ? `0 6px 14px -4px ${c.success}55`
          : `0 6px 14px -4px ${c.primary}55`,
      }}>
      {justAdded ? UIIcons.check : UIIcons.plus}
      {justAdded ? 'Sepete Eklendi' : 'Sepete Ekle'}
    </button>
  );
}

// ─────────── PRODUCT ROW (list view) ───────────
function ProductRow({ p, c, onAdd, onOpen, justAdded }) {
  return (
    <div
      onClick={onOpen}
      style={{
      display: 'grid',
      gridTemplateColumns: '128px 1fr auto auto',
      gap: 20,
      alignItems: 'center',
      background: c.card,
      border: `1px solid ${c.border}`,
      borderRadius: 12,
      padding: 14,
      cursor: 'pointer',
    }}>
      <div style={{ height: 80, borderRadius: 8, overflow: 'hidden' }}>
        <ProductPlaceholder kind={p.imgKind} c={c} imgSrc={p.imgFolder ? `images/products/${p.imgFolder}/1.${p.imgExt || 'jpg'}` : null} />
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{
          fontSize: 10.5, fontWeight: 600, letterSpacing: '0.06em',
          color: c.muted, textTransform: 'uppercase', marginBottom: 5,
        }}>{p.brand} · {p.model}</div>
        <h3 style={{ margin: 0, fontSize: 14.5, fontWeight: 600, color: c.text }}>{p.name}</h3>
        <p style={{
          margin: '4px 0 0', fontSize: 12.5, color: c.muted, lineHeight: 1.5,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{p.desc}</p>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontSize: 17, fontWeight: 700, color: c.text }}>{formatTL(p.priceNet)}</div>
        <div style={{ fontSize: 11, color: c.subtle, marginTop: 2 }}>
          {p.priceUnit ? `/ ${p.priceUnit} · ` : ''}KDV hariç
        </div>
      </div>
      <div style={{ width: 160 }}>
        <AddToCartButton c={c} justAdded={justAdded} onAdd={onAdd} />
      </div>
    </div>
  );
}

// ─────────── ÖZEL TALEP MODALI ───────────
// Katalogda olmayan ürün/hizmet için kullanıcı bu modal ile IT'ye doğrudan talep gönderir.
function CustomRequestModal({ open, onClose, c }) {
  const [name, setName] = React.useState('');
  const [justification, setJustification] = React.useState('');
  const [link, setLink] = React.useState('');
  const [budget, setBudget] = React.useState('');
  const [errorFlash, setErrorFlash] = React.useState(false);
  const [successId, setSuccessId] = React.useState(null);

  React.useEffect(() => {
    if (!open) {
      setName(''); setJustification(''); setLink(''); setBudget('');
      setErrorFlash(false); setSuccessId(null);
    }
  }, [open]);

  if (!open) return null;

  const nameOk = name.trim().length > 0;
  const justOk = justification.trim().length > 0;
  const canSubmit = nameOk && justOk;

  function submit() {
    if (!canSubmit) { setErrorFlash(true); return; }
    let id = null;
    if (window.__requests && typeof window.__requests.addCustom === 'function') {
      id = window.__requests.addCustom({ name: name.trim(), justification: justification.trim(), link: link.trim(), budget: budget.trim() });
    }
    setSuccessId(id || '#IT-2026-SP-001');
  }

  function goRequests() {
    onClose();
    if (typeof window.__navigate === 'function') window.__navigate('requests');
  }

  const labelStyle = { fontSize: 12.5, fontWeight: 500, color: c.text, marginBottom: 6, display: 'block' };
  const hintStyle = { fontSize: 11.5, color: c.muted, marginTop: 4 };
  const inputStyle = (invalid) => ({
    width: '100%', boxSizing: 'border-box',
    padding: '10px 12px', borderRadius: 10,
    background: c.surface, color: c.text,
    border: `1px solid ${invalid ? c.danger : c.border}`,
    fontSize: 13.5, fontFamily: 'inherit', outline: 'none',
    transition: 'border-color 120ms',
  });

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(15,23,42,0.45)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 560,
        background: c.card, borderRadius: 16,
        border: `1px solid ${c.border}`,
        boxShadow: '0 24px 60px -20px rgba(15,23,42,0.40)',
        overflow: 'hidden',
      }}>
        {successId ? (
          <div style={{ padding: '36px 28px', textAlign: 'center' }}>
            <div style={{
              width: 56, height: 56, borderRadius: 999,
              background: 'rgba(16,185,129,0.12)', color: c.success,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              marginBottom: 16,
            }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20 6L9 17l-5-5" />
              </svg>
            </div>
            <h3 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: c.text }}>Özel talebiniz IT'ye iletildi</h3>
            <p style={{ margin: '10px 0 16px', fontSize: 13.5, color: c.muted, lineHeight: 1.55 }}>
              IT ekibi talebinizi değerlendirip uygun varyantı önerecek. Süreç durumunu Taleplerim'den takip edebilirsiniz.
            </p>
            <div style={{
              display: 'inline-block', padding: '10px 16px',
              background: c.borderSoft, border: `1px dashed ${c.border}`,
              borderRadius: 10,
              fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
              fontSize: 14, fontWeight: 700, color: c.text,
              letterSpacing: '0.04em', marginBottom: 22,
            }}>{successId}</div>
            <div style={{ fontSize: 11.5, color: c.subtle, marginBottom: 22 }}>Talep numarası</div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
              <button onClick={onClose} style={{
                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',
              }}>Kapat</button>
              <button onClick={goRequests} style={{
                appearance: 'none', cursor: 'pointer',
                padding: '11px 20px', borderRadius: 10,
                background: c.primary, color: '#fff', border: 'none',
                fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
              }}>Taleplerime Git</button>
            </div>
          </div>
        ) : (
          <React.Fragment>
            {/* Başlık */}
            <div style={{
              padding: '20px 24px',
              borderBottom: `1px solid ${c.border}`,
              display: 'flex', alignItems: 'flex-start', gap: 12,
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10,
                background: c.selectedBg, color: c.selectedText,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2" />
                  <rect x="9" y="3" width="6" height="4" rx="1" />
                  <path d="M12 11v6M9 14h6" />
                </svg>
              </div>
              <div style={{ flex: 1 }}>
                <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600, color: c.text }}>Özel Talep Oluştur</h3>
                <p style={{ margin: '4px 0 0', fontSize: 12.5, color: c.muted, lineHeight: 1.5 }}>
                  Katalogda olmayan bir ürün veya hizmet için IT ekibine doğrudan talep gönderin.
                </p>
              </div>
              <button onClick={onClose} title="Kapat" style={{
                appearance: 'none', border: 'none', cursor: 'pointer',
                background: 'transparent', color: c.muted,
                padding: 4, marginRight: -4, marginTop: -4,
                display: 'inline-flex',
              }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M18 6L6 18M6 6l12 12" />
                </svg>
              </button>
            </div>

            {/* Form */}
            <div style={{ padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div>
                <label style={labelStyle}>
                  Ürün / hizmet adı <span style={{ color: c.danger }}>*</span>
                </label>
                <input
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder='Örn. 27" 4K USB-C monitör · Figma takım lisansı · grafik tablet'
                  style={inputStyle(errorFlash && !nameOk)}
                />
                <div style={hintStyle}>IT'nin neyi araştıracağını bilmesi için yeterli detay verin.</div>
              </div>

              <div>
                <label style={labelStyle}>
                  Bu ürüne neden ihtiyacınız var? <span style={{ color: c.danger }}>*</span>
                </label>
                <textarea
                  rows={4}
                  value={justification}
                  onChange={(e) => setJustification(e.target.value)}
                  placeholder="İhtiyacın iş gerekçesini açıklayın — onay süreci için gerekli."
                  style={{ ...inputStyle(errorFlash && !justOk), resize: 'vertical', minHeight: 88, fontFamily: 'inherit' }}
                />
              </div>

              <div>
                <label style={labelStyle}>Ürün / referans linki <span style={{ color: c.muted, fontWeight: 400 }}>(opsiyonel)</span></label>
                <input
                  type="url"
                  value={link}
                  onChange={(e) => setLink(e.target.value)}
                  placeholder="https://üretici.com/urun veya ekran görüntüsü linki"
                  style={inputStyle(false)}
                />
                <div style={hintStyle}>Varsa IT ekibinin doğru ürünü bulması çok daha hızlı olur.</div>
              </div>

              <div>
                <label style={labelStyle}>Tahmini bütçe <span style={{ color: c.muted, fontWeight: 400 }}>(opsiyonel)</span></label>
                <input
                  type="text"
                  value={budget}
                  onChange={(e) => setBudget(e.target.value)}
                  placeholder="Örn. 15.000 ₺ · KDV hariç"
                  style={inputStyle(false)}
                />
                <div style={hintStyle}>Bütçe verirseniz onay süresi kısalır.</div>
              </div>

              {errorFlash && !canSubmit && (
                <div style={{
                  padding: '10px 12px', borderRadius: 8,
                  background: 'rgba(239,68,68,0.08)', color: c.danger,
                  border: `1px solid ${c.danger}33`,
                  fontSize: 12.5,
                }}>
                  Lütfen yıldızlı (zorunlu) alanları doldurun.
                </div>
              )}
            </div>

            {/* Alt aksiyon */}
            <div style={{
              padding: '14px 24px',
              borderTop: `1px solid ${c.border}`,
              display: 'flex', gap: 10, justifyContent: 'flex-end',
              background: c.surface,
            }}>
              <button onClick={onClose} style={{
                appearance: 'none', cursor: 'pointer',
                padding: '10px 16px', borderRadius: 10,
                background: 'transparent', color: c.text,
                border: `1px solid ${c.border}`,
                fontSize: 13.5, fontWeight: 500, fontFamily: 'inherit',
              }}>Vazgeç</button>
              <button onClick={submit} style={{
                appearance: 'none', cursor: 'pointer',
                padding: '10px 18px', borderRadius: 10,
                background: c.primary, color: '#fff', border: 'none',
                fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', gap: 8,
                boxShadow: `0 6px 14px -4px ${c.primary}55`,
              }}>
                IT'ye Gönder
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14M13 5l7 7-7 7" />
                </svg>
              </button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

// ─────────── EMPTY STATE ───────────
function EmptyState({ c, onClear, onCustomRequest }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: '64px 24px', textAlign: 'center',
      background: c.surface,
      border: `1px dashed ${c.border}`,
      borderRadius: 16,
      color: c.text,
    }}>
      <div style={{
        width: 80, height: 80, borderRadius: 999,
        background: c.borderSoft, color: c.subtle,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 18,
      }}>
        {UIIcons.emptyBox}
      </div>
      <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Aradığınız kriterlere uygun ürün bulunamadı</h3>
      <p style={{ margin: '8px 0 20px', fontSize: 13, color: c.muted, maxWidth: 360, lineHeight: 1.55 }}>
        Aramanızı veya seçili kategoriyi değiştirmeyi deneyin. Beklediğiniz ürün katalogda yoksa
        IT ekibinden talep edebilirsiniz.
      </p>
      <div style={{ display: 'flex', gap: 10 }}>
        <button onClick={onClear} style={{
          appearance: 'none', cursor: 'pointer',
          padding: '10px 18px', borderRadius: 10,
          background: c.primary, color: '#fff',
          border: 'none', fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
        }}>Tüm ürünleri göster</button>
        <button
          onClick={onCustomRequest}
          style={{
            appearance: 'none', cursor: 'pointer',
            padding: '10px 18px', borderRadius: 10,
            background: 'transparent', color: c.text,
            border: `1px solid ${c.border}`,
            fontSize: 13.5, fontWeight: 500, fontFamily: 'inherit',
          }}>Özel talep oluştur</button>
      </div>
    </div>
  );
}

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

  const [selectedSub, setSelectedSub] = React.useState(null);
  const [selectedGroup, setSelectedGroup] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const [sort, setSort] = React.useState('popular');
  const [viewMode, setViewMode] = React.useState('grid');
  const cart = useCartSnapshot();
  const [recentlyAdded, setRecentlyAdded] = React.useState(null);
  const [customRequestOpen, setCustomRequestOpen] = React.useState(false);

  const c = catalogTheme(dark);

  // Filter
  const filtered = React.useMemo(() => {
    let xs = CATALOG_PRODUCTS;
    if (selectedGroup) xs = xs.filter((p) => p.group === selectedGroup);
    if (selectedSub) xs = xs.filter((p) => p.sub === selectedSub);
    if (search.trim()) {
      const q = search.trim().toLowerCase();
      xs = xs.filter((p) =>
        p.name.toLowerCase().includes(q) ||
        p.brand.toLowerCase().includes(q) ||
        p.sub.toLowerCase().includes(q) ||
        p.desc.toLowerCase().includes(q)
      );
    }
    // Sort
    const sorted = [...xs];
    if (sort === 'priceAsc') sorted.sort((a, b) => a.priceNet - b.priceNet);
    else if (sort === 'priceDesc') sorted.sort((a, b) => b.priceNet - a.priceNet);
    else if (sort === 'az') sorted.sort((a, b) => a.name.localeCompare(b.name, 'tr'));
    else sorted.sort((a, b) => b.requestCount - a.requestCount);
    return sorted;
  }, [selectedGroup, selectedSub, search, sort]);

  // Page title
  const pageTitle = selectedSub
    ? selectedSub
    : selectedGroup
      ? (CATALOG_CATEGORIES.find((g) => g.id === selectedGroup) || {}).name
      : 'Tüm Ürünler';
  const groupName = selectedGroup
    ? (CATALOG_CATEGORIES.find((g) => g.id === selectedGroup) || {}).name
    : null;
  const breadcrumb = selectedSub ? groupName : null;

  function addToCart(pid) {
    if (window.__cart && typeof window.__cart.add === 'function') window.__cart.add(pid);
    setRecentlyAdded(pid);
    setTimeout(() => setRecentlyAdded((cur) => (cur === pid ? null : cur)), 1500);
  }

  function openProduct(pid) {
    if (typeof window.__navigate === 'function') window.__navigate('product-detail', pid);
  }

  function clearFilters() {
    setSelectedGroup(null); setSelectedSub(null); setSearch('');
  }

  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}
        initialBellOpen={initialBellOpen}
      />

      <div style={{ display: 'flex', flex: 1, minHeight: 0 }}>
        <CatalogSidebar
          c={c}
          dark={dark}
          selectedSub={selectedSub}
          selectedGroup={selectedGroup}
          onSelectAll={() => { setSelectedGroup(null); setSelectedSub(null); }}
          onSelectGroup={(g) => { setSelectedGroup(g); setSelectedSub(null); }}
          onSelectSub={(g, s) => { setSelectedGroup(g); setSelectedSub(s); }}
        />

        <main style={{ flex: 1, minWidth: 0 }}>
          <FilterBar
            c={c}
            count={filtered.length}
            sort={sort} setSort={setSort}
            viewMode={viewMode} setViewMode={setViewMode}
            title={pageTitle}
            subtitle={breadcrumb}
          />

          <div style={{ padding: '6px 28px 32px' }}>
            {filtered.length === 0 ? (
              <EmptyState c={c} onClear={clearFilters} onCustomRequest={() => setCustomRequestOpen(true)} />
            ) : viewMode === 'grid' ? (
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
                gap: 18,
              }}>
                {filtered.map((p) => (
                  <ProductCard
                    key={p.id} p={p} c={c}
                    justAdded={recentlyAdded === p.id}
                    onAdd={() => addToCart(p.id)}
                    onOpen={() => openProduct(p.id)}
                  />
                ))}
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {filtered.map((p) => (
                  <ProductRow
                    key={p.id} p={p} c={c}
                    justAdded={recentlyAdded === p.id}
                    onAdd={() => addToCart(p.id)}
                    onOpen={() => openProduct(p.id)}
                  />
                ))}
              </div>
            )}
          </div>
        </main>
      </div>

      <CustomRequestModal open={customRequestOpen} onClose={() => setCustomRequestOpen(false)} c={c} />
    </div>
  );
}

Object.assign(window, {
  CatalogPage,
  CatalogSidebar, SidebarRow,
  FilterBar, ProductCard, ProductRow, AddToCartButton, EmptyState, CustomRequestModal,
});
