// ─────────── Sözleşme / Çerçeve Anlaşma Yönetimi (B4) ───────────
// Tedarikçiye bağlı sözleşmeler: çerçeve anlaşma, hizmet, abonelik, tek seferlik, NDA.
// Süre/yenileme takibi (bitişe N gün), değer tavanı, belge, durum. Satınalma paneli "Sözleşmeler" sekmesi.
// Prototip: tüm veri demo; gerçek uygulamada sözleşme yönetimi (CLM) modülü.

const _ctDate = (offsetDays) => { const d = new Date(); d.setDate(d.getDate() + offsetDays); return d.toISOString().slice(0, 10); };

const CONTRACT_TYPE_META = {
  framework:    { label: 'Çerçeve Anlaşma', color: '#2563EB' },
  service:      { label: 'Hizmet Sözleşmesi', color: '#0891B2' },
  subscription: { label: 'Abonelik', color: '#7C3AED' },
  onetime:      { label: 'Tek Seferlik Alım', color: '#475569' },
  nda:          { label: 'Gizlilik (NDA)', color: '#B45309' },
};
const CONTRACT_STATUS_META = {
  draft:      { label: 'Taslak', color: '#6B7280', bg: 'rgba(107,114,128,0.14)' },
  active:     { label: 'Aktif', color: '#047857', bg: 'rgba(16,185,129,0.14)' },
  expiring:   { label: 'Yakında bitiyor', color: '#B45309', bg: 'rgba(245,158,11,0.16)' },
  expired:    { label: 'Süresi doldu', color: '#B91C1C', bg: 'rgba(239,68,68,0.14)' },
  terminated: { label: 'Feshedildi', color: '#6B7280', bg: 'rgba(107,114,128,0.14)' },
};
const CONTRACT_EXPIRY_DAYS = 60;   // bitişe bu kadar gün kalınca "yakında bitiyor"

function contractDaysLeft(con) {
  if (!con || !con.endDate) return null;
  return Math.ceil((new Date(con.endDate + 'T00:00:00') - new Date(new Date().toISOString().slice(0, 10) + 'T00:00:00')) / 86400000);
}
// Görünen (türetilmiş) durum: saklı taslak/fesih korunur; aktifse tarihten süre/yakında-bitiyor türetilir.
function contractStatusOf(con) {
  if (!con) return 'active';
  if (con.status === 'draft') return 'draft';
  if (con.status === 'terminated') return 'terminated';
  const dl = contractDaysLeft(con);
  if (dl != null && dl < 0) return 'expired';
  if (dl != null && dl <= CONTRACT_EXPIRY_DAYS) return 'expiring';
  return 'active';
}

const CONTRACTS_SEED = [
  { id: 'CT-2026-001', no: 'ÇA-2026-014', title: 'Dizüstü & Masaüstü Donanım Çerçeve Anlaşması', supplierId: 's-abc', supplierName: 'ABC Bilişim', type: 'framework', category: 'Bilişim Donanım', startDate: _ctDate(-120), endDate: _ctDate(245), value: 2500000, autoRenew: true, paymentTerms: '60 gün vadeli', status: 'active', owner: 'Kerem Acar', module: 'it', note: 'Yıllık 500 adede kadar dizüstü; birim fiyatlar ekte sabit.', createdAt: _ctDate(-120) },
  { id: 'CT-2026-002', no: 'HS-2026-007', title: 'Sunucu & Ağ Bakım Hizmeti (7/24 SLA)', supplierId: 's-teknikus', supplierName: 'Teknikus', type: 'service', category: 'Bakım & Destek', startDate: _ctDate(-335), endDate: _ctDate(28), value: 480000, autoRenew: false, paymentTerms: 'Aylık', status: 'active', owner: 'Kerem Acar', module: 'it', note: '4 saat müdahale taahhüdü. Yenileme görüşmesi başlatılmalı.', createdAt: _ctDate(-335) },
  { id: 'CT-2026-003', no: 'AB-2026-021', title: 'Microsoft 365 E3 Abonelik (250 kullanıcı)', supplierId: 's-netorder', supplierName: 'NetOrder', type: 'subscription', category: 'Yazılım & Lisans', startDate: _ctDate(-60), endDate: _ctDate(305), value: 920000, autoRenew: true, paymentTerms: 'Yıllık peşin', status: 'active', owner: 'Kerem Acar', module: 'it', note: 'Otomatik yenilemeli.', createdAt: _ctDate(-60) },
  { id: 'CT-2025-044', no: 'ÇA-2025-044', title: 'Kırtasiye & Sarf Çerçeve Anlaşması', supplierId: 's-ofisplus', supplierName: 'OfisPlus', type: 'framework', category: 'Kırtasiye', startDate: _ctDate(-400), endDate: _ctDate(-35), value: 180000, autoRenew: false, paymentTerms: '30 gün', status: 'active', owner: 'Kerem Acar', module: 'admin', note: 'Süresi doldu — yenileme/yeni ihale gerekli.', createdAt: _ctDate(-400) },
];
window.CONTRACTS_SEED = CONTRACTS_SEED;

