// ratings.jsx — Teslim sonrası değerlendirme (Faz 4 / Parça 4.5)
// "İkisi birden": talep eden ürünü + teslim deneyimini puanlar; talebi açanın yöneticisi
// tedarikçiyi (genel performans) puanlar → tedarikçi kartının ortalama puanına işlenir.
// Ortak stiller (inputBox, solidBtn, ghostBtn) admin-approvals.jsx'te global.

// ─────────── Yıldız seçici ───────────
function StarRatingInput({ value, onChange, c, size = 26 }) {
  const [hover, setHover] = React.useState(0);
  return (
    <div style={{ display: 'inline-flex', gap: 4 }}>
      {[1, 2, 3, 4, 5].map((i) => {
        const on = (hover || value) >= i;
        return (
          <button key={i} type="button"
            onClick={() => onChange(i)}
            onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(0)}
            style={{ appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer', padding: 0, lineHeight: 0 }}>
            <svg width={size} height={size} viewBox="0 0 24 24" fill={on ? '#F59E0B' : 'none'} stroke={on ? '#F59E0B' : c.subtle} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 2l3 6.5 7 .9-5 4.9 1.2 7-6.4-3.4L5.6 21l1.2-7-5-4.9 7-.9z" />
            </svg>
          </button>
        );
      })}
    </div>
  );
}

// Statik yıldız gösterimi
function StarsView({ value, c }) {
  return (
    <span style={{ display: 'inline-flex', gap: 2, alignItems: 'center' }}>
      {[1, 2, 3, 4, 5].map((i) => (
        <svg key={i} width="14" height="14" viewBox="0 0 24 24" fill={i <= Math.round(value) ? '#F59E0B' : 'none'} stroke={i <= Math.round(value) ? '#F59E0B' : c.subtle} strokeWidth="1.6"><path d="M12 2l3 6.5 7 .9-5 4.9 1.2 7-6.4-3.4L5.6 21l1.2-7-5-4.9 7-.9z" /></svg>
      ))}
      <span style={{ fontSize: 12, color: c.muted, marginLeft: 3 }}>{value ? value.toFixed(1) : '—'}</span>
    </span>
  );
}

// ─────────── Talep eden: ürün + teslim değerlendirme modalı ───────────
function ProductRatingModal({ rating, c, onClose }) {
  const isMobile = useIsMobile();
  const [productStars, setProductStars] = React.useState(rating.product ? rating.product.stars : 0);
  const [deliveryStars, setDeliveryStars] = React.useState(rating.product ? rating.product.deliveryStars : 0);
  const [note, setNote] = React.useState(rating.product ? (rating.product.note || '') : '');

  function save() {
    if (!productStars) { alert('Ürün puanı verin.'); return; }
    if (!deliveryStars) { alert('Teslim deneyimi puanı verin.'); return; }
    window.__ratings.rateProduct(rating.requestId, { stars: productStars, deliveryStars, note: note.trim() });
    onClose();
  }
  const row = { marginBottom: 16 };
  const lbl = { fontSize: 12.5, color: c.muted, marginBottom: 8, display: 'block' };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 250, background: 'rgba(2,6,23,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.surface, border: `1px solid ${c.border}`, borderRadius: 18, width: 'min(460px, 100%)', padding: isMobile ? 18 : 24 }}>
        <div style={{ fontSize: 16, fontWeight: 700, color: c.text, marginBottom: 4 }}>Ürünü ve teslimi değerlendir</div>
        <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 16 }}>Talep {rating.requestId} · {(rating.items || []).map((it) => it.name).join(', ')}</div>
        <div style={row}><label style={lbl}>Ürün kalitesi / beklentiyi karşıladı mı?</label><StarRatingInput value={productStars} onChange={setProductStars} c={c} /></div>
        <div style={row}><label style={lbl}>Teslim deneyimi (süre, paketleme, eksiksizlik)</label><StarRatingInput value={deliveryStars} onChange={setDeliveryStars} c={c} /></div>
        <div style={row}><label style={lbl}>Notunuz (opsiyonel)</label><textarea value={note} onChange={(e) => setNote(e.target.value)} rows={3} style={{ ...inputBox(c), resize: 'vertical' }} placeholder="Deneyiminizi yazın..." /></div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={save} style={solidBtn(c.primary, isMobile)}>Değerlendirmeyi gönder</button>
          <button onClick={onClose} style={ghostBtn(c, isMobile)}>Vazgeç</button>
        </div>
      </div>
    </div>
  );
}

