// Cart Page — Sayfa 4
// Önceden 3 ürünle dolu gerçekçi sepet. Her satırda zorunlu gerekçe.
// Sağda sticky özet kartı + onay akışı + başarı modalı.

const INITIAL_CART = [
  {
    id: 'p01', productId: 'p01', qty: 1,
    name: 'Dell Latitude 5550 Business Laptop',
    brand: 'Dell', model: 'Latitude 5550',
    imgKind: 'laptop', imgFolder: 'DellLatitude5550BusinessLaptop', priceNet: 45000, priceUnit: null,
    // Örnek doldurulmuş gerekçe — diğerleri boş (validasyon gösterimi)
    justification: 'Mevcut Dell Latitude 5400 cihazım 2019 model. Power BI ve Excel modelleri üzerinde çalışırken sürekli takılıyor ve günde 3-4 kez yeniden başlatma gerektiriyor. Daha yüksek RAM ve yeni nesil işlemciye ihtiyacım var.',
  },
  {
    id: 'p07', productId: 'p07', qty: 1,
    name: 'Logitech MX Keys S Kablosuz Klavye',
    brand: 'Logitech', model: 'MX Keys S',
    imgKind: 'keyboard', imgFolder: 'LogitechMXKeysSKablosuzKlavye', priceNet: 4200, priceUnit: null,
    justification: '',
  },
  {
    id: 'p13', productId: 'p13', qty: 1,
    name: 'Microsoft 365 Business Standard',
    brand: 'Microsoft', model: 'M365 Business Std.',
    imgKind: 'software-ms', imgFolder: 'Microsoft365BusinessStandard', priceNet: 4920, priceUnit: 'yıllık/kullanıcı',
    justification: '',
  },
];

const MANAGERS = [
  { id: 'm1', name: 'Mehmet Demir', title: 'Departman Müdürü · IT', current: true },
  { id: 'm2', name: 'Ayşe Yıldız',  title: 'Birim Şefi · IT Operasyon', current: false },
  { id: 'm3', name: 'Zeynep Şen',   title: 'IT Direktörü', current: false },
];

const APPROVAL_STEPS = [
  { id: 'mgr',   label: 'Yöneticim',       sub: 'Mehmet D.' },
  { id: 'exec',  label: 'Üst Yönetim',     sub: 'Departman bütçesi' },
  { id: 'it',    label: 'IT Onayı',        sub: 'Teknik uygunluk' },
  { id: 'buy',   label: 'Satınalma',       sub: 'Sipariş & teslim' },
];

// ─────────── icons ───────────
const CartIcons = {
  trash: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
      <path d="M10 11v6M14 11v6" />
    </svg>
  ),
  warn: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 9v4M12 17h.01" />
      <path d="M10.3 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.7 3.86a2 2 0 0 0-3.4 0z" />
    </svg>
  ),
  arrow: (
    <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>
  ),
  draft: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 20h9M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
    </svg>
  ),
};