// Abone hook (window.__contracts + 'contractschange')
function useContractsSnapshot() {
  const [items, setItems] = React.useState(() => (window.__contracts && window.__contracts.items) || []);
  React.useEffect(() => {
    const sync = () => setItems((window.__contracts && window.__contracts.items) || []);
    window.addEventListener('contractschange', sync);
    sync();
    return () => window.removeEventListener('contractschange', sync);
  }, []);
  return items;
}

function ctFmt(v) { return window.formatTL ? window.formatTL(v) : (v + ' ₺'); }

function ContractStatusBadge({ status, c }) {
  const m = CONTRACT_STATUS_META[status] || CONTRACT_STATUS_META.active;
  return <span style={{ fontSize: 11, fontWeight: 700, color: m.color, background: m.bg, padding: '3px 9px', borderRadius: 999, whiteSpace: 'nowrap' }}>{m.label}</span>;
}

// ── Sözleşme kartı ──
function ContractCard({ con, c, onEdit, onTerminate, onRemove }) {
  const isMobile = window.useIsMobile ? window.useIsMobile() : false;
  const st = contractStatusOf(con);
  const tm = CONTRACT_TYPE_META[con.type] || {};
  const dl = contractDaysLeft(con);
  const expSoon = st === 'expiring';
  const expired = st === 'expired';
  return (
    <div style={{ background: c.card, border: `1px solid ${(expSoon || expired) ? (expired ? '#EF4444' : '#F59E0B') + '66' : c.border}`, borderRadius: 14, padding: isMobile ? 14 : 18 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, flexWrap: 'wrap', marginBottom: 8 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: c.text }}>{con.title}</div>
          <div style={{ fontSize: 12, color: c.muted, marginTop: 2 }}>{con.supplierName}{con.no ? ` · ${con.no}` : ''}</div>
        </div>
        <ContractStatusBadge status={st} c={c} />
      </div>

      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 10 }}>
        <span style={{ fontSize: 11, fontWeight: 700, color: tm.color, background: (tm.color || '#888') + '18', padding: '2px 9px', borderRadius: 999 }}>{tm.label || con.type}</span>
        {con.category && <span style={{ fontSize: 11, color: c.muted, background: c.chipBg, padding: '2px 9px', borderRadius: 999 }}>{con.category}</span>}
        {con.autoRenew && <span style={{ fontSize: 11, color: c.muted, background: c.chipBg, padding: '2px 9px', borderRadius: 999 }}>↻ Otomatik yenileme</span>}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4, 1fr)', gap: 10, marginBottom: con.note ? 10 : 12 }}>
        <div><div style={{ fontSize: 10.5, color: c.muted }}>Başlangıç</div><div style={{ fontSize: 12.5, color: c.text, fontWeight: 600 }}>{con.startDate || '—'}</div></div>
        <div><div style={{ fontSize: 10.5, color: c.muted }}>Bitiş</div><div style={{ fontSize: 12.5, color: expired ? '#B91C1C' : c.text, fontWeight: 600 }}>{con.endDate || '—'}</div></div>
        <div><div style={{ fontSize: 10.5, color: c.muted }}>Tutar / tavan</div><div style={{ fontSize: 12.5, color: c.text, fontWeight: 700 }}>{con.value ? ctFmt(con.value) : '—'}</div></div>
        <div><div style={{ fontSize: 10.5, color: c.muted }}>Ödeme</div><div style={{ fontSize: 12.5, color: c.text, fontWeight: 600 }}>{con.paymentTerms || '—'}</div></div>
      </div>

      {(expSoon || expired) && (
        <div style={{ fontSize: 12, fontWeight: 600, color: expired ? '#B91C1C' : '#B45309', marginBottom: 10 }}>
          {expired ? `⚠ Süresi ${Math.abs(dl)} gün önce doldu — yenileme gerekli` : `🔔 Bitişe ${dl} gün kaldı — yenilemeyi planlayın`}
        </div>
      )}

      {con.note && <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 12, lineHeight: 1.5 }}>{con.note}</div>}

      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
        {con.docDataUrl && <a href={con.docDataUrl} download={con.docName || 'sozlesme'} style={{ fontSize: 12, color: c.primary, textDecoration: 'none', fontWeight: 600 }}>📄 {con.docName || 'Belge'}</a>}
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <button onClick={() => onEdit(con)} style={ctGhost(c)}>Düzenle</button>
          {con.status !== 'terminated' && <button onClick={() => onTerminate(con)} style={{ ...ctGhost(c), color: '#B91C1C', borderColor: '#EF444455' }}>Feshet</button>}
          <button onClick={() => onRemove(con)} style={{ ...ctGhost(c), color: c.muted }}>Sil</button>
        </div>
      </div>
    </div>
  );
}
function ctGhost(c) { return { appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, background: c.card, color: c.text, border: `1px solid ${c.border}`, borderRadius: 9, padding: '7px 13px' }; }
function ctInput(c) { return { width: '100%', boxSizing: 'border-box', padding: '10px 12px', background: c.inputBg || c.card, color: c.text, border: `1px solid ${c.border}`, borderRadius: 10, fontSize: 13, fontFamily: 'inherit', outline: 'none' }; }