// ─────────── Yönetici: tedarikçi performans değerlendirme modalı ───────────
function SupplierRatingModal({ rating, c, onClose }) {
  const isMobile = useIsMobile();
  const [stars, setStars] = React.useState(rating.supplier ? rating.supplier.stars : 0);
  const [note, setNote] = React.useState(rating.supplier ? (rating.supplier.note || '') : '');
  function save() {
    if (!stars) { alert('Tedarikçi puanı verin.'); return; }
    window.__ratings.rateSupplier(rating.requestId, { stars, note: note.trim() });
    onClose();
  }
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 250, background: 'rgba(2,6,23,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.surface, border: `1px solid ${c.border}`, borderRadius: 18, width: 'min(460px, 100%)', padding: isMobile ? 18 : 24 }}>
        <div style={{ fontSize: 16, fontWeight: 700, color: c.text, marginBottom: 4 }}>Tedarikçiyi değerlendir</div>
        <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 16 }}><b>{rating.supplierName}</b> · Talep {rating.requestId} ({rating.requester})</div>
        <div style={{ marginBottom: 16 }}><label style={{ fontSize: 12.5, color: c.muted, marginBottom: 8, display: 'block' }}>Genel performans (kalite, iletişim, termin)</label><StarRatingInput value={stars} onChange={setStars} c={c} /></div>
        <div style={{ marginBottom: 16 }}><label style={{ fontSize: 12.5, color: c.muted, marginBottom: 8, display: 'block' }}>Not (opsiyonel)</label><textarea value={note} onChange={(e) => setNote(e.target.value)} rows={3} style={{ ...inputBox(c), resize: 'vertical' }} /></div>
        <div style={{ fontSize: 11.5, color: c.subtle, marginBottom: 14 }}>Bu puan tedarikçi kartının ortalama puanına işlenir.</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={save} style={solidBtn(c.primary, isMobile)}>Puanı kaydet</button>
          <button onClick={onClose} style={ghostBtn(c, isMobile)}>Vazgeç</button>
        </div>
      </div>
    </div>
  );
}

// ─────────── Yönetici Onay Kutusu: değerlendirme kartı ───────────
function ManagerRatingCard({ r, c, onRate }) {
  const isMobile = useIsMobile();
  return (
    <div style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, padding: isMobile ? 14 : 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: c.text }}>{r.supplierName || 'Tedarikçi'}</div>
          <div style={{ fontSize: 12, color: c.muted }}>Talep {r.requestId} · {r.requester} · {(r.items || []).map((it) => it.name).join(', ')}</div>
        </div>
        {r.supplier
          ? <StarsView value={r.supplier.stars} c={c} />
          : <span style={{ padding: '3px 10px', borderRadius: 999, fontSize: 11, fontWeight: 600, background: 'rgba(245,158,11,0.14)', color: '#B45309' }}>Bekliyor</span>}
      </div>
      {r.supplier
        ? <div style={{ fontSize: 12, color: c.muted }}>Değerlendirildi{r.supplier.note ? ` · ${r.supplier.note}` : ''}</div>
        : <button onClick={() => onRate(r)} style={{ ...solidBtn(c.primary, isMobile) }}>Tedarikçiyi değerlendir</button>}
    </div>
  );
}

Object.assign(window, { StarRatingInput, StarsView, ProductRatingModal, SupplierRatingModal, ManagerRatingCard });
