// App.jsx — Çalışan prototip: Login → sol menülü uygulama kabuğu.
// Sayfalar arası geçiş useState ile yönetilir (gerçek URL routing yok).
// Her sayfa kendi içinde dark/tema state'ini tutuyor; biz sadece etrafına
// kalıcı bir sol navigasyon menüsü sarıyoruz ve header linklerini bağlıyoruz.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light"
}/*EDITMODE-END*/;

// ─────────── Menü ikonları ───────────
const NavIcons = {
  catalog: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="3" width="7" height="7" rx="1.5" /><rect x="14" y="3" width="7" height="7" rx="1.5" />
      <rect x="3" y="14" width="7" height="7" rx="1.5" /><rect x="14" y="14" width="7" height="7" rx="1.5" />
    </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>
  ),
  requests: (
    <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="M9 12h6M9 16h4" />
    </svg>
  ),
  notifications: (
    <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>
  ),
  profile: (
    <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="8" r="4" /><path d="M4 21a8 8 0 0 1 16 0" />
    </svg>
  ),
  logout: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /><path d="M16 17l5-5-5-5M21 12H9" />
    </svg>
  ),
};

const NAV_ITEMS = [
  { id: 'catalog', label: 'Katalog', icon: 'catalog' },
  { id: 'cart', label: 'Sepetim', icon: 'cart', badgeKey: 'cart' },
  { id: 'requests', label: 'Taleplerim', icon: 'requests' },
  { id: 'notifications', label: 'Bildirimler', icon: 'notifications', badgeKey: 'notif' },
  { id: 'profile', label: 'Profilim', icon: 'profile' },
];