// ── Yeni/Düzenle sözleşme formu (modal) ──
function ContractForm({ c, initial, onClose }) {
  const isMobile = window.useIsMobile ? window.useIsMobile() : false;
  const suppliers = (window.useSuppliersSnapshot ? window.useSuppliersSnapshot() : []).filter((s) => s.status !== 'banned');
  const [title, setTitle] = React.useState(initial ? initial.title : '');
  const [no, setNo] = React.useState(initial ? initial.no || '' : '');
  const [supplierId, setSupplierId] = React.useState(initial ? initial.supplierId || '' : '');
  const [type, setType] = React.useState(initial ? initial.type : 'framework');
  const [category, setCategory] = React.useState(initial ? initial.category || '' : '');
  const [startDate, setStartDate] = React.useState(initial ? initial.startDate || '' : '');
  const [endDate, setEndDate] = React.useState(initial ? initial.endDate || '' : '');
  const [value, setValue] = React.useState(initial ? (initial.value || '') : '');
  const [paymentTerms, setPaymentTerms] = React.useState(initial ? initial.paymentTerms || '' : '');
  const [autoRenew, setAutoRenew] = React.useState(initial ? !!initial.autoRenew : false);
  const [note, setNote] = React.useState(initial ? initial.note || '' : '');
  const [docDataUrl, setDocDataUrl] = React.useState(initial ? initial.docDataUrl || '' : '');
  const [docName, setDocName] = React.useState(initial ? initial.docName || '' : '');

  const lbl = { fontSize: 11.5, color: c.muted, marginBottom: 5, display: 'block' };
  const col = { display: 'flex', flexDirection: 'column' };

  function onFile(e) {
    const f = e.target.files && e.target.files[0]; if (!f) return;
    if (f.size > 4 * 1024 * 1024) { alert('Dosya 4 MB\'tan küçük olmalı.'); return; }
    const r = new FileReader(); r.onload = () => { setDocDataUrl(r.result); setDocName(f.name); }; r.readAsDataURL(f);
  }
  function save() {
    if (!title.trim()) { alert('Sözleşme başlığı zorunlu.'); return; }
    if (startDate && endDate && endDate < startDate) { alert('Bitiş tarihi başlangıçtan önce olamaz.'); return; }
    const sup = suppliers.find((s) => s.id === supplierId);
    const data = {
      title: title.trim(), no: no.trim(), supplierId: supplierId || null, supplierName: sup ? (sup.shortName || sup.company) : (initial ? initial.supplierName : ''),
      type, category: category.trim(), startDate, endDate, value: parseInt(String(value).replace(/[^\d]/g, ''), 10) || 0,
      paymentTerms: paymentTerms.trim(), autoRenew, note: note.trim(), docDataUrl: docDataUrl || undefined, docName: docName || undefined,
      module: initial ? initial.module : (sup && sup.module) || 'it',
    };
    const C = window.__contracts || {};
    if (initial) { if (C.update) C.update(initial.id, data); }
    else { if (C.add) C.add({ ...data, owner: (window.__user && window.__user.name) || 'Satınalma' }); }
    onClose();
  }

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 200, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: isMobile ? '16px' : '40px 16px', overflowY: 'auto' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.bg, borderRadius: 16, width: '100%', maxWidth: 620, border: `1px solid ${c.border}`, padding: isMobile ? 18 : 24 }}>
        <div style={{ fontSize: 16, fontWeight: 700, color: c.text, marginBottom: 16 }}>{initial ? 'Sözleşmeyi düzenle' : 'Yeni sözleşme'}</div>

        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 12 }}>
          <div style={{ ...col, gridColumn: isMobile ? 'auto' : '1 / -1' }}><label style={lbl}>Başlık *</label><input value={title} onChange={(e) => setTitle(e.target.value)} style={ctInput(c)} placeholder="örn. Donanım Çerçeve Anlaşması" /></div>
          <div style={col}><label style={lbl}>Sözleşme no</label><input value={no} onChange={(e) => setNo(e.target.value)} style={ctInput(c)} placeholder="ÇA-2026-001" /></div>
          <div style={col}><label style={lbl}>Tedarikçi</label>
            <select value={supplierId} onChange={(e) => setSupplierId(e.target.value)} style={{ ...ctInput(c), cursor: 'pointer' }}>
              <option value="">— seçin —</option>
              {suppliers.map((s) => <option key={s.id} value={s.id}>{s.shortName || s.company}</option>)}
            </select>
          </div>
          <div style={col}><label style={lbl}>Tür</label>
            <select value={type} onChange={(e) => setType(e.target.value)} style={{ ...ctInput(c), cursor: 'pointer' }}>
              {Object.keys(CONTRACT_TYPE_META).map((k) => <option key={k} value={k}>{CONTRACT_TYPE_META[k].label}</option>)}
            </select>
          </div>
          <div style={col}><label style={lbl}>Kategori</label><input value={category} onChange={(e) => setCategory(e.target.value)} style={ctInput(c)} placeholder="örn. Bilişim Donanım" /></div>
          <div style={col}><label style={lbl}>Başlangıç</label><input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} style={ctInput(c)} /></div>
          <div style={col}><label style={lbl}>Bitiş</label><input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} style={ctInput(c)} /></div>
          <div style={col}><label style={lbl}>Tutar / tavan (₺)</label><input value={value} onChange={(e) => setValue(e.target.value)} style={ctInput(c)} placeholder="2500000" inputMode="numeric" /></div>
          <div style={col}><label style={lbl}>Ödeme koşulu</label><input value={paymentTerms} onChange={(e) => setPaymentTerms(e.target.value)} style={ctInput(c)} placeholder="60 gün vadeli" /></div>
          <div style={{ ...col, gridColumn: isMobile ? 'auto' : '1 / -1', flexDirection: 'row', alignItems: 'center', gap: 8 }}>
            <input id="ct-auto" type="checkbox" checked={autoRenew} onChange={(e) => setAutoRenew(e.target.checked)} style={{ width: 16, height: 16 }} />
            <label htmlFor="ct-auto" style={{ fontSize: 13, color: c.text, cursor: 'pointer' }}>Otomatik yenileme</label>
          </div>
          <div style={{ ...col, gridColumn: isMobile ? 'auto' : '1 / -1' }}><label style={lbl}>Not</label><textarea value={note} onChange={(e) => setNote(e.target.value)} rows={2} style={{ ...ctInput(c), resize: 'vertical' }} placeholder="Kapsam, SLA, özel şartlar…" /></div>
          <div style={{ ...col, gridColumn: isMobile ? 'auto' : '1 / -1' }}>
            <label style={lbl}>Sözleşme belgesi (PDF/görsel, ≤4MB)</label>
            <input type="file" onChange={onFile} style={{ fontSize: 12, color: c.muted }} />
            {docName && <span style={{ fontSize: 11.5, color: c.primary, marginTop: 4 }}>📄 {docName}</span>}
          </div>
        </div>

        <div style={{ display: 'flex', gap: 10, marginTop: 20, justifyContent: 'flex-end' }}>
          <button onClick={onClose} style={ctGhost(c)}>Vazgeç</button>
          <button onClick={save} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, background: c.primary, color: '#fff', border: 'none', borderRadius: 9, padding: '10px 18px' }}>{initial ? 'Kaydet' : 'Oluştur'}</button>
        </div>
      </div>
    </div>
  );
}

