// Sipariş & Sevkiyat Operasyon Paneli
// React 18 + Tailwind CSS (CDN) — tek dosya

const { useState, useEffect, useRef } = React;

// ── API ──────────────────────────────────────────────────────────
async function apiFetch(path, opts = {}) {
  const res = await fetch('/api' + path, {
    ...opts,
    headers: { 'Content-Type': 'application/json', ...(opts.headers || {}) },
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    throw new Error(body.error || res.statusText);
  }
  return res.json();
}
const api = {
  get:    (p)    => apiFetch(p),
  post:   (p, d) => apiFetch(p, { method: 'POST',   body: JSON.stringify(d) }),
  patch:  (p, d) => apiFetch(p, { method: 'PATCH',  body: JSON.stringify(d) }),
  delete: (p)    => apiFetch(p, { method: 'DELETE' }),
};

// ── ADMIN ŞİFRE KONTROL MODALİ ───────────────────────────────────
const ADMIN_SIFRE = '260959';

function AdminSifrModal({ baslik, aciklama, onConfirm, onCancel, loading }) {
  const [sifre, setSifre] = React.useState('');
  const [hata,  setHata]  = React.useState('');
  const inputRef = useRef(null);

  useEffect(() => { setTimeout(() => inputRef.current?.focus(), 60); }, []);

  function handleSubmit() {
    if (sifre !== ADMIN_SIFRE) {
      setHata('Yanlış şifre');
      setSifre('');
      inputRef.current?.focus();
      return;
    }
    setHata('');
    onConfirm();
  }

  return (
    <div className="fixed inset-0 z-[300] flex items-center justify-center bg-black/60">
      <div className="bg-white rounded-2xl shadow-2xl p-6 w-80 mx-4">
        <div className="flex items-center gap-3 mb-3">
          <div className="w-9 h-9 rounded-full bg-red-100 flex items-center justify-center shrink-0">
            <span className="text-red-600 text-base">🗑</span>
          </div>
          <div>
            <h3 className="font-bold text-gray-900 text-sm">{baslik}</h3>
            <p className="text-xs text-gray-500 mt-0.5">{aciklama}</p>
          </div>
        </div>
        {hata && (
          <div className="mb-3 px-3 py-2 bg-red-50 border border-red-200 text-red-600 rounded-lg text-xs font-medium">
            {hata}
          </div>
        )}
        <input
          ref={inputRef}
          type="password"
          value={sifre}
          onChange={e => { setSifre(e.target.value); setHata(''); }}
          onKeyDown={e => e.key === 'Enter' && handleSubmit()}
          placeholder="Admin şifresi"
          autoComplete="off"
          className="w-full border rounded-xl px-3 py-2.5 text-sm mb-4 focus:outline-none focus:ring-2 focus:ring-red-400"
        />
        <div className="flex gap-2">
          <button onClick={onCancel} disabled={loading}
            className="flex-1 border border-gray-200 text-gray-600 hover:bg-gray-50 py-2.5 rounded-xl text-sm font-semibold transition-colors">
            İptal
          </button>
          <button onClick={handleSubmit} disabled={loading}
            className="flex-1 bg-red-600 hover:bg-red-700 disabled:bg-red-300 text-white py-2.5 rounded-xl text-sm font-semibold transition-colors">
            {loading ? 'Siliniyor…' : 'Kalıcı Sil'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── SABITLER ─────────────────────────────────────────────────────
const DURUM_RENK = {
  beklemede:     'bg-yellow-100 text-yellow-800',
  onaylandi:     'bg-blue-100   text-blue-800',
  hazirlaniyor:  'bg-purple-100 text-purple-800',
  teslim_edildi: 'bg-green-100  text-green-800',
  iptal:         'bg-red-100    text-red-800',
};
const DURUM_LABEL = {
  beklemede:     'Beklemede',
  onaylandi:     'Onaylandı',
  hazirlaniyor:  'Hazırlanıyor',
  teslim_edildi: 'Teslim Edildi',
  iptal:         'İptal',
};
const MENU = [
  { key: 'dashboard',       label: 'Dashboard'         },
  { key: 'siparisler',      label: 'Siparişler'        },
  { key: 'yeni-siparis',    label: 'Yeni Sipariş'      },
  { key: 'musteriler',      label: 'Müşteriler'        },
  { key: 'urunler',         label: 'Ürünler'           },
  { key: 'yarin-sevkiyat',  label: 'Yarınki Sevkiyat'  },
];

// ── UTILS ────────────────────────────────────────────────────────
function fmtDate(d) {
  if (!d) return '—';
  return new Date(d).toLocaleDateString('tr-TR');
}

function siparislerExcelIndir(siparisler, dosyaAdi) {
  const basliklar = ['Sipariş No', 'Teslimat Tarihi', 'Müşteri', 'Cari Kod', 'Bölge', 'Satışçı', 'Ürün', 'Miktar', 'Birim', 'Durum', 'Notlar'];
  const rows = [basliklar];
  siparisler.forEach(s => {
    const kalemler = s.kalemler || [];
    const base = [
      s.siparis_no,
      fmtDate(s.teslimat_tarihi),
      s.musteri_ad || '',
      s.cari_kod || '',
      s.siparis_bolge_kodu || '',
      s.satisci_ad || '',
    ];
    if (kalemler.length === 0) {
      rows.push([...base, '', '', '', DURUM_LABEL[s.durum] || s.durum, s.notlar || '']);
    } else {
      kalemler.forEach((k, ki) => {
        rows.push([
          ...base,
          k.urun_ad || '',
          k.miktar || '',
          k.birim || '',
          ki === 0 ? (DURUM_LABEL[s.durum] || s.durum) : '',
          ki === 0 ? (s.notlar || '') : '',
        ]);
      });
    }
  });
  const ws = XLSX.utils.aoa_to_sheet(rows);
  ws['!cols'] = [16, 14, 26, 12, 10, 15, 28, 8, 8, 14, 22].map(w => ({ wch: w }));
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Siparişler');
  XLSX.writeFile(wb, dosyaAdi + '.xlsx');
}
function useDebounce(val, ms = 300) {
  const [deb, setDeb] = useState(val);
  useEffect(() => {
    const t = setTimeout(() => setDeb(val), ms);
    return () => clearTimeout(t);
  }, [val, ms]);
  return deb;
}

// ── GİRİŞ EKRANI ─────────────────────────────────────────────────
function LoginView({ onLogin }) {
  const [kullanici, setKullanici] = useState('');
  const [sifre,     setSifre]     = useState('');
  const [hata,      setHata]      = useState('');
  const [yukleniyor,setYukleniyor]= useState(false);

  async function handleLogin(e) {
    e.preventDefault();
    if (!kullanici || !sifre) { setHata('Kullanıcı adı ve şifre gerekli'); return; }
    setYukleniyor(true); setHata('');
    try {
      const res = await api.post('/login', { kullanici_adi: kullanici, sifre });
      onLogin(res.kullanici);
    } catch {
      setHata('Kullanıcı adı veya şifre hatalı');
    } finally {
      setYukleniyor(false);
    }
  }

  return (
    <div className="min-h-screen bg-gray-100 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-xl p-8 w-full max-w-sm">
        <div className="text-center mb-7">
          <div className="text-4xl mb-3">📦</div>
          <h1 className="text-xl font-bold text-gray-900">Sipariş Paneli</h1>
          <p className="text-sm text-gray-400 mt-1">Seval Gıda Operasyon</p>
        </div>
        {hata && (
          <div className="mb-4 px-4 py-3 bg-red-50 border border-red-200 text-red-600 rounded-xl text-sm text-center font-medium">
            {hata}
          </div>
        )}
        <form onSubmit={handleLogin} className="space-y-3">
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1.5">Kullanıcı Adı</label>
            <input
              type="text" value={kullanici}
              onChange={e => { setKullanici(e.target.value); setHata(''); }}
              placeholder="kullanici-adi" autoFocus autoComplete="username"
              className="w-full border rounded-xl px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1.5">Şifre</label>
            <input
              type="password" value={sifre}
              onChange={e => { setSifre(e.target.value); setHata(''); }}
              placeholder="••••••••" autoComplete="current-password"
              className="w-full border rounded-xl px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <button type="submit" disabled={yukleniyor}
            className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-blue-300 text-white py-3 rounded-xl font-semibold text-sm transition-colors mt-2">
            {yukleniyor ? 'Giriş yapılıyor...' : 'Giriş Yap'}
          </button>
        </form>
      </div>
    </div>
  );
}

// ── KÜÇÜK BİLEŞENLER ─────────────────────────────────────────────
function Toast({ toast }) {
  if (!toast) return null;
  return (
    <div className={`fixed bottom-5 right-5 z-[999] px-5 py-3 rounded-xl shadow-2xl text-white text-sm font-medium
      ${toast.type === 'error' ? 'bg-red-500' : 'bg-green-600'}`}>
      {toast.message}
    </div>
  );
}

function DurumBadge({ durum }) {
  return (
    <span className={`inline-block px-2.5 py-0.5 rounded-full text-xs font-semibold whitespace-nowrap
      ${DURUM_RENK[durum] || 'bg-gray-100 text-gray-600'}`}>
      {DURUM_LABEL[durum] || durum}
    </span>
  );
}

function Spinner() {
  return <div className="text-center text-gray-400 text-sm py-12">Yükleniyor...</div>;
}

function ErrMsg({ msg }) {
  if (!msg) return null;
  return (
    <div className="mb-4 px-4 py-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm">
      {msg}
    </div>
  );
}

// ── SIDEBAR ──────────────────────────────────────────────────────
function Sidebar({ view, navigate, kullanici, onLogout }) {
  return (
    <div className="h-full flex flex-col select-none">
      <div className="px-5 py-5 border-b border-gray-700">
        <div className="text-white font-bold text-lg leading-tight">Sipariş</div>
        <div className="text-gray-400 text-xs mt-0.5">Operasyon Paneli</div>
      </div>
      <nav className="flex-1 py-3 px-2">
        {MENU.map(item => (
          <button
            key={item.key}
            onClick={() => navigate(item.key)}
            className={`w-full text-left px-3 py-2.5 rounded-lg mb-0.5 text-sm font-medium transition-colors
              ${view === item.key
                ? 'bg-blue-600 text-white'
                : 'text-gray-300 hover:bg-gray-700 hover:text-white'}`}
          >
            {item.label}
          </button>
        ))}
      </nav>
      <div className="px-3 py-4 border-t border-gray-700">
        <div className="text-xs text-gray-500 px-2 mb-2 truncate">👤 {kullanici}</div>
        <button onClick={onLogout}
          className="w-full text-left px-3 py-2 rounded-lg text-sm text-gray-400 hover:bg-gray-700 hover:text-white transition-colors">
          Çıkış Yap
        </button>
      </div>
    </div>
  );
}

// ── DASHBOARD ────────────────────────────────────────────────────
function DashboardView({ navigate }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get('/dashboard').then(setData).catch(console.error).finally(() => setLoading(false));
  }, []);

  if (loading) return <Spinner />;
  if (!data) return <div className="text-red-500 text-sm py-8 text-center">Veriler alınamadı.</div>;

  const cards = [
    { label: 'Bugün Sipariş',    value: data.bugunSiparis,   color: 'bg-blue-50   border-blue-200',   text: 'text-blue-700'   },
    { label: 'Yarın Sevkiyat',   value: data.yarin_sevkiyat, color: 'bg-green-50  border-green-200',  text: 'text-green-700',  action: () => navigate('yarin-sevkiyat') },
    { label: 'Onay Bekleyen',    value: data.onay_bekleyen,  color: 'bg-yellow-50 border-yellow-200', text: 'text-yellow-700', action: () => navigate('siparisler') },
    { label: 'Bu Hafta Toplam',  value: data.bu_hafta,       color: 'bg-purple-50 border-purple-200', text: 'text-purple-700'  },
  ];

  return (
    <div>
      <h1 className="text-xl font-bold text-gray-800 mb-5">Dashboard</h1>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        {cards.map(c => (
          <div key={c.label} onClick={c.action}
            className={`${c.color} border rounded-2xl p-4 ${c.action ? 'cursor-pointer hover:shadow-md' : ''} transition-shadow`}>
            <div className={`text-4xl font-bold ${c.text}`}>{c.value}</div>
            <div className="text-sm text-gray-500 mt-1">{c.label}</div>
          </div>
        ))}
      </div>

      {data.bolge_ozet && data.bolge_ozet.length > 0 && (
        <div>
          <h2 className="text-base font-semibold text-gray-700 mb-3">Bölge Özeti</h2>
          <div className="bg-white rounded-2xl border overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-b">
                <tr>
                  <th className="text-left px-5 py-3 text-gray-500 font-medium">Bölge</th>
                  <th className="text-right px-5 py-3 text-gray-500 font-medium">Sipariş</th>
                  <th className="text-right px-5 py-3 text-gray-500 font-medium">Kalem</th>
                </tr>
              </thead>
              <tbody>
                {data.bolge_ozet.map((row, i) => (
                  <tr key={i} className="border-t hover:bg-gray-50">
                    <td className="px-5 py-3 font-medium">{row.bolge || '—'}</td>
                    <td className="px-5 py-3 text-right tabular-nums">{row.siparis_sayisi}</td>
                    <td className="px-5 py-3 text-right tabular-nums">{row.toplam_kalem || 0}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

// ── SİPARİŞ DETAY PANELİ ─────────────────────────────────────────
function SiparisDetayPanel({ siparisId, onClose, showToast, onDurumChange, onSilindi }) {
  const [siparis,          setSiparis]          = useState(null);
  const [loading,          setLoading]          = useState(true);
  const [showDeleteModal,  setShowDeleteModal]  = useState(false);
  const [siliniyor,        setSiliniyor]        = useState(false);

  useEffect(() => {
    if (!siparisId) return;
    setLoading(true);
    setSiparis(null);
    api.get(`/siparisler/${siparisId}`)
      .then(setSiparis)
      .catch(e => showToast(e.message, 'error'))
      .finally(() => setLoading(false));
  }, [siparisId]);

  function handleDurum(newDurum) {
    api.patch(`/siparisler/${siparisId}/durum`, { durum: newDurum })
      .then(() => {
        setSiparis(prev => ({ ...prev, durum: newDurum }));
        onDurumChange && onDurumChange(siparisId, newDurum);
        showToast(`Durum "${DURUM_LABEL[newDurum]}" olarak güncellendi`);
      })
      .catch(e => showToast(e.message, 'error'));
  }

  async function handleSil() {
    setSiliniyor(true);
    try {
      const res = await api.delete(`/siparisler/${siparisId}`);
      showToast(`${res.siparis_no} silindi`);
      setShowDeleteModal(false);
      onSilindi && onSilindi(siparisId);
      onClose();
    } catch (e) {
      showToast(e.message, 'error');
      setSiliniyor(false);
    }
  }

  const btnler = {
    beklemede:    [{ label: 'Onayla',       durum: 'onaylandi',     cls: 'bg-blue-600 hover:bg-blue-700 text-white'   },
                   { label: 'İptal Et',     durum: 'iptal',         cls: 'bg-red-500 hover:bg-red-600 text-white'    }],
    onaylandi:    [{ label: 'Hazırlanıyor', durum: 'hazirlaniyor',  cls: 'bg-purple-600 hover:bg-purple-700 text-white' },
                   { label: 'İptal Et',     durum: 'iptal',         cls: 'bg-red-500 hover:bg-red-600 text-white'    }],
    hazirlaniyor: [{ label: 'Teslim Edildi',durum: 'teslim_edildi', cls: 'bg-green-600 hover:bg-green-700 text-white' },
                   { label: 'İptal Et',     durum: 'iptal',         cls: 'bg-red-500 hover:bg-red-600 text-white'    }],
  };

  return (
    <div className="fixed inset-0 z-[100]">
      <div className="absolute inset-0 bg-black/40" onClick={onClose} />
      <div className="absolute right-0 top-0 h-full w-full max-w-lg bg-white shadow-2xl overflow-y-auto flex flex-col">

        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b sticky top-0 bg-white z-10">
          <h2 className="font-bold text-gray-800">Sipariş Detayı</h2>
          <button onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 text-gray-400 hover:text-gray-700 text-xl font-bold">
            ×
          </button>
        </div>

        {loading ? <Spinner /> : !siparis ? null : (
          <div className="p-5 space-y-5 flex-1">

            {/* Başlık */}
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="font-mono text-xs text-gray-400">{siparis.siparis_no}</div>
                <div className="font-bold text-gray-900 text-lg mt-0.5">{siparis.musteri_ad}</div>
                <div className="text-sm text-gray-500">{siparis.cari_kod} · {siparis.telefon || '—'}</div>
              </div>
              <DurumBadge durum={siparis.durum} />
            </div>

            {/* Meta */}
            <div className="grid grid-cols-2 gap-3">
              {[
                ['Sipariş Tarihi',  fmtDate(siparis.siparis_tarihi)],
                ['Teslimat Tarihi', fmtDate(siparis.teslimat_tarihi)],
                siparis.siparis_bolge_kodu && ['Sipariş Bölgesi', siparis.siparis_bolge_kodu],
                siparis.satisci_ad         && ['Satışçı',         siparis.satisci_ad],
                siparis.adres              && ['Teslimat Adresi', `${siparis.adres}${siparis.ilce ? ', ' + siparis.ilce : ''}`],
              ].filter(Boolean).map(([label, val]) => (
                <div key={label} className="bg-gray-50 rounded-xl px-4 py-3">
                  <div className="text-xs text-gray-400 mb-0.5">{label}</div>
                  <div className="text-sm font-medium text-gray-800 break-words">{val}</div>
                </div>
              ))}
            </div>

            {/* Kalemler */}
            {siparis.kalemler && siparis.kalemler.length > 0 && (
              <div>
                <div className="text-sm font-semibold text-gray-700 mb-2">Kalemler</div>
                <div className="rounded-xl overflow-hidden border">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50 border-b">
                      <tr>
                        <th className="text-left px-4 py-2.5 text-gray-500 font-medium text-xs">Ürün</th>
                        <th className="text-right px-4 py-2.5 text-gray-500 font-medium text-xs">Miktar</th>
                        <th className="text-right px-4 py-2.5 text-gray-500 font-medium text-xs">Birim</th>
                      </tr>
                    </thead>
                    <tbody>
                      {siparis.kalemler.map((k, i) => (
                        <tr key={i} className="border-t">
                          <td className="px-4 py-2.5">{k.urun_ad}</td>
                          <td className="px-4 py-2.5 text-right font-semibold tabular-nums">{k.miktar}</td>
                          <td className="px-4 py-2.5 text-right text-gray-500">{k.birim || k.urun_birim}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* Notlar */}
            {siparis.notlar && (
              <div>
                <div className="text-sm font-semibold text-gray-700 mb-1">Notlar</div>
                <div className="bg-amber-50 border border-amber-100 rounded-xl px-4 py-3 text-sm text-gray-700">
                  {siparis.notlar}
                </div>
              </div>
            )}

            {/* Chatwoot */}
            {siparis.chatwoot_link && (
              <a href={siparis.chatwoot_link} target="_blank" rel="noreferrer"
                className="inline-flex items-center gap-1.5 text-sm text-blue-600 hover:text-blue-800 underline">
                Chatwoot Konuşmasını Aç ↗
              </a>
            )}

            {/* Durum butonları */}
            {btnler[siparis.durum] && (
              <div className="border-t pt-4">
                <div className="text-xs font-semibold text-gray-500 mb-2 uppercase tracking-wide">Durumu Güncelle</div>
                <div className="flex gap-2">
                  {btnler[siparis.durum].map(b => (
                    <button key={b.durum} onClick={() => handleDurum(b.durum)}
                      className={`flex-1 py-2 rounded-xl text-sm font-semibold transition-colors ${b.cls}`}>
                      {b.label}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* Silme */}
            <div className="border-t pt-4 pb-1">
              <button onClick={() => setShowDeleteModal(true)}
                className="w-full py-2 rounded-xl text-sm font-semibold text-red-500 border border-red-200 hover:bg-red-50 transition-colors">
                Siparişi Sil
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Admin şifre modali */}
      {showDeleteModal && (
        <AdminSifrModal
          baslik="Siparişi kalıcı olarak sil"
          aciklama={`${siparis?.siparis_no} silinecek. Bu işlem geri alınamaz.`}
          onConfirm={handleSil}
          onCancel={() => setShowDeleteModal(false)}
          loading={siliniyor}
        />
      )}
    </div>
  );
}

// ── SİPARİŞLER LİSTESİ ───────────────────────────────────────────
function SiparislerView({ selectedId, setSelectedId, showToast }) {
  const [siparisler, setSiparisler] = useState([]);
  const [loading, setLoading]       = useState(true);
  const [excelYukleniyor, setExcelYukleniyor] = useState(false);
  const [filters, setFilters]       = useState({ durum: '', tarih_baslangic: '', tarih_bitis: '', bolge: '' });

  function buildQ() {
    const p = new URLSearchParams();
    Object.entries(filters).forEach(([k, v]) => v && p.set(k, v));
    return p.toString();
  }

  function load() {
    setLoading(true);
    const q = buildQ();
    api.get('/siparisler' + (q ? '?' + q : ''))
      .then(setSiparisler)
      .catch(e => showToast(e.message, 'error'))
      .finally(() => setLoading(false));
  }

  async function excelIndir() {
    setExcelYukleniyor(true);
    try {
      const q = buildQ();
      const data = await api.get('/siparisler/export' + (q ? '?' + q : ''));
      const tarih = new Date().toISOString().slice(0, 10);
      siparislerExcelIndir(data, 'Siparisler-' + tarih);
    } catch (e) {
      showToast(e.message, 'error');
    } finally {
      setExcelYukleniyor(false);
    }
  }

  useEffect(() => { load(); }, [filters]);

  function onDurumChange(id, newDurum) {
    setSiparisler(prev => prev.map(s => s.id === id ? { ...s, durum: newDurum } : s));
  }

  function onSilindi(id) {
    setSiparisler(prev => prev.filter(s => s.id !== id));
    setSelectedId(null);
  }

  const setF = (k, v) => setFilters(f => ({ ...f, [k]: v }));

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h1 className="text-xl font-bold text-gray-800">Siparişler</h1>
        <button onClick={excelIndir} disabled={excelYukleniyor}
          className="bg-green-600 hover:bg-green-700 disabled:bg-green-300 text-white px-4 py-2 rounded-xl text-sm font-semibold flex items-center gap-2">
          {excelYukleniyor ? 'Hazırlanıyor…' : '⬇ Excel İndir'}
        </button>
      </div>

      {/* Filtreler */}
      <div className="bg-white rounded-2xl border p-4 mb-4">
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
          <select value={filters.durum} onChange={e => setF('durum', e.target.value)}
            className="border rounded-lg px-3 py-2 text-sm bg-white">
            <option value="">Tüm Durumlar</option>
            {Object.entries(DURUM_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
          </select>
          <input type="date" value={filters.tarih_baslangic}
            onChange={e => setF('tarih_baslangic', e.target.value)}
            className="border rounded-lg px-3 py-2 text-sm" title="Teslimat tarihi başlangıcı" />
          <input type="date" value={filters.tarih_bitis}
            onChange={e => setF('tarih_bitis', e.target.value)}
            className="border rounded-lg px-3 py-2 text-sm" title="Teslimat tarihi bitişi" />
          <input type="text" value={filters.bolge} placeholder="Bölge kodu..."
            onChange={e => setF('bolge', e.target.value)}
            className="border rounded-lg px-3 py-2 text-sm" />
        </div>
      </div>

      {/* Tablo */}
      <div className="bg-white rounded-2xl border overflow-hidden">
        {loading ? <Spinner /> : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-b">
                <tr>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Sipariş No</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Müşteri</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Teslimat</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Durum</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium hidden md:table-cell">Bölge</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium hidden lg:table-cell">Satışçı</th>
                  <th className="text-right px-4 py-3 text-gray-500 font-medium">Kalem</th>
                </tr>
              </thead>
              <tbody>
                {siparisler.length === 0 ? (
                  <tr><td colSpan={7} className="text-center text-gray-400 py-10">Sipariş bulunamadı</td></tr>
                ) : siparisler.map(s => (
                  <tr key={s.id} onClick={() => setSelectedId(s.id)}
                    className={`border-t cursor-pointer hover:bg-blue-50 transition-colors
                      ${selectedId === s.id ? 'bg-blue-50' : ''}`}>
                    <td className="px-4 py-3 font-mono text-xs text-gray-400">{s.siparis_no}</td>
                    <td className="px-4 py-3">
                      <div className="font-medium">{s.musteri_ad}</div>
                      <div className="text-xs text-gray-400">{s.cari_kod}</div>
                    </td>
                    <td className="px-4 py-3 whitespace-nowrap">{fmtDate(s.teslimat_tarihi)}</td>
                    <td className="px-4 py-3"><DurumBadge durum={s.durum} /></td>
                    <td className="px-4 py-3 text-gray-500 hidden md:table-cell">{s.siparis_bolge_kodu || '—'}</td>
                    <td className="px-4 py-3 text-gray-500 hidden lg:table-cell">{s.satisci_ad || '—'}</td>
                    <td className="px-4 py-3 text-right tabular-nums">{s.kalem_sayisi || 0}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {selectedId && (
        <SiparisDetayPanel
          siparisId={selectedId}
          onClose={() => setSelectedId(null)}
          showToast={showToast}
          onDurumChange={onDurumChange}
          onSilindi={onSilindi}
        />
      )}
    </div>
  );
}

// ── YENİ SİPARİŞ ─────────────────────────────────────────────────
function YeniSiparisView({ navigate, showToast }) {
  const [musterQ,       setMusterQ]       = useState('');
  const [musterSonuc,   setMusterSonuc]   = useState([]);
  const [seciliMusteri, setSeciliMusteri] = useState(null);

  const [urunQ,         setUrunQ]         = useState('');
  const [urunSonuc,     setUrunSonuc]     = useState([]);
  const [seciliUrun,    setSeciliUrun]    = useState(null);
  const [miktar,        setMiktar]        = useState('');
  const [birim,         setBirim]         = useState('');

  const [kalemler,        setKalemler]        = useState([]);
  const [teslimatTarihi,  setTeslimatTarihi]  = useState('');
  const [bolgeKodu,       setBolgeKodu]       = useState('');
  const [notlar,          setNotlar]          = useState('');
  const [chatwootLink,    setChatwootLink]    = useState('');
  const [hata,            setHata]            = useState('');
  const [kaydediyor,      setKaydediyor]      = useState(false);

  const miktarRef = useRef(null);
  const debMuster = useDebounce(musterQ, 280);
  const debUrun   = useDebounce(urunQ,   250);

  useEffect(() => {
    if (!debMuster || debMuster.length < 2) { setMusterSonuc([]); return; }
    api.get('/musteriler?q=' + encodeURIComponent(debMuster)).then(setMusterSonuc).catch(() => {});
  }, [debMuster]);

  useEffect(() => {
    if (!debUrun || debUrun.length < 1) { setUrunSonuc([]); return; }
    api.get('/urunler?q=' + encodeURIComponent(debUrun)).then(setUrunSonuc).catch(() => {});
  }, [debUrun]);

  function selectMusteri(m) {
    setSeciliMusteri(m);
    setMusterQ('');
    setMusterSonuc([]);
    if (m.siparis_bolge_kodu) setBolgeKodu(m.siparis_bolge_kodu);
  }

  function selectUrun(u) {
    setSeciliUrun(u);
    setUrunQ('');
    setUrunSonuc([]);
    setBirim(u.birim || 'adet');
    setTimeout(() => miktarRef.current && miktarRef.current.focus(), 60);
  }

  function ekleKalem() {
    if (!seciliUrun) return;
    const m = parseFloat(miktar);
    if (!m || m <= 0) { setHata('Geçerli bir miktar girin'); return; }
    setKalemler(prev => [...prev, {
      urun_id: seciliUrun.id,
      urun_ad: seciliUrun.ad,
      miktar: m,
      birim: birim || seciliUrun.birim || 'adet',
    }]);
    setSeciliUrun(null);
    setMiktar('');
    setBirim('');
    setHata('');
  }

  function handleTarih(val) {
    const gun = new Date(val).getDay();
    if (gun === 0) { setHata('Pazar günü teslimat seçilemez'); setTeslimatTarihi(''); return; }
    setHata('');
    setTeslimatTarihi(val);
  }

  async function handleKaydet() {
    if (!seciliMusteri)      { setHata('Müşteri seçilmedi'); return; }
    if (kalemler.length < 1) { setHata('En az bir ürün kalemi ekleyin'); return; }
    if (!teslimatTarihi)     { setHata('Teslimat tarihi seçilmedi'); return; }

    setHata('');
    setKaydediyor(true);
    try {
      const siparis = await api.post('/siparisler', {
        musteri_id:        seciliMusteri.id,
        kalemler:          kalemler.map(k => ({ urun_id: k.urun_id, miktar: k.miktar, birim: k.birim })),
        teslimat_tarihi:   teslimatTarihi,
        notlar:            notlar || null,
        chatwoot_link:     chatwootLink || null,
        siparis_bolge_kodu: bolgeKodu || null,
      });
      try { if (navigator.clipboard) await navigator.clipboard.writeText(siparis.siparis_no); } catch {}
      showToast(`✅ Sipariş kaydedildi: ${siparis.siparis_no}`);
      navigate('siparisler', { siparisId: siparis.id });
    } catch (e) {
      setHata(e.message);
    } finally {
      setKaydediyor(false);
    }
  }

  const today = new Date().toISOString().slice(0, 10);

  return (
    <div className="max-w-2xl">
      <h1 className="text-xl font-bold text-gray-800 mb-5">Yeni Sipariş</h1>
      <ErrMsg msg={hata} />

      <div className="bg-white rounded-2xl border p-5 space-y-5">

        {/* ── Müşteri ── */}
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-1.5">Müşteri *</label>
          {seciliMusteri ? (
            <div className="flex items-center justify-between bg-blue-50 border border-blue-200 rounded-xl px-4 py-3">
              <div>
                <div className="font-semibold text-gray-800">{seciliMusteri.ad}</div>
                <div className="text-xs text-gray-500 mt-0.5">
                  {seciliMusteri.cari_kod}
                  {seciliMusteri.telefon ? ` · ${seciliMusteri.telefon}` : ''}
                  {seciliMusteri.siparis_bolge_kodu ? ` · ${seciliMusteri.siparis_bolge_kodu}` : ''}
                </div>
              </div>
              <button onClick={() => setSeciliMusteri(null)}
                className="ml-3 text-gray-400 hover:text-red-500 text-xl font-bold w-8 h-8 flex items-center justify-center rounded-full hover:bg-red-50">
                ×
              </button>
            </div>
          ) : (
            <div className="relative">
              <input type="text" value={musterQ} onChange={e => setMusterQ(e.target.value)}
                onBlur={() => setTimeout(() => setMusterSonuc([]), 200)}
                placeholder="Telefon, cari kod veya ad ile ara..."
                className="w-full border rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
              {musterSonuc.length > 0 && (
                <ul className="absolute z-20 top-full left-0 right-0 bg-white border rounded-xl shadow-xl mt-1 max-h-52 overflow-y-auto">
                  {musterSonuc.map(m => (
                    <li key={m.id} onMouseDown={() => selectMusteri(m)}
                      className="px-4 py-2.5 hover:bg-blue-50 cursor-pointer border-b last:border-0">
                      <div className="font-medium text-sm">{m.ad}</div>
                      <div className="text-xs text-gray-400">{m.cari_kod} · {m.telefon}</div>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          )}
        </div>

        {/* ── Ürün Ekle ── */}
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-1.5">Ürün Ekle</label>
          <div className="relative">
            <input type="text" value={urunQ} onChange={e => setUrunQ(e.target.value)}
              onBlur={() => setTimeout(() => setUrunSonuc([]), 200)}
              placeholder="Ürün adı veya kodu ile ara..."
              className="w-full border rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
            {urunSonuc.length > 0 && (
              <ul className="absolute z-20 top-full left-0 right-0 bg-white border rounded-xl shadow-xl mt-1 max-h-44 overflow-y-auto">
                {urunSonuc.map(u => (
                  <li key={u.id} onMouseDown={() => selectUrun(u)}
                    className="px-4 py-2.5 hover:bg-blue-50 cursor-pointer border-b last:border-0">
                    <div className="font-medium text-sm">{u.ad}</div>
                    <div className="text-xs text-gray-400">{u.kod} · {u.birim}</div>
                  </li>
                ))}
              </ul>
            )}
          </div>

          {seciliUrun && (
            <div className="mt-2 flex items-center gap-2 bg-gray-50 border rounded-xl px-3 py-2">
              <span className="text-sm font-medium text-gray-700 flex-1 truncate">{seciliUrun.ad}</span>
              <input ref={miktarRef} type="number" value={miktar} onChange={e => setMiktar(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && ekleKalem()}
                placeholder="Miktar" min="0" step="any"
                className="border rounded-lg px-2.5 py-1.5 text-sm w-24 focus:outline-none focus:ring-2 focus:ring-blue-500" />
              <input type="text" value={birim} onChange={e => setBirim(e.target.value)}
                placeholder="Birim"
                className="border rounded-lg px-2.5 py-1.5 text-sm w-20 focus:outline-none focus:ring-2 focus:ring-blue-500" />
              <button onClick={ekleKalem}
                className="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1.5 rounded-lg text-sm font-semibold whitespace-nowrap">
                Ekle
              </button>
              <button onClick={() => { setSeciliUrun(null); setMiktar(''); setBirim(''); }}
                className="text-gray-400 hover:text-red-500 font-bold text-lg">×</button>
            </div>
          )}

          {kalemler.length > 0 && (
            <div className="mt-3 rounded-xl overflow-hidden border">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 border-b">
                  <tr>
                    <th className="text-left px-3 py-2 text-gray-500 font-medium text-xs">Ürün</th>
                    <th className="text-right px-3 py-2 text-gray-500 font-medium text-xs">Miktar</th>
                    <th className="text-right px-3 py-2 text-gray-500 font-medium text-xs">Birim</th>
                    <th className="w-8"></th>
                  </tr>
                </thead>
                <tbody>
                  {kalemler.map((k, i) => (
                    <tr key={i} className="border-t">
                      <td className="px-3 py-2">{k.urun_ad}</td>
                      <td className="px-3 py-2 text-right font-semibold tabular-nums">{k.miktar}</td>
                      <td className="px-3 py-2 text-right text-gray-500">{k.birim}</td>
                      <td className="px-3 py-2 text-center">
                        <button onClick={() => setKalemler(prev => prev.filter((_, j) => j !== i))}
                          className="text-red-400 hover:text-red-600 font-bold text-base w-5 h-5 flex items-center justify-center mx-auto">×</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* ── Tarih + Bölge ── */}
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1.5">Teslimat Tarihi *</label>
            <input type="date" value={teslimatTarihi} min={today}
              onChange={e => handleTarih(e.target.value)}
              className="w-full border rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1.5">Bölge Kodu</label>
            <input type="text" value={bolgeKodu} onChange={e => setBolgeKodu(e.target.value)}
              placeholder="örn. BZ"
              className="w-full border rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
        </div>

        {/* ── Notlar ── */}
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-1.5">Notlar</label>
          <textarea value={notlar} onChange={e => setNotlar(e.target.value)} rows={2}
            placeholder="Opsiyonel not..."
            className="w-full border rounded-xl px-3 py-2.5 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500" />
        </div>

        {/* ── Chatwoot ── */}
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-1.5">Chatwoot Linki</label>
          <input type="url" value={chatwootLink} onChange={e => setChatwootLink(e.target.value)}
            placeholder="https://..."
            className="w-full border rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
        </div>

        <button onClick={handleKaydet} disabled={kaydediyor}
          className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-blue-300 text-white py-3 rounded-xl font-semibold text-sm transition-colors">
          {kaydediyor ? 'Kaydediliyor...' : 'Siparişi Kaydet'}
        </button>
      </div>
    </div>
  );
}

// ── MÜŞTERİ KAYIT / DÜZENLE FORMU ───────────────────────────────
function MusteriFormPanel({ musteri, onClose, onSaved, showToast }) {
  const isEdit = !!musteri;
  const [form, setForm] = React.useState({
    ad:                  musteri?.ad                  || '',
    cari_kod:            musteri?.cari_kod            || '',
    telefon:             musteri?.telefon             || '',
    siparis_bolge_kodu:  musteri?.siparis_bolge_kodu  || '',
    cari_adres:          musteri?.cari_adres          || '',
    cari_ilce:           musteri?.cari_ilce           || '',
    cari_il:             musteri?.cari_il             || '',
    chatwoot_contact_id: musteri?.chatwoot_contact_id || '',
    notlar:              musteri?.notlar              || '',
  });
  const [ekTelefonlar, setEkTelefonlar] = React.useState(
    (musteri?.telefonlar || [])
      .filter(t => !t.birincil)
      .map(t => ({ telefon: t.telefon, turu: t.turu || 'cep' }))
  );
  const [kaydediyor, setKaydediyor] = React.useState(false);
  const [hata, setHata] = React.useState('');

  const setF = (k, v) => setForm(f => ({ ...f, [k]: v }));

  function ekTelEkle() {
    setEkTelefonlar(prev => [...prev, { telefon: '', turu: 'cep' }]);
  }
  function ekTelSil(i) {
    setEkTelefonlar(prev => prev.filter((_, j) => j !== i));
  }
  function ekTelGuncelle(i, k, v) {
    setEkTelefonlar(prev => prev.map((t, j) => j === i ? { ...t, [k]: v } : t));
  }

  async function handleKaydet() {
    if (!form.ad.trim())       { setHata('Firma / müşteri adı zorunludur'); return; }
    if (!form.cari_kod.trim()) { setHata('Cari kod zorunludur'); return; }
    setHata(''); setKaydediyor(true);
    try {
      const payload = { ...form, ekTelefonlar: ekTelefonlar.filter(t => t.telefon.trim()) };
      const saved = isEdit
        ? await api.patch(`/musteriler/${musteri.id}`, payload)
        : await api.post('/musteriler', payload);
      showToast(isEdit ? 'Müşteri güncellendi' : 'Müşteri kaydedildi');
      onSaved(saved);
    } catch (e) {
      setHata(e.message);
    } finally {
      setKaydediyor(false);
    }
  }

  return (
    <div className="fixed inset-0 z-[100]">
      <div className="absolute inset-0 bg-black/40" onClick={onClose} />
      <div className="absolute right-0 top-0 h-full w-full max-w-lg bg-white shadow-2xl overflow-y-auto flex flex-col">

        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b sticky top-0 bg-white z-10">
          <h2 className="font-bold text-gray-800">{isEdit ? 'Müşteri Düzenle' : 'Yeni Müşteri Kaydı'}</h2>
          <button onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 text-gray-400 hover:text-gray-700 text-xl font-bold">×</button>
        </div>

        <div className="p-5 space-y-5 flex-1">
          {hata && <ErrMsg msg={hata} />}

          {/* Ad + Cari Kod + Bölge */}
          <div className="space-y-3">
            <div>
              <label className="block text-xs font-semibold text-gray-500 mb-1.5">Firma / Müşteri Adı *</label>
              <input type="text" value={form.ad} onChange={e => setF('ad', e.target.value)}
                placeholder="Ahmet Restoran" autoFocus
                className="w-full border rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-semibold text-gray-500 mb-1.5">Cari Kod *</label>
                <input type="text" value={form.cari_kod}
                  onChange={e => setF('cari_kod', e.target.value.toUpperCase())}
                  placeholder="AHM001"
                  className="w-full border rounded-xl px-3 py-2.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500" />
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-500 mb-1.5">Sipariş Bölge Kodu</label>
                <input type="text" value={form.siparis_bolge_kodu}
                  onChange={e => setF('siparis_bolge_kodu', e.target.value.toUpperCase())}
                  placeholder="BZ"
                  className="w-full border rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
              </div>
            </div>
          </div>

          {/* Birincil telefon */}
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1.5">Birincil Telefon</label>
            <input type="tel" value={form.telefon} onChange={e => setF('telefon', e.target.value)}
              placeholder="05321234567"
              className="w-full border rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
            <p className="text-xs text-gray-400 mt-1">WhatsApp / n8n bu numarayı kullanır.</p>
          </div>

          {/* Ek telefonlar */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="text-xs font-semibold text-gray-500">Ek Telefon Numaraları</label>
              <button onClick={ekTelEkle}
                className="text-xs text-blue-600 hover:text-blue-800 font-semibold px-2 py-0.5 rounded hover:bg-blue-50">
                + Ekle
              </button>
            </div>
            {ekTelefonlar.length === 0 ? (
              <p className="text-xs text-gray-400 italic">Ek telefon yok</p>
            ) : ekTelefonlar.map((t, i) => (
              <div key={i} className="flex items-center gap-2 mb-2">
                <input type="tel" value={t.telefon}
                  onChange={e => ekTelGuncelle(i, 'telefon', e.target.value)}
                  placeholder="05321234567"
                  className="flex-1 border rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
                <select value={t.turu} onChange={e => ekTelGuncelle(i, 'turu', e.target.value)}
                  className="border rounded-xl px-2 py-2 text-sm bg-white w-20">
                  <option value="cep">Cep</option>
                  <option value="is">İş</option>
                  <option value="faks">Faks</option>
                  <option value="diger">Diğer</option>
                </select>
                <button onClick={() => ekTelSil(i)}
                  className="text-red-400 hover:text-red-600 font-bold text-lg w-7 h-7 flex items-center justify-center shrink-0">×</button>
              </div>
            ))}
          </div>

          {/* Cari / Fatura Adresi */}
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-2">Cari Adres (Fatura Adresi)</label>
            <textarea value={form.cari_adres} onChange={e => setF('cari_adres', e.target.value)} rows={2}
              placeholder="Sokak / Cadde / No"
              className="w-full border rounded-xl px-3 py-2.5 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 mb-2" />
            <div className="grid grid-cols-2 gap-3">
              <input type="text" value={form.cari_ilce} onChange={e => setF('cari_ilce', e.target.value)}
                placeholder="İlçe"
                className="border rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
              <input type="text" value={form.cari_il} onChange={e => setF('cari_il', e.target.value)}
                placeholder="İl"
                className="border rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
            </div>
            <p className="text-xs text-gray-400 mt-1">Sevk adresi farklıysa sipariş detayından eklenir.</p>
          </div>

          {/* Chatwoot Contact ID */}
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1.5">Chatwoot Contact ID</label>
            <input type="text" value={form.chatwoot_contact_id}
              onChange={e => setF('chatwoot_contact_id', e.target.value)}
              placeholder="Chatwoot → Contacts'taki sayısal ID"
              className="w-full border rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
            <p className="text-xs text-gray-400 mt-1">Chatwoot müşteri profiline doğrudan link için.</p>
          </div>

          {/* Notlar */}
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1.5">Notlar</label>
            <textarea value={form.notlar} onChange={e => setF('notlar', e.target.value)} rows={2}
              placeholder="Müşteri hakkında özel not..."
              className="w-full border rounded-xl px-3 py-2.5 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>

          <button onClick={handleKaydet} disabled={kaydediyor}
            className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-blue-300 text-white py-3 rounded-xl font-semibold text-sm transition-colors">
            {kaydediyor ? 'Kaydediliyor...' : (isEdit ? 'Değişiklikleri Kaydet' : 'Müşteriyi Kaydet')}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── MÜŞTERİLER ───────────────────────────────────────────────────
function MusterilerView({ showToast }) {
  const [q,           setQ]           = useState('');
  const [musteriler,  setMusteriler]  = useState([]);
  const [loading,     setLoading]     = useState(true);
  const [secili,      setSecili]      = useState(null);
  const [gecmis,      setGecmis]      = useState([]);
  const [formAcik,    setFormAcik]    = useState(false);
  const [editMusteri, setEditMusteri] = useState(null);
  const debQ = useDebounce(q, 300);

  function loadList() {
    setLoading(true);
    api.get('/musteriler' + (debQ ? '?q=' + encodeURIComponent(debQ) : ''))
      .then(setMusteriler)
      .catch(e => showToast(e.message, 'error'))
      .finally(() => setLoading(false));
  }

  useEffect(() => { loadList(); }, [debQ]);

  function selectMusteri(m) {
    // Detay için tam kaydı çek (telefonlar + sevk_adresleri dahil)
    api.get(`/musteriler/${m.id}`)
      .then(full => { setSecili(full); })
      .catch(() => setSecili(m));
    api.get(`/siparisler?musteri_id=${m.id}`)
      .then(setGecmis)
      .catch(() => setGecmis([]));
  }

  function onSaved(saved) {
    setFormAcik(false);
    setEditMusteri(null);
    loadList();
    // Açık detay panelini de güncelle
    if (secili?.id === saved.id) {
      api.get(`/musteriler/${saved.id}`).then(setSecili).catch(() => setSecili(saved));
    }
  }

  function handleYeniMusteri() {
    setEditMusteri(null);
    setFormAcik(true);
  }

  function handleDuzenle() {
    setEditMusteri(secili);
    setFormAcik(true);
  }

  const TURU_LABEL = { cep: 'Cep', is: 'İş', faks: 'Faks', diger: 'Diğer' };

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h1 className="text-xl font-bold text-gray-800">Müşteriler</h1>
        <button onClick={handleYeniMusteri}
          className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-xl text-sm font-semibold">
          + Yeni Müşteri
        </button>
      </div>

      <div className="flex gap-4 items-start flex-col lg:flex-row">

        {/* Liste */}
        <div className="flex-1 w-full">
          <input type="text" value={q} onChange={e => setQ(e.target.value)}
            placeholder="Ad, telefon veya cari kod ile ara..."
            className="w-full border rounded-xl px-3 py-2.5 text-sm mb-3 focus:outline-none focus:ring-2 focus:ring-blue-500" />

          <div className="bg-white rounded-2xl border overflow-hidden">
            {loading ? <Spinner /> : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50 border-b">
                    <tr>
                      <th className="text-left px-4 py-3 text-gray-500 font-medium">Cari Kod</th>
                      <th className="text-left px-4 py-3 text-gray-500 font-medium">Ad</th>
                      <th className="text-left px-4 py-3 text-gray-500 font-medium hidden md:table-cell">Telefon</th>
                      <th className="text-left px-4 py-3 text-gray-500 font-medium hidden md:table-cell">Bölge</th>
                    </tr>
                  </thead>
                  <tbody>
                    {musteriler.length === 0 ? (
                      <tr><td colSpan={4} className="text-center text-gray-400 py-10">Müşteri bulunamadı</td></tr>
                    ) : musteriler.map(m => (
                      <tr key={m.id} onClick={() => selectMusteri(m)}
                        className={`border-t cursor-pointer hover:bg-blue-50 transition-colors ${secili?.id === m.id ? 'bg-blue-50' : ''}`}>
                        <td className="px-4 py-3 font-mono text-xs text-gray-400">{m.cari_kod}</td>
                        <td className="px-4 py-3 font-medium">{m.ad}</td>
                        <td className="px-4 py-3 text-gray-500 hidden md:table-cell">{m.telefon || '—'}</td>
                        <td className="px-4 py-3 hidden md:table-cell">{m.siparis_bolge_kodu || '—'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>

        {/* Detay */}
        {secili && (
          <div className="w-full lg:w-80 bg-white rounded-2xl border p-5 shrink-0">
            <div className="flex justify-between items-start mb-3">
              <div>
                <div className="font-bold text-gray-900">{secili.ad}</div>
                <div className="text-xs text-gray-400 font-mono mt-0.5">{secili.cari_kod}</div>
              </div>
              <div className="flex items-center gap-1">
                <button onClick={handleDuzenle}
                  className="text-xs bg-blue-50 text-blue-600 hover:bg-blue-100 px-2.5 py-1 rounded-lg font-semibold">
                  Düzenle
                </button>
                <button onClick={() => setSecili(null)}
                  className="text-gray-400 hover:text-gray-600 font-bold text-xl w-7 h-7 flex items-center justify-center rounded-full hover:bg-gray-100">×</button>
              </div>
            </div>

            <div className="space-y-2 text-sm text-gray-700 mb-3">
              {secili.siparis_bolge_kodu && (
                <div><span className="text-gray-400">Bölge:</span> {secili.siparis_bolge_kodu}</div>
              )}

              {/* Telefonlar */}
              {secili.telefon && (
                <div className="flex items-center gap-1.5">
                  <span className="text-gray-400 text-xs">📱 Birincil:</span>
                  <a href={`tel:${secili.telefon}`} className="hover:text-blue-600">{secili.telefon}</a>
                </div>
              )}
              {(secili.telefonlar || []).map((t, i) => (
                <div key={i} className="flex items-center gap-1.5">
                  <span className="text-gray-400 text-xs">{TURU_LABEL[t.turu] || t.turu}:</span>
                  <a href={`tel:${t.telefon}`} className="hover:text-blue-600">{t.telefon}</a>
                </div>
              ))}

              {/* Cari adres */}
              {(secili.cari_adres || secili.cari_ilce || secili.cari_il) && (
                <div className="pt-1 border-t">
                  <div className="text-xs text-gray-400 font-semibold mb-1">Cari Adres</div>
                  {secili.cari_adres && <div className="text-xs">{secili.cari_adres}</div>}
                  {(secili.cari_ilce || secili.cari_il) && (
                    <div className="text-xs text-gray-500">
                      {[secili.cari_ilce, secili.cari_il].filter(Boolean).join(' / ')}
                    </div>
                  )}
                </div>
              )}

              {/* Sevk adresleri */}
              {(secili.sevk_adresleri || []).length > 0 && (
                <div className="pt-1 border-t">
                  <div className="text-xs text-gray-400 font-semibold mb-1">Sevk Adresleri</div>
                  {secili.sevk_adresleri.map((a, i) => (
                    <div key={i} className="text-xs text-gray-600 mb-1">
                      {a.varsayilan && <span className="text-blue-600 font-semibold">[Varsayılan] </span>}
                      {[a.adres, a.ilce, a.il].filter(Boolean).join(', ')}
                    </div>
                  ))}
                </div>
              )}

              {/* Chatwoot */}
              {secili.chatwoot_contact_id && (
                <div className="pt-1 border-t">
                  <a href={`/chatwoot/contacts/${secili.chatwoot_contact_id}`}
                    target="_blank" rel="noreferrer"
                    className="inline-flex items-center gap-1 text-xs text-blue-600 hover:text-blue-800">
                    💬 Chatwoot Contact #{secili.chatwoot_contact_id}
                  </a>
                </div>
              )}

              {secili.notlar && (
                <div className="pt-1 border-t">
                  <span className="text-gray-400 text-xs">Not:</span>
                  <div className="text-xs mt-0.5 text-gray-600">{secili.notlar}</div>
                </div>
              )}
            </div>

            {/* Son siparişler */}
            <div className="border-t pt-3">
              <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Son Siparişler</div>
              {gecmis.length === 0 ? (
                <div className="text-xs text-gray-400">Sipariş kaydı yok</div>
              ) : gecmis.slice(0, 6).map(s => (
                <div key={s.id} className="flex justify-between items-center py-2 border-b last:border-0">
                  <div>
                    <div className="font-mono text-xs text-gray-400">{s.siparis_no}</div>
                    <div className="text-xs text-gray-600 mt-0.5">{fmtDate(s.teslimat_tarihi)}</div>
                  </div>
                  <DurumBadge durum={s.durum} />
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {formAcik && (
        <MusteriFormPanel
          musteri={editMusteri}
          onClose={() => { setFormAcik(false); setEditMusteri(null); }}
          onSaved={onSaved}
          showToast={showToast}
        />
      )}
    </div>
  );
}

// ── ÜRÜNLER ──────────────────────────────────────────────────────
function UrunlerView({ showToast }) {
  const [urunler,  setUrunler]  = useState([]);
  const [loading,  setLoading]  = useState(true);
  const [yeni,     setYeni]     = useState({ ad: '', kod: '', birim: 'adet' });

  useEffect(() => {
    api.get('/urunler').then(setUrunler).catch(e => showToast(e.message, 'error')).finally(() => setLoading(false));
  }, []);

  async function handleEkle(e) {
    e.preventDefault();
    if (!yeni.ad.trim()) return;
    try {
      const created = await api.post('/urunler', yeni);
      setUrunler(prev => [...prev, created]);
      setYeni({ ad: '', kod: '', birim: 'adet' });
      showToast('Ürün eklendi');
    } catch (err) {
      showToast(err.message, 'error');
    }
  }

  async function toggleAktif(urun) {
    try {
      const updated = await api.patch(`/urunler/${urun.id}`, { aktif: !urun.aktif });
      setUrunler(prev => prev.map(u => u.id === urun.id ? updated : u));
    } catch (err) {
      showToast(err.message, 'error');
    }
  }

  const setY = (k, v) => setYeni(n => ({ ...n, [k]: v }));

  return (
    <div>
      <h1 className="text-xl font-bold text-gray-800 mb-4">Ürünler</h1>

      {/* Ekle formu */}
      <form onSubmit={handleEkle}
        className="bg-white rounded-2xl border p-4 mb-4 flex flex-wrap gap-3 items-end">
        <div className="flex-1 min-w-36">
          <label className="block text-xs font-semibold text-gray-500 mb-1">Ürün Adı *</label>
          <input type="text" value={yeni.ad} onChange={e => setY('ad', e.target.value)}
            placeholder="Ürün adı" required
            className="w-full border rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
        </div>
        <div className="w-28">
          <label className="block text-xs font-semibold text-gray-500 mb-1">Kod</label>
          <input type="text" value={yeni.kod} onChange={e => setY('kod', e.target.value)}
            placeholder="URN001"
            className="w-full border rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
        </div>
        <div className="w-24">
          <label className="block text-xs font-semibold text-gray-500 mb-1">Birim</label>
          <input type="text" value={yeni.birim} onChange={e => setY('birim', e.target.value)}
            placeholder="kg"
            className="w-full border rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
        </div>
        <button type="submit"
          className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-xl text-sm font-semibold">
          + Ekle
        </button>
      </form>

      {/* Tablo */}
      <div className="bg-white rounded-2xl border overflow-hidden">
        {loading ? <Spinner /> : (
          <table className="w-full text-sm">
            <thead className="bg-gray-50 border-b">
              <tr>
                <th className="text-left px-4 py-3 text-gray-500 font-medium">Ad</th>
                <th className="text-left px-4 py-3 text-gray-500 font-medium hidden md:table-cell">Kod</th>
                <th className="text-left px-4 py-3 text-gray-500 font-medium">Birim</th>
                <th className="text-center px-4 py-3 text-gray-500 font-medium">Aktif</th>
              </tr>
            </thead>
            <tbody>
              {urunler.length === 0 ? (
                <tr><td colSpan={4} className="text-center text-gray-400 py-10">Ürün bulunamadı</td></tr>
              ) : urunler.map(u => (
                <tr key={u.id} className={`border-t ${!u.aktif ? 'opacity-50' : ''}`}>
                  <td className="px-4 py-3 font-medium">{u.ad}</td>
                  <td className="px-4 py-3 font-mono text-xs text-gray-400 hidden md:table-cell">{u.kod || '—'}</td>
                  <td className="px-4 py-3 text-gray-500">{u.birim}</td>
                  <td className="px-4 py-3">
                    <div className="flex justify-center">
                      <button onClick={() => toggleAktif(u)}
                        className={`relative w-10 h-5 rounded-full transition-colors duration-200 focus:outline-none
                          ${u.aktif ? 'bg-blue-600' : 'bg-gray-300'}`}>
                        <span className={`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-all duration-200
                          ${u.aktif ? 'right-0.5' : 'left-0.5'}`} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

// ── YARINKI SEVKİYAT ─────────────────────────────────────────────
function YarinSevkiyatView() {
  const [siparisler, setSiparisler] = useState([]);
  const [loading,    setLoading]    = useState(true);

  useEffect(() => {
    api.get('/siparisler/yarin-sevkiyat')
      .then(setSiparisler)
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const yarin = (() => {
    const d = new Date(); d.setDate(d.getDate() + 1);
    return d.toLocaleDateString('tr-TR', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
  })();

  // Bölgeye göre grupla
  const gruplar = {};
  siparisler.forEach(s => {
    const b = s.siparis_bolge_kodu || 'Bölge Belirtilmemiş';
    if (!gruplar[b]) gruplar[b] = [];
    gruplar[b].push(s);
  });

  return (
    <div>
      <div className="flex items-center justify-between mb-4 no-print">
        <div>
          <h1 className="text-xl font-bold text-gray-800">Yarınki Sevkiyat</h1>
          <div className="text-sm text-gray-500 mt-0.5">{yarin}</div>
        </div>
        <div className="flex gap-2">
          <button onClick={() => siparislerExcelIndir(siparisler, 'Sevkiyat-' + new Date().toISOString().slice(0,10))}
            className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-xl text-sm font-semibold">
            ⬇ Excel İndir
          </button>
          <button onClick={() => window.print()}
            className="bg-gray-800 hover:bg-gray-900 text-white px-4 py-2 rounded-xl text-sm font-semibold">
            Yazdır
          </button>
        </div>
      </div>

      <div className="print-title">
        <h2 style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '4px' }}>Sevkiyat Listesi</h2>
        <p style={{ fontSize: '13px', color: '#555', marginBottom: '12px' }}>{yarin}</p>
      </div>

      {loading ? <Spinner /> : siparisler.length === 0 ? (
        <div className="bg-white rounded-2xl border text-center text-gray-400 py-12 text-sm">
          Yarın için onaylı sevkiyat bulunmuyor
        </div>
      ) : (
        <div className="space-y-5">
          {Object.entries(gruplar).map(([bolge, liste]) => (
            <div key={bolge} className="bg-white rounded-2xl border overflow-hidden">
              <div className="bg-gray-800 text-white px-5 py-3 flex items-center justify-between">
                <span className="font-semibold text-sm">Bölge: {bolge}</span>
                <span className="text-gray-400 text-xs">{liste.length} sipariş</span>
              </div>
              <table className="w-full text-sm">
                <thead className="bg-gray-50 border-b">
                  <tr>
                    <th className="text-left px-4 py-2.5 text-gray-500 font-medium text-xs">Müşteri</th>
                    <th className="text-left px-4 py-2.5 text-gray-500 font-medium text-xs hidden md:table-cell">Adres</th>
                    <th className="text-left px-4 py-2.5 text-gray-500 font-medium text-xs">Ürünler</th>
                    <th className="text-left px-4 py-2.5 text-gray-500 font-medium text-xs hidden md:table-cell">Not</th>
                  </tr>
                </thead>
                <tbody>
                  {liste.map(s => (
                    <tr key={s.id} className="border-t align-top">
                      <td className="px-4 py-3">
                        <div className="font-semibold">{s.musteri_ad}</div>
                        <div className="text-xs text-gray-400 font-mono">{s.cari_kod}</div>
                      </td>
                      <td className="px-4 py-3 text-xs text-gray-500 hidden md:table-cell">
                        {s.adres ? `${s.adres}${s.ilce ? ', ' + s.ilce : ''}` : '—'}
                      </td>
                      <td className="px-4 py-3">
                        {(s.kalemler || []).map((k, i) => (
                          <div key={i} className="text-xs">
                            {k.urun_ad}: <span className="font-semibold">{k.miktar} {k.birim}</span>
                          </div>
                        ))}
                      </td>
                      <td className="px-4 py-3 text-xs text-gray-500 hidden md:table-cell">
                        {s.notlar || '—'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── ANA UYGULAMA ─────────────────────────────────────────────────
function App() {
  const [authChecked,       setAuthChecked]       = useState(false);
  const [kullanici,         setKullanici]         = useState(null);
  const [view,              setView]              = useState('dashboard');
  const [selectedSiparisId, setSelectedSiparisId] = useState(null);
  const [toast,             setToast]             = useState(null);
  const [menuOpen,          setMenuOpen]          = useState(false);

  useEffect(() => {
    api.get('/me')
      .then(d => { setKullanici(d.authenticated ? d.kullanici : null); setAuthChecked(true); })
      .catch(() => { setKullanici(null); setAuthChecked(true); });
  }, []);

  async function handleLogout() {
    try { await api.post('/logout', {}); } catch {}
    setKullanici(null);
  }

  function showToast(msg, type = 'success') {
    setToast({ message: msg, type });
    setTimeout(() => setToast(null), 3500);
  }

  function navigate(newView, opts = {}) {
    setView(newView);
    setMenuOpen(false);
    setSelectedSiparisId(opts.siparisId || null);
  }

  if (!authChecked) return (
    <div className="min-h-screen bg-gray-100 flex items-center justify-center">
      <div className="text-gray-400 text-sm">Yükleniyor...</div>
    </div>
  );
  if (!kullanici) return <LoginView onLogin={k => setKullanici(k)} />;

  return (
    <div className="flex h-screen bg-gray-100 overflow-hidden">

      {/* Mobil overlay */}
      {menuOpen && (
        <div className="fixed inset-0 z-20 bg-black/50 lg:hidden" onClick={() => setMenuOpen(false)} />
      )}

      {/* Sidebar */}
      <div className={`
        fixed lg:relative inset-y-0 left-0 z-30 w-52 bg-gray-900 flex-shrink-0
        transform transition-transform duration-200
        ${menuOpen ? 'translate-x-0' : '-translate-x-full'}
        lg:translate-x-0
      `}>
        <Sidebar view={view} navigate={navigate} kullanici={kullanici} onLogout={handleLogout} />
      </div>

      {/* İçerik */}
      <div className="flex-1 flex flex-col min-w-0 overflow-hidden">

        {/* Mobil header */}
        <div className="lg:hidden flex items-center h-12 px-4 bg-white border-b shrink-0">
          <button onClick={() => setMenuOpen(true)}
            className="text-gray-600 hover:text-gray-800 mr-3 text-xl leading-none">
            ☰
          </button>
          <span className="font-semibold text-gray-800 text-sm">Sipariş Paneli</span>
        </div>

        <main className="flex-1 overflow-y-auto p-4 lg:p-6">
          {view === 'dashboard'      && <DashboardView navigate={navigate} />}
          {view === 'siparisler'     && (
            <SiparislerView
              selectedId={selectedSiparisId}
              setSelectedId={setSelectedSiparisId}
              showToast={showToast}
            />
          )}
          {view === 'yeni-siparis'   && <YeniSiparisView navigate={navigate} showToast={showToast} />}
          {view === 'musteriler'     && <MusterilerView showToast={showToast} />}
          {view === 'urunler'        && <UrunlerView showToast={showToast} />}
          {view === 'yarin-sevkiyat' && <YarinSevkiyatView />}
        </main>
      </div>

      <Toast toast={toast} />
    </div>
  );
}

// ── RENDER ───────────────────────────────────────────────────────
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