// ─────────── Cart line item ───────────
function CartLineItem({ item, c, onQtyChange, onRemove, onJustificationChange, errorFlash }) {
  const subtotal = item.priceNet * item.qty;
  const max = 500;
  const len = item.justification.length;
  const missing = errorFlash && item.justification.trim().length === 0;

  return (
    <div style={{
      position: 'relative',
      background: c.card,
      border: `1px solid ${missing ? c.danger : c.border}`,
      borderRadius: 14,
      padding: 20,
      transition: 'border-color 160ms',
      boxShadow: missing ? `0 0 0 3px ${c.danger}22` : 'none',
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: '108px 1fr 36px', gap: 20 }}>
        {/* Image */}
        <div style={{ width: 108, height: 108, borderRadius: 10, overflow: 'hidden', border: `1px solid ${c.border}` }}>
          <ProductPlaceholder kind={item.imgKind} c={c} imgSrc={item.imgFolder ? `images/products/${item.imgFolder}/1.${item.imgExt || 'jpg'}` : null} />
        </div>

        {/* Middle */}
        <div style={{ minWidth: 0 }}>
          <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', marginBottom: 8,
          }}>{item.brand} · {item.model}</div>

          <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600, color: c.text, lineHeight: 1.35 }}>
            {item.name}
          </h3>

          {/* Price + qty + total row */}
          <div style={{
            marginTop: 14,
            display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap',
          }}>
            <div>
              <div style={{ fontSize: 11, color: c.muted, marginBottom: 2 }}>Birim fiyat</div>
              <div style={{ fontSize: 14, fontWeight: 600, color: c.text }}>
                {formatTL(item.priceNet)}
                {item.priceUnit && <span style={{ fontSize: 11.5, color: c.muted, fontWeight: 500 }}> / {item.priceUnit}</span>}
              </div>
            </div>

            <div>
              <div style={{ fontSize: 11, color: c.muted, marginBottom: 2 }}>Adet</div>
              <QuantitySelector qty={item.qty} setQty={(q) => onQtyChange(q)} c={c} />
            </div>

            <div style={{ marginLeft: 'auto', textAlign: 'right' }}>
              <div style={{ fontSize: 11, color: c.muted, marginBottom: 2 }}>Toplam</div>
              <div style={{ fontSize: 17, fontWeight: 700, color: c.text, letterSpacing: '-0.01em' }}>
                {formatTL(subtotal)}
              </div>
            </div>
          </div>

          {/* Justification (required) */}
          <div style={{ marginTop: 16 }}>
            <label style={{
              display: 'flex', alignItems: 'center', gap: 6,
              fontSize: 12.5, fontWeight: 600, color: c.text, marginBottom: 6,
            }}>
              Bu ürüne neden ihtiyacınız var?
              <span style={{ color: c.danger, fontWeight: 700 }}>*</span>
            </label>
            <textarea
              value={item.justification}
              maxLength={max}
              onChange={(e) => onJustificationChange(e.target.value)}
              placeholder="Örn: Mevcut laptopum 2018 model ve yazılım geliştirme işlerimde yetersiz kalıyor. Daha yüksek RAM'e ihtiyacım var."
              style={{
                width: '100%', boxSizing: 'border-box',
                minHeight: 78, resize: 'vertical',
                padding: '10px 12px',
                background: c.inputBg, color: c.text,
                border: `1px solid ${missing ? c.danger : c.border}`,
                borderRadius: 10,
                fontSize: 13, lineHeight: 1.55,
                fontFamily: 'inherit', outline: 'none',
                transition: 'border-color 120ms, box-shadow 120ms',
              }}
              onFocus={(e) => {
                if (!missing) {
                  e.target.style.borderColor = c.primary;
                  e.target.style.boxShadow = `0 0 0 3px ${c.primary}22`;
                }
              }}
              onBlur={(e) => {
                e.target.style.borderColor = missing ? c.danger : c.border;
                e.target.style.boxShadow = 'none';
              }}
            />
            <div style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              marginTop: 6, fontSize: 11.5,
            }}>
              <span style={{ color: missing ? c.danger : c.subtle }}>
                {missing ? 'Bu alan zorunludur — kısa bir gerekçe yazın.' : 'Onay sürecini hızlandırmak için açık ve net yazın.'}
              </span>
              <span style={{ color: len > max * 0.9 ? '#B45309' : c.subtle, fontWeight: 500 }}>
                {len} / {max}
              </span>
            </div>
          </div>
        </div>

        {/* Trash */}
        <div>
          <button
            onClick={onRemove}
            title="Sepetten çıkar"
            style={{
              appearance: 'none', cursor: 'pointer',
              width: 36, height: 36, borderRadius: 8,
              background: 'transparent', color: c.muted,
              border: `1px solid ${c.border}`,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              transition: 'all 120ms',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.color = c.danger; e.currentTarget.style.borderColor = c.danger; e.currentTarget.style.background = 'rgba(239,68,68,0.06)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.color = c.muted; e.currentTarget.style.borderColor = c.border; e.currentTarget.style.background = 'transparent'; }}>
            {CartIcons.trash}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─────────── Approval flow stepper ───────────
function ApprovalStepper({ c, currentStep = 0 }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-start', position: 'relative' }}>
        {APPROVAL_STEPS.map((s, i) => {
          const isFirst = i === 0;
          const isNext = i === currentStep;
          const dotBg = isNext ? c.primary : c.borderSoft;
          const dotColor = isNext ? '#fff' : c.muted;
          const dotBorder = isNext ? c.primary : c.border;
          return (
            <React.Fragment key={s.id}>
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', position: 'relative', zIndex: 1 }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 999,
                  background: dotBg, color: dotColor,
                  border: `2px solid ${dotBorder}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 700,
                  boxShadow: isNext ? `0 0 0 4px ${c.primary}22` : 'none',
                }}>{i + 1}</div>
                <div style={{ marginTop: 6, fontSize: 11, fontWeight: 600, color: c.text }}>{s.label}</div>
                <div style={{ marginTop: 2, fontSize: 10, color: c.muted }}>{s.sub}</div>
              </div>
              {i < APPROVAL_STEPS.length - 1 && (
                <div style={{
                  position: 'absolute', top: 13,
                  left: `calc(${(100 / APPROVAL_STEPS.length) * (i + 0.5)}% + 14px)`,
                  width: `calc(${100 / APPROVAL_STEPS.length}% - 28px)`,
                  height: 2, background: c.border, zIndex: 0,
                }} />
              )}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

// ─────────── Manager dropdown ───────────
function ManagerSelect({ c, value, onChange }) {
  const [open, setOpen] = React.useState(false);
  const selected = MANAGERS.find((m) => m.id === value) || MANAGERS[0];
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen((x) => !x)} style={{
        width: '100%', boxSizing: 'border-box',
        appearance: 'none', cursor: 'pointer',
        background: c.inputBg, color: c.text,
        border: `1px solid ${c.border}`, borderRadius: 10,
        padding: '10px 12px',
        fontSize: 13, fontWeight: 500, fontFamily: 'inherit',
        display: 'flex', alignItems: 'center', gap: 10,
        textAlign: 'left',
      }}>
        <div style={{
          width: 28, height: 28, borderRadius: 999,
          background: 'linear-gradient(135deg, #2563EB, #1D4ED8)',
          color: '#fff', fontSize: 10.5, fontWeight: 600,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>{selected.name.split(' ').map((p) => p[0]).join('').slice(0, 2)}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: c.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{selected.name}</div>
          <div style={{ fontSize: 11, color: c.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{selected.title}</div>
        </div>
        <span style={{ color: c.muted, display: 'flex' }}>{UIIcons.chevDown}</span>
      </button>
      {open && (
        <React.Fragment>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 30 }} />
          <div style={{
            position: 'absolute', top: 'calc(100% + 6px)', left: 0, right: 0, zIndex: 31,
            background: c.surface, border: `1px solid ${c.border}`, borderRadius: 12,
            boxShadow: '0 14px 30px -10px rgba(15,23,42,0.18)',
            padding: 6,
            maxHeight: 280, overflowY: 'auto',
          }}>
            {MANAGERS.map((m) => {
              const active = m.id === value;
              return (
                <button key={m.id}
                  onClick={() => { onChange(m.id); setOpen(false); }}
                  style={{
                    width: '100%', textAlign: 'left',
                    appearance: 'none', cursor: 'pointer',
                    background: active ? c.selectedBg : 'transparent',
                    color: active ? c.selectedText : c.text,
                    border: 'none', borderRadius: 8,
                    padding: 10,
                    fontFamily: 'inherit',
                    display: 'flex', alignItems: 'center', gap: 10,
                  }}>
                  <div style={{
                    width: 26, height: 26, borderRadius: 999,
                    background: 'linear-gradient(135deg, #2563EB, #1D4ED8)',
                    color: '#fff', fontSize: 10, fontWeight: 600,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                  }}>{m.name.split(' ').map((p) => p[0]).join('').slice(0, 2)}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600 }}>
                      {m.name}
                      {m.current && (
                        <span style={{
                          marginLeft: 6, padding: '2px 6px',
                          background: c.chipBg, color: c.muted,
                          fontSize: 9.5, fontWeight: 600, letterSpacing: '0.06em',
                          borderRadius: 4, textTransform: 'uppercase',
                        }}>varsayılan</span>
                      )}
                    </div>
                    <div style={{ fontSize: 11, color: active ? c.selectedText : c.muted }}>{m.title}</div>
                  </div>
                  {active && <span style={{ color: c.primary, display: 'flex' }}>{UIIcons.check}</span>}
                </button>
              );
            })}
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

// ─────────── Summary card (right side) ───────────
function CartSummary({ c, items, errorFlash, managerId, setManagerId, generalNote, setGeneralNote, onSubmit, onDraft }) {
  const subtotal = items.reduce((s, x) => s + x.priceNet * x.qty, 0);
  const vat = Math.round(subtotal * 0.20);
  const total = subtotal + vat;
  const itemCount = items.reduce((s, x) => s + x.qty, 0);
  const missingCount = items.filter((x) => !x.justification.trim()).length;

  return (
    <aside style={{
      position: 'sticky', top: 84,
      width: 360, flexShrink: 0,
    }}>
      <div style={{
        background: c.card,
        border: `1px solid ${c.border}`,
        borderRadius: 14,
        padding: 22,
      }}>
        <h2 style={{ margin: 0, fontSize: 16, fontWeight: 600, color: c.text }}>Sipariş Özeti</h2>

        {/* Totals */}
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 9 }}>
          <SummaryRow c={c} label={`${itemCount} ürün ara toplamı`} value={formatTL(subtotal)} />
          <SummaryRow c={c} label="KDV (%20)" value={formatTL(vat)} />
        </div>

        <div style={{ borderTop: `1px solid ${c.border}`, margin: '14px 0' }} />

        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: c.text }}>Genel Toplam</span>
          <span style={{ fontSize: 22, fontWeight: 700, color: c.text, letterSpacing: '-0.015em' }}>
            {formatTL(total)}
          </span>
        </div>
        <div style={{ fontSize: 11.5, color: c.subtle, marginTop: 2, textAlign: 'right' }}>KDV dahil</div>

        {/* Approval flow */}
        <div style={{ marginTop: 22, paddingTop: 18, borderTop: `1px solid ${c.borderSoft}` }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: c.text, marginBottom: 14 }}>Onay Süreci</div>
          <ApprovalStepper c={c} currentStep={0} />
        </div>

        {/* Manager */}
        <div style={{ marginTop: 22, paddingTop: 18, borderTop: `1px solid ${c.borderSoft}` }}>
          <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: c.text, marginBottom: 8 }}>
            Onaya gönderilecek yönetici
          </label>
          <ManagerSelect c={c} value={managerId} onChange={setManagerId} />
        </div>

        {/* General note */}
        <div style={{ marginTop: 16 }}>
          <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: c.text, marginBottom: 6 }}>
            Talep için genel not <span style={{ color: c.muted, fontWeight: 400 }}>(opsiyonel)</span>
          </label>
          <textarea
            value={generalNote}
            onChange={(e) => setGeneralNote(e.target.value)}
            placeholder="Örn: Q2 yeni başlayan ekip arkadaşı için."
            maxLength={300}
            style={{
              width: '100%', boxSizing: 'border-box',
              minHeight: 58, resize: 'vertical',
              padding: '9px 12px',
              background: c.inputBg, color: c.text,
              border: `1px solid ${c.border}`, borderRadius: 10,
              fontSize: 12.5, lineHeight: 1.55,
              fontFamily: 'inherit', outline: 'none',
            }}
          />
        </div>

        {/* Error banner */}
        {errorFlash && missingCount > 0 && (
          <div style={{
            marginTop: 14,
            display: 'flex', alignItems: 'flex-start', gap: 10,
            padding: '10px 12px',
            background: 'rgba(239,68,68,0.10)',
            border: `1px solid ${c.danger}33`,
            borderRadius: 10,
            color: c.danger, fontSize: 12, lineHeight: 1.5, fontWeight: 500,
          }}>
            <span style={{ display: 'flex', marginTop: 1 }}>{CartIcons.warn}</span>
            <span>
              <strong>{missingCount} üründe gerekçe boş.</strong> Devam etmek için her ürüne neden ihtiyacınız olduğunu yazın.
            </span>
          </div>
        )}

        {/* Buttons */}
        <button onClick={onSubmit} style={{
          marginTop: 16, width: '100%', boxSizing: 'border-box',
          appearance: 'none', cursor: 'pointer',
          padding: '13px 18px', borderRadius: 10,
          background: c.primary, color: '#fff', border: 'none',
          fontSize: 14, fontWeight: 600, fontFamily: 'inherit',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          boxShadow: `0 6px 14px -4px ${c.primary}55`,
        }}>
          Onaya Gönder {CartIcons.arrow}
        </button>
        <button onClick={onDraft} style={{
          marginTop: 8, 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, fontWeight: 500, fontFamily: 'inherit',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          {CartIcons.draft} Taslak olarak kaydet
        </button>
      </div>

      {/* Helper note below summary */}
      <div style={{
        marginTop: 14, padding: 14,
        background: c.selectedBg, color: c.selectedText,
        border: `1px solid ${c.primary}22`,
        borderRadius: 12,
        fontSize: 12, lineHeight: 1.55,
      }}>
        Onaylar tamamlandıktan sonra siparişiniz IT Satınalma ekibine düşer.
        Süreç boyunca her aşamada e-posta bildirimi alırsınız.
      </div>
    </aside>
  );
}

function SummaryRow({ c, label, value }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 13 }}>
      <span style={{ color: c.muted }}>{label}</span>
      <span style={{ color: c.text, fontWeight: 500 }}>{value}</span>
    </div>
  );
}

// ─────────── Success modal ───────────
function SuccessModal({ open, requestId, onClose, c }) {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 50,
      background: 'rgba(2,6,23,0.55)',
      backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
      animation: 'fadeIn 160ms ease-out',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: 'min(480px, 100%)',
        background: c.card, color: c.text,
        borderRadius: 16, padding: '32px 32px 28px',
        boxShadow: '0 24px 60px -12px rgba(2,6,23,0.45)',
        border: `1px solid ${c.border}`,
        animation: 'popIn 200ms cubic-bezier(.2,.9,.3,1.2)',
        textAlign: 'center',
      }}>
        <div style={{
          width: 72, height: 72, borderRadius: 999,
          background: 'rgba(16,185,129,0.12)', color: c.success,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 18,
        }}>
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M20 6L9 17l-5-5" />
          </svg>
        </div>
        <h2 style={{ margin: 0, fontSize: 20, fontWeight: 600 }}>Talebiniz başarıyla gönderildi</h2>
        <p style={{ margin: '10px auto 18px', maxWidth: 380, fontSize: 13.5, color: c.muted, lineHeight: 1.6 }}>
          Talep numaranız aşağıdadır. Yöneticinizin onayı bekleniyor — sonraki aşamada e-posta ile bilgilendirileceksiniz.
        </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: 15, fontWeight: 700, color: c.text,
          letterSpacing: '0.04em',
          marginBottom: 6,
        }}>
          {requestId}
        </div>
        <div style={{ fontSize: 11.5, color: c.subtle, marginBottom: 24 }}>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={() => {
              onClose();
              if (typeof window.__navigate === 'function') window.__navigate('requests');
            }}
            style={{
              appearance: 'none', cursor: 'pointer',
              padding: '11px 20px', borderRadius: 10,
              background: c.primary, color: '#fff', border: 'none',
              fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
              display: 'inline-flex', alignItems: 'center', gap: 8,
            }}>
            Taleplerime Git {CartIcons.arrow}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─────────── Empty cart ───────────
function EmptyCart({ c, onExplore }) {
  return (
    <div style={{
      textAlign: 'center', padding: '80px 24px',
      background: c.surface, border: `1px dashed ${c.border}`, borderRadius: 16,
    }}>
      <div style={{
        width: 84, height: 84, borderRadius: 999,
        background: c.borderSoft, color: c.subtle,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 18,
      }}>
        <svg width="38" height="38" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" 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>
      </div>
      <h3 style={{ margin: 0, fontSize: 17, fontWeight: 600, color: c.text }}>Sepetiniz boş</h3>
      <p style={{ margin: '8px 0 22px', fontSize: 13, color: c.muted, maxWidth: 360, marginLeft: 'auto', marginRight: 'auto', lineHeight: 1.55 }}>
        Henüz sepete bir ürün eklemediniz. Katalogdan ihtiyaç duyduğunuz ürünleri ekleyerek talep oluşturmaya başlayabilirsiniz.
      </p>
      <button onClick={onExplore} style={{
        appearance: 'none', cursor: 'pointer',
        padding: '11px 22px', borderRadius: 10,
        background: c.primary, color: '#fff', border: 'none',
        fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
      }}>Ürünleri Keşfet</button>
    </div>
  );
}

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

  // Paylaşılan sepetten oku — App seviyesinde tutulan items.
  const items = useCartSnapshot();
  const [managerId, setManagerId] = React.useState('m1');
  const [generalNote, setGeneralNote] = React.useState('');
  const [errorFlash, setErrorFlash] = React.useState(false);
  const [success, setSuccess] = React.useState(null); // null | requestId
  const [headerSearch, setHeaderSearch] = React.useState('');

  const c = catalogTheme(dark);

  function updateItem(id, patch) {
    if (!window.__cart) return;
    if ('qty' in patch && typeof window.__cart.setQty === 'function') {
      window.__cart.setQty(id, patch.qty);
    }
    if ('justification' in patch && typeof window.__cart.setJustification === 'function') {
      window.__cart.setJustification(id, patch.justification);
    }
  }
  function removeItem(id) {
    if (window.__cart && typeof window.__cart.remove === 'function') window.__cart.remove(id);
  }

  function submit() {
    const missing = items.filter((x) => !x.justification.trim());
    if (missing.length > 0) {
      setErrorFlash(true);
      return;
    }
    setErrorFlash(false);
    // Paylaşılan taleplere "Onay Bekliyor" olarak ekle
    let newId;
    if (window.__requests && typeof window.__requests.addPending === 'function') {
      newId = window.__requests.addPending(items);
    } else {
      const n = String(Math.floor(120 + Math.random() * 100)).padStart(5, '0');
      newId = `#IT-2026-${n}`;
    }
    setSuccess(newId);
  }

  function closeSuccess() {
    setSuccess(null);
    // Demo: talep gönderildikten sonra sepeti temizle
    if (window.__cart && typeof window.__cart.clear === 'function') window.__cart.clear();
  }

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

      {/* Title strip */}
      <div style={{ padding: '24px 32px 4px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: c.muted }}>
          <a href="#" style={{ color: 'inherit', textDecoration: 'none' }}>Tüm Ürünler</a>
          <span style={{ color: c.subtle }}>/</span>
          <span style={{ color: c.text, fontWeight: 500 }}>Sepetim</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginTop: 8 }}>
          <h1 style={{ margin: 0, fontSize: 26, fontWeight: 600, letterSpacing: '-0.015em', color: c.text }}>
            Sepetim
          </h1>
          <span style={{ fontSize: 14, color: c.muted, fontWeight: 500 }}>
            {items.length} ürün · {items.reduce((s, x) => s + x.qty, 0)} adet
          </span>
        </div>
      </div>

      {/* Main 2-column */}
      <div style={{
        padding: '20px 32px 40px',
        display: 'flex', gap: 28, alignItems: 'flex-start',
      }}>
        {/* LEFT — items */}
        <div style={{ flex: 1, minWidth: 0 }}>
          {items.length === 0 ? (
            <EmptyCart c={c} onExplore={() => { if (typeof window.__navigate === 'function') window.__navigate('catalog'); }} />
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {items.map((it) => (
                <CartLineItem
                  key={it.id} item={it} c={c} errorFlash={errorFlash}
                  onQtyChange={(q) => updateItem(it.id, { qty: q })}
                  onRemove={() => removeItem(it.id)}
                  onJustificationChange={(v) => updateItem(it.id, { justification: v })}
                />
              ))}
            </div>
          )}
        </div>

        {/* RIGHT — summary */}
        {items.length > 0 && (
          <CartSummary
            c={c} items={items}
            errorFlash={errorFlash}
            managerId={managerId} setManagerId={setManagerId}
            generalNote={generalNote} setGeneralNote={setGeneralNote}
            onSubmit={submit}
            onDraft={() => {
              if (items.length === 0) {
                alert('Taslak olarak kaydetmek için sepette en az 1 ürün olmalı.');
                return;
              }
              let newId = null;
              if (window.__requests && typeof window.__requests.addDraft === 'function') {
                newId = window.__requests.addDraft(items);
              }
              alert(`Talebiniz taslak olarak kaydedildi.\n\nTalep No: ${newId || '(demo)'} · ${items.length} ürün\n\nTaleplerim → Taslak sekmesinden tekrar açıp düzenleyebilirsiniz.`);
              if (window.__cart && typeof window.__cart.clear === 'function') window.__cart.clear();
              if (typeof window.__navigate === 'function') window.__navigate('requests');
            }}
          />
        )}
      </div>

      <SuccessModal open={!!success} requestId={success} onClose={closeSuccess} c={c} />
    </div>
  );
}

Object.assign(window, {
  CartPage, INITIAL_CART, MANAGERS, APPROVAL_STEPS,
  CartLineItem, ApprovalStepper, ManagerSelect, CartSummary, SuccessModal, EmptyCart,
});