// ── Sözleşmeler görünümü (Satınalma sekmesi) ──
function ContractsView({ c }) {
  const isMobile = window.useIsMobile ? window.useIsMobile() : false;
  const all = useContractsSnapshot();
  const [form, setForm] = React.useState(null);   // null | {} (new) | contract (edit)
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [q, setQ] = React.useState('');

  const withStatus = all.map((con) => ({ con, st: contractStatusOf(con) }));
  const alerts = withStatus.filter((x) => x.st === 'expiring' || x.st === 'expired');
  const list = withStatus.filter((x) => {
    if (statusFilter !== 'all' && x.st !== statusFilter) return false;
    if (q.trim()) {
      const s = q.trim().toLowerCase();
      if (![x.con.title, x.con.supplierName, x.con.no, x.con.category].some((v) => (v || '').toLowerCase().includes(s))) return false;
    }
    return true;
  }).sort((a, b) => (a.con.endDate || '').localeCompare(b.con.endDate || ''));

  const usedStatuses = ['all', ...Object.keys(CONTRACT_STATUS_META).filter((k) => withStatus.some((x) => x.st === k))];
  const chip = (active, m) => ({ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, padding: '6px 12px', borderRadius: 999, border: `1px solid ${active ? (m ? m.color : c.primary) : c.border}`, background: active ? (m ? m.color : c.primary) : c.card, color: active ? '#fff' : c.muted });

  function terminate(con) {
    if (window.confirm(`"${con.title}" sözleşmesi feshedilsin mi?`)) { const note = window.prompt('Fesih gerekçesi (opsiyonel):') || ''; if (window.__contracts) window.__contracts.setStatus(con.id, 'terminated', note); }
  }
  function remove(con) {
    if (window.confirm(`"${con.title}" sözleşmesi kalıcı olarak silinsin mi?`)) { if (window.__contracts) window.__contracts.remove(con.id); }
  }

  return (
    <div>
      {form && <ContractForm c={c} initial={form.id ? form : null} onClose={() => setForm(null)} />}

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginBottom: 14 }}>
        <div style={{ fontSize: 12.5, color: c.muted }}>{list.length} sözleşme</div>
        <button onClick={() => setForm({})} style={{ marginLeft: 'auto', appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, background: c.primary, color: '#fff', border: 'none', borderRadius: 9, padding: '9px 16px' }}>+ Yeni sözleşme</button>
      </div>

      {alerts.length > 0 && (
        <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '12px 14px', borderRadius: 12, background: 'rgba(245,158,11,.12)', border: '1px solid rgba(245,158,11,.4)', marginBottom: 14 }}>
          <span style={{ fontSize: 16 }}>🔔</span>
          <div style={{ fontSize: 12.5, color: c.text, lineHeight: 1.5 }}>
            <b>{alerts.length} sözleşme dikkat gerektiriyor:</b> {alerts.filter((x) => x.st === 'expiring').length} yakında bitiyor, {alerts.filter((x) => x.st === 'expired').length} süresi doldu. Yenileme/yeni ihale planlayın.
          </div>
        </div>
      )}

      <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap', marginBottom: 12 }}>
        {usedStatuses.map((k) => (
          <button key={k} onClick={() => setStatusFilter(k)} style={chip(statusFilter === k, CONTRACT_STATUS_META[k])}>
            {k === 'all' ? 'Tümü' : CONTRACT_STATUS_META[k].label}
          </button>
        ))}
      </div>

      <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Ara (başlık / tedarikçi / no / kategori)…" style={{ ...ctInput(c), marginBottom: 14 }} />

      {list.length === 0 ? (
        <div style={{ background: c.card, border: `1px dashed ${c.border}`, borderRadius: 14, padding: 40, textAlign: 'center', color: c.muted }}>
          <div style={{ fontSize: 28, marginBottom: 8 }}>📑</div>
          <div style={{ fontSize: 14, fontWeight: 600, color: c.text, marginBottom: 4 }}>{all.length === 0 ? 'Henüz sözleşme yok' : 'Bu filtreyle eşleşen sözleşme yok'}</div>
          {all.length === 0 ? '"+ Yeni sözleşme" ile bir çerçeve anlaşma veya hizmet sözleşmesi ekleyin.' : ''}
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {list.map((x) => <ContractCard key={x.con.id} con={x.con} c={c} onEdit={(con) => setForm(con)} onTerminate={terminate} onRemove={remove} />)}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ContractsView, ContractCard, ContractForm, ContractStatusBadge, useContractsSnapshot, contractStatusOf, contractDaysLeft, CONTRACT_TYPE_META, CONTRACT_STATUS_META, CONTRACTS_SEED });