// ─────────── Sol navigasyon menüsü ───────────
function AppSidebar({ current, onNavigate, dark, collapsed, onToggleCollapse, badges }) {
  const c = dark
    ? { bg: '#0B1220', border: '#1F2A3D', text: '#F1F5F9', muted: '#94A3B8',
        activeBg: 'rgba(37,99,235,0.16)', activeText: '#93C5FD', hover: 'rgba(255,255,255,0.04)',
        logoBg: 'rgba(255,255,255,0.06)', logoBorder: 'rgba(255,255,255,0.18)' }
    : { bg: '#FFFFFF', border: '#E2E8F0', text: '#0F172A', muted: '#64748B',
        activeBg: '#EFF4FF', activeText: '#1D4ED8', hover: '#F1F5F9',
        logoBg: '#EEF2F6', logoBorder: '#CBD5E1' };

  const W = collapsed ? 72 : 240;

  return (
    <div style={{
      width: W, flexShrink: 0,
      height: '100%',
      background: c.bg,
      borderRight: `1px solid ${c.border}`,
      display: 'flex', flexDirection: 'column',
      transition: 'width 180ms ease',
      position: 'sticky', top: 0,
    }}>
      {/* Logo + ürün adı */}
      <div style={{
        height: 64, flexShrink: 0,
        display: 'flex', alignItems: 'center', gap: 12,
        padding: collapsed ? '0 18px' : '0 20px',
        borderBottom: `1px solid ${c.border}`,
      }}>
        <img
          src="images/logo/mark-color.svg"
          alt="IT Talep Sistemi"
          width="36" height="36"
          style={{ borderRadius: 8, flexShrink: 0, display: 'block' }}
        />
        {!collapsed && (
          <div style={{ fontSize: 14, fontWeight: 600, color: c.text, letterSpacing: '-0.005em', whiteSpace: 'nowrap' }}>
            IT Talep Sistemi
          </div>
        )}
      </div>

      {/* Menü maddeleri */}
      <nav style={{ flex: 1, padding: '12px 12px', display: 'flex', flexDirection: 'column', gap: 4 }}>
        {NAV_ITEMS.map((item) => {
          const active = current === item.id;
          const badge = item.badgeKey ? badges[item.badgeKey] : 0;
          return (
            <button
              key={item.id}
              onClick={() => onNavigate(item.id)}
              title={collapsed ? item.label : undefined}
              style={{
                appearance: 'none', border: 'none', cursor: 'pointer',
                width: '100%', textAlign: 'left',
                display: 'flex', alignItems: 'center', gap: 12,
                padding: collapsed ? '11px 0' : '11px 12px',
                justifyContent: collapsed ? 'center' : 'flex-start',
                borderRadius: 10,
                background: active ? c.activeBg : 'transparent',
                color: active ? c.activeText : c.text,
                fontSize: 13.5, fontWeight: active ? 600 : 500,
                fontFamily: 'inherit',
                position: 'relative',
                transition: 'background 120ms, color 120ms',
              }}
              onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = c.hover; }}
              onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
              <span style={{ display: 'flex', flexShrink: 0 }}>{NavIcons[item.icon]}</span>
              {!collapsed && <span style={{ flex: 1, whiteSpace: 'nowrap' }}>{item.label}</span>}
              {badge > 0 && (
                <span style={{
                  position: collapsed ? 'absolute' : 'static',
                  top: collapsed ? 6 : undefined, right: collapsed ? 14 : undefined,
                  minWidth: 18, height: 18, padding: '0 5px', boxSizing: 'border-box',
                  background: '#2563EB', color: '#fff',
                  fontSize: 10.5, fontWeight: 700, lineHeight: '18px',
                  borderRadius: 999, textAlign: 'center',
                }}>{badge}</span>
              )}
            </button>
          );
        })}
      </nav>

      {/* Alt: collapse + çıkış */}
      <div style={{ padding: '12px 12px', borderTop: `1px solid ${c.border}`, display: 'flex', flexDirection: 'column', gap: 4 }}>
        <button
          onClick={() => onNavigate('__logout')}
          title={collapsed ? 'Çıkış Yap' : undefined}
          style={{
            appearance: 'none', border: 'none', cursor: 'pointer',
            width: '100%',
            display: 'flex', alignItems: 'center', gap: 12,
            justifyContent: collapsed ? 'center' : 'flex-start',
            padding: collapsed ? '11px 0' : '11px 12px',
            borderRadius: 10, background: 'transparent', color: c.muted,
            fontSize: 13.5, fontWeight: 500, fontFamily: 'inherit',
            transition: 'background 120ms',
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = c.hover}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
          <span style={{ display: 'flex', flexShrink: 0 }}>{NavIcons.logout}</span>
          {!collapsed && <span>Çıkış Yap</span>}
        </button>
        <button
          onClick={onToggleCollapse}
          title={collapsed ? 'Menüyü genişlet' : 'Menüyü daralt'}
          style={{
            appearance: 'none', border: 'none', cursor: 'pointer',
            width: '100%',
            display: 'flex', alignItems: 'center', gap: 12,
            justifyContent: collapsed ? 'center' : 'flex-start',
            padding: collapsed ? '11px 0' : '11px 12px',
            borderRadius: 10, background: 'transparent', color: c.muted,
            fontSize: 13.5, fontWeight: 500, fontFamily: 'inherit',
            transition: 'background 120ms',
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = c.hover}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
          <span style={{ display: 'flex', flexShrink: 0, transform: collapsed ? 'rotate(180deg)' : 'none', transition: 'transform 180ms' }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
              <path d="M15 18l-6-6 6-6" />
            </svg>
          </span>
          {!collapsed && <span>Daralt</span>}
        </button>
      </div>
    </div>
  );
}

// ─────────── Ana uygulama ───────────
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const dark = t.theme === 'dark';

  // 'login' → giriş ekranı; sonrası uygulama kabuğu
  const [page, setPage] = React.useState('login');
  const [selectedProductId, setSelectedProductId] = React.useState(null);
  const [collapsed, setCollapsed] = React.useState(false);

  // ── Paylaşılan sepet state'i ──
  // Demo verisiyle başlar (INITIAL_CART) — kullanıcı ekledikçe büyür.
  const [cartItems, setCartItems] = React.useState(() =>
    Array.isArray(window.INITIAL_CART) ? window.INITIAL_CART.slice() : []
  );

  // ── Paylaşılan bildirim state'i ──
  // Demo NOTIFICATIONS ile başlar, okundu işaretlemeleri burada kalır.
  const [notifItems, setNotifItems] = React.useState(() =>
    Array.isArray(window.NOTIFICATIONS) ? window.NOTIFICATIONS.map((n) => ({ ...n })) : []
  );

  // ── Paylaşılan talepler state'i ──
  // Demo REQUESTS ile başlar; "Taslak kaydet" ve "Onaya gönder" yeni kayıt ekler.
  const [requestItems, setRequestItems] = React.useState(() =>
    Array.isArray(window.REQUESTS)
      ? window.REQUESTS.map((r) => ({ ...r, items: (r.items || []).map((it) => ({ ...it })) }))
      : []
  );

  // Sayfalar global navigasyon fonksiyonunu çağırabilsin (header linkleri için)
  // İkinci argüman opsiyonel: ürün detay sayfasına geçerken ürün id'sini taşır.
  React.useEffect(() => {
    window.__navigate = (p, productId) => {
      if (p === '__logout') { setPage('login'); return; }
      if (p === 'product-detail' && productId) setSelectedProductId(productId);
      setPage(p);
    };
    return () => { delete window.__navigate; };
  }, []);

  // Paylaşılan sepet — okuma/yazma window üzerinden, değişimde olay yayınla
  React.useEffect(() => {
    window.__cart = {
      items: cartItems,
      add: (productId, qty = 1) => {
        const cp = (window.CATALOG_PRODUCTS || []).find((p) => p.id === productId);
        if (!cp) return;
        setCartItems((prev) => {
          const existing = prev.find((it) => it.productId === productId);
          if (existing) {
            return prev.map((it) => it.productId === productId ? { ...it, qty: it.qty + qty } : it);
          }
          return [...prev, {
            id: productId, productId, qty,
            name: cp.name, brand: cp.brand, model: cp.model,
            imgKind: cp.imgKind, imgFolder: cp.imgFolder, imgExt: cp.imgExt,
            priceNet: cp.priceNet, priceUnit: cp.priceUnit || null,
            justification: '',
          }];
        });
      },
      remove: (id) => setCartItems((prev) => prev.filter((it) => it.id !== id)),
      setQty: (id, qty) => setCartItems((prev) => prev.map((it) => it.id === id ? { ...it, qty } : it)),
      setJustification: (id, text) => setCartItems((prev) => prev.map((it) => it.id === id ? { ...it, justification: text } : it)),
      clear: () => setCartItems([]),
    };
    window.dispatchEvent(new CustomEvent('cartchange'));
  }, [cartItems]);

  // Paylaşılan bildirimler — okundu işaretlemeleri uygulama ömrü boyunca korunur
  React.useEffect(() => {
    window.__notif = {
      items: notifItems,
      markAll: () => setNotifItems((prev) => prev.map((n) => ({ ...n, read: true }))),
      markOne: (id) => setNotifItems((prev) => prev.map((n) => n.id === id ? { ...n, read: true } : n)),
    };
    window.dispatchEvent(new CustomEvent('notifchange'));
  }, [notifItems]);

  // Paylaşılan talepler — yeni taslak ve onaya gönderilen kayıtlar buraya eklenir
  React.useEffect(() => {
    const trMonths = ['Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara'];
    const fmtDate = (d) => `${d.getDate()} ${trMonths[d.getMonth()]} ${d.getFullYear()}`;
    const fmtDateTime = (d) => `${fmtDate(d)}, ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
    const nextId = () => `#IT-2026-${String(Math.floor(140 + Math.random() * 800)).padStart(5, '0')}`;
    const mapItems = (cartItems) => cartItems.map((it) => ({
      id: it.productId || it.id, name: it.name, brand: it.brand, model: it.model,
      imgKind: it.imgKind, imgFolder: it.imgFolder, imgExt: it.imgExt,
      qty: it.qty, priceNet: it.priceNet, priceUnit: it.priceUnit,
      justification: it.justification || '',
    }));
    const subtotal = (cartItems) => cartItems.reduce((s, x) => s + (x.priceNet || 0) * (x.qty || 1), 0);

    window.__requests = {
      items: requestItems,
      addDraft: (cartItems) => {
        const id = nextId();
        const req = {
          id, date: fmtDate(new Date()), submittedAt: null,
          status: 'draft', netSubtotal: subtotal(cartItems),
          items: mapItems(cartItems),
          currentStep: -1,
        };
        setRequestItems((prev) => [req, ...prev]);
        return id;
      },
      addPending: (cartItems, providedId) => {
        const id = providedId || nextId();
        const now = new Date();
        const req = {
          id, date: fmtDate(now), submittedAt: fmtDateTime(now),
          status: 'pending', netSubtotal: subtotal(cartItems),
          items: mapItems(cartItems).map((x) => ({ ...x, state: 'pending' })),
          currentStep: 0,
          timeline: [
            { kind: 'submitted', actor: 'Ayşe Kaya',    role: 'Talebi oluşturan',     time: fmtDateTime(now) },
            { kind: 'pending',   actor: 'Mehmet Demir', role: 'Yöneticim',            time: null },
            { kind: 'queued',    actor: 'Üst Yönetim',  role: 'Departman Direktörü',  time: null },
            { kind: 'queued',    actor: 'IT Onayı',     role: 'Teknik uygunluk',      time: null },
            { kind: 'queued',    actor: 'Satınalma',    role: 'Sipariş & teslim',     time: null },
          ],
        };
        setRequestItems((prev) => [req, ...prev]);
        return id;
      },
      addCustom: ({ name, justification, link, budget }) => {
        const id = `#IT-2026-SP-${String(Math.floor(1 + Math.random() * 900)).padStart(3, '0')}`;
        const now = new Date();
        const budgetNum = parseInt((budget || '').replace(/[^\d]/g, ''), 10) || 0;
        const req = {
          id, date: fmtDate(now), submittedAt: fmtDateTime(now),
          status: 'pending', kind: 'custom',
          netSubtotal: budgetNum,
          items: [{
            name, imgKind: 'service',
            qty: 1, priceNet: budgetNum,
            justification: justification || '',
            link: link || null,
            budget: budget || null,
            state: 'pending',
          }],
          currentStep: 0,
          timeline: [
            { kind: 'submitted', actor: 'Ayşe Kaya', role: 'Talebi oluşturan', time: fmtDateTime(now) },
            { kind: 'pending',   actor: 'Ahmet Kara', role: 'IT Onayı',
              time: null,
              note: 'Katalogda olmayan ürün için özel talep — IT ekibi değerlendirip uygun varyantı önerecek.' },
            { kind: 'queued',    actor: 'Mehmet Demir', role: 'Yöneticim',           time: null },
            { kind: 'queued',    actor: 'Üst Yönetim',  role: 'Departman Direktörü', time: null },
            { kind: 'queued',    actor: 'Satınalma',    role: 'Sipariş & teslim',    time: null },
          ],
        };
        setRequestItems((prev) => [req, ...prev]);
        return id;
      },
      remove: (id) => setRequestItems((prev) => prev.filter((r) => r.id !== id)),
    };
    window.dispatchEvent(new CustomEvent('requestschange'));
  }, [requestItems]);

  function navigate(p, productId) {
    if (p === '__logout') { setPage('login'); return; }
    if (p === 'product-detail' && productId) setSelectedProductId(productId);
    setPage(p);
  }

  // Sol menü rozetleri (sepet adedi, okunmamış bildirim) — paylaşılan state'den
  const cartCount = cartItems.length;
  const notifCount = notifItems.filter((n) => !n.read).length;
  const badges = { cart: cartCount, notif: notifCount };

  // ── LOGIN EKRANI ──
  if (page === 'login') {
    return (
      <React.Fragment>
        <div style={{ position: 'relative', width: '100vw', height: '100vh', overflow: 'hidden' }}>
          {/* Giriş yapınca katalog sayfasına geçen bir LoginV2 sarmalayıcısı */}
          <LoginWithRedirect dark={dark} onSuccess={() => setPage('catalog')} />
        </div>
        <TweaksPanel title="Tweaks">
          <TweakSection label="Tema">
            <TweakRadio
              label="Görünüm"
              value={t.theme}
              options={[{ value: 'light', label: 'Açık' }, { value: 'dark', label: 'Koyu' }]}
              onChange={(v) => setTweak('theme', v)}
            />
          </TweakSection>
        </TweaksPanel>
      </React.Fragment>
    );
  }

  // ── UYGULAMA KABUĞU (sol menü + içerik) ──
  const shellBg = dark ? '#0B1220' : '#F6F8FB';

  return (
    <React.Fragment>
      <div style={{
        width: '100vw', height: '100vh',
        display: 'flex',
        background: shellBg,
        fontFamily: 'Inter, system-ui, sans-serif',
        overflow: 'hidden',
      }}>
        <AppSidebar
          current={page}
          onNavigate={navigate}
          dark={dark}
          collapsed={collapsed}
          onToggleCollapse={() => setCollapsed((x) => !x)}
          badges={badges}
        />

        {/* İçerik alanı — her sayfa kendi header'ı + scroll'u ile */}
        <div style={{ flex: 1, height: '100%', overflowY: 'auto', overflowX: 'hidden' }}>
          <PageSwitch page={page} dark={dark} productId={selectedProductId} />
        </div>
      </div>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Tema">
          <TweakRadio
            label="Görünüm"
            value={t.theme}
            options={[{ value: 'light', label: 'Açık' }, { value: 'dark', label: 'Koyu' }]}
            onChange={(v) => setTweak('theme', v)}
          />
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}

// Aktif sayfaya göre ilgili bileşeni render et.
// key={page+dark} → tema değişince sayfa initialDark'ı yeniden okusun.
function PageSwitch({ page, dark, productId }) {
  switch (page) {
    case 'catalog':
      return <CatalogPage key={'catalog' + dark} initialDark={dark} />;
    case 'product-detail':
      return <ProductDetailPage key={'pd-' + productId + '-' + dark} initialDark={dark} productId={productId} />;
    case 'cart':
      return <CartPage key={'cart' + dark} initialDark={dark} />;
    case 'requests':
      return <RequestsPage key={'requests' + dark} initialDark={dark} />;
    case 'notifications':
      return <NotificationsPage key={'notif' + dark} initialDark={dark} />;
    case 'profile':
      return <ProfilePage key={'profile' + dark} initialDark={dark} />;
    default:
      return <CatalogPage key={'catalog' + dark} initialDark={dark} />;
  }
}

// Login başarıya ulaşınca otomatik katalog sayfasına yönlendiren sarmalayıcı.
// LoginV2'nin kendi success state'ini izler ve kısa bir gecikmeyle geçiş yapar.
function LoginWithRedirect({ dark, onSuccess }) {
  const triggeredRef = React.useRef(false);

  React.useEffect(() => {
    // LoginV2 success'e geçince DOM'da "Yönlendiriliyorsunuz" metni belirir.
    // Basit ve sağlam yöntem: success animasyonu sonrası otomatik geçiş için
    // login formunun submit'ini gözlemlemek yerine periyodik kontrol.
    const iv = setInterval(() => {
      if (triggeredRef.current) return;
      const root = document.getElementById('root');
      if (root && /Yönlendiriliyorsunuz|başarılı şekilde giriş/i.test(root.innerText)) {
        triggeredRef.current = true;
        clearInterval(iv);
        setTimeout(onSuccess, 900);
      }
    }, 250);
    return () => clearInterval(iv);
  }, [onSuccess]);

  return <LoginV2 initialDark={dark} />;
}

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