// Demand / Talep Listem — Faz 5.3a (planlı/toplu satınalma — 1. parça)
// Kullanıcının katalogdan "Döneme Ekle" ile biriktirdiği 6 aylık ihtiyaç listesi (forecast).
// SİPARİŞ DEĞİL — modül yöneticisi sonra (5.3b) birleştirip bütçe çıkarır.
// Anlık (spot) sepet akışından tamamen ayrıdır.

function DemandPeriodChip({ period, c }) {
  const meta = (window.DEMAND_PERIOD_STATUS || {})[period.status] || { label: period.status, color: c.muted, bg: c.chipBg };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '3px 10px', borderRadius: 999,
      fontSize: 11.5, fontWeight: 600,
      color: meta.color, background: meta.bg,
    }}>
      <span style={{ width: 7, height: 7, borderRadius: 999, background: meta.color }} />
      {meta.label}
    </span>
  );
}

// Tek bir dönem-talebi kalemi (düzenlenebilir: adet + not + sil)
function DemandLineRow({ it, c, readOnly, onQty, onNote, onRemove }) {
  const lineTotal = (it.priceNet || 0) * (it.qty || 1);
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: '56px 1fr auto',
      gap: 14, alignItems: 'start',
      padding: '14px 0', borderTop: `1px solid ${c.borderSoft}`,
    }}>
      <div style={{ width: 56, height: 56, borderRadius: 10, overflow: 'hidden', background: c.chipBg, flexShrink: 0 }}>
        <ProductPlaceholder kind={it.imgKind} c={c} imgSrc={window.productImgSrc ? window.productImgSrc(it) : null} />
      </div>

      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: '0.05em', color: c.muted, textTransform: 'uppercase' }}>
          {it.brand}{it.model ? ` · ${it.model}` : ''}
        </div>
        <div style={{ fontSize: 14, fontWeight: 600, color: c.text, marginTop: 2, lineHeight: 1.35 }}>{it.name}</div>
        <div style={{ fontSize: 12, color: c.subtle, marginTop: 3 }}>
          Birim: {formatTL(it.priceNet)}{it.priceUnit ? ` / ${it.priceUnit}` : ''} · KDV hariç
        </div>
        {!readOnly && (
          <input
            value={it.note || ''}
            onChange={(e) => onNote(it.id, e.target.value)}
            placeholder="Not (opsiyonel) — örn. yıl boyu kademeli, Q3'te yoğun"
            style={{
              marginTop: 8, width: '100%', maxWidth: 420, boxSizing: 'border-box',
              padding: '7px 10px', borderRadius: 8,
              border: `1px solid ${c.border}`, background: c.bg, color: c.text,
              fontSize: 12.5, fontFamily: 'inherit', outline: 'none',
            }} />
        )}
        {readOnly && it.note && (
          <div style={{ marginTop: 6, fontSize: 12, color: c.muted, fontStyle: 'italic' }}>“{it.note}”</div>
        )}
      </div>

      <div style={{ textAlign: 'right', minWidth: 120 }}>
        {readOnly ? (
          <div style={{ fontSize: 13, fontWeight: 600, color: c.text }}>{it.qty} adet</div>
        ) : (
          <div style={{ display: 'inline-flex', alignItems: 'center', border: `1px solid ${c.border}`, borderRadius: 8, overflow: 'hidden' }}>
            <button onClick={() => onQty(it.id, (it.qty || 1) - 1)} style={qtyBtnStyle(c)}>−</button>
            <span style={{ minWidth: 34, textAlign: 'center', fontSize: 13.5, fontWeight: 600, color: c.text }}>{it.qty}</span>
            <button onClick={() => onQty(it.id, (it.qty || 1) + 1)} style={qtyBtnStyle(c)}>+</button>
          </div>
        )}
        <div style={{ fontSize: 14, fontWeight: 700, color: c.text, marginTop: 8 }}>{formatTL(lineTotal)}</div>
        {!readOnly && (
          <button onClick={() => onRemove(it.id)} style={{
            marginTop: 6, appearance: 'none', border: 'none', background: 'transparent',
            color: c.danger || '#EF4444', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
          }}>Çıkar</button>
        )}
      </div>
    </div>
  );
}

function qtyBtnStyle(c) {
  return {
    appearance: 'none', border: 'none', cursor: 'pointer',
    background: c.chipBg, color: c.text,
    width: 30, height: 30, fontSize: 16, fontWeight: 700, lineHeight: '30px',
    fontFamily: 'inherit',
  };
}

function DemandPage({ initialDark = false, user }) {
  const [dark, setDark] = React.useState(initialDark);
  React.useEffect(() => { setDark(initialDark); }, [initialDark]);
  const isMobile = useIsMobile();
  const c = catalogTheme(dark);

  const currentUser = useCurrentUser() || user;
  const demandItems = useDemandSnapshot();
  const periods = window.DEMAND_PERIODS || [];
  const active = window.activeDemandPeriod && window.activeDemandPeriod();
  const [periodId, setPeriodId] = React.useState(active ? active.id : (periods[0] && periods[0].id));
  const period = periods.find((p) => p.id === periodId) || active || periods[0];
  const readOnly = !period || period.status !== 'collecting';

  const meId = currentUser ? currentUser.id : 'anon';
  const myItems = demandItems.filter((d) => d.by === meId && period && d.periodId === period.id);

  // Modüle göre grupla (sepetin aksine dönem talebi birden çok modül içerebilir)
  const MODS = window.MODULES || {};
  const groups = {};
  myItems.forEach((it) => { (groups[it.module || 'it'] = groups[it.module || 'it'] || []).push(it); });
  const groupKeys = Object.keys(groups);

  const netTotal = myItems.reduce((s, it) => s + (it.priceNet || 0) * (it.qty || 1), 0);
  const grossTotal = Math.round(netTotal * 1.2);
  const totalQty = myItems.reduce((s, it) => s + (it.qty || 1), 0);

  const dmd = window.__demand || {};

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

      <div style={{ padding: isMobile ? '16px 16px 40px' : '28px 32px 48px', maxWidth: 920, width: '100%', margin: '0 auto', boxSizing: 'border-box' }}>
        {/* Başlık */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
          <h1 style={{ margin: 0, fontSize: 24, fontWeight: 700, letterSpacing: '-0.01em' }}>🗓️ Talep Listem</h1>
          <span style={{ fontSize: 13, color: c.muted }}>6 aylık ihtiyaç planı</span>
        </div>

        {/* Dönem sekmeleri */}
        {periods.length > 1 && (
          <div style={{ display: 'flex', gap: 8, marginTop: 16, flexWrap: 'wrap' }}>
            {periods.map((p) => {
              const sel = p.id === periodId;
              return (
                <button key={p.id} onClick={() => setPeriodId(p.id)} style={{
                  appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
                  padding: '8px 14px', borderRadius: 10,
                  border: `1px solid ${sel ? c.primary : c.border}`,
                  background: sel ? (dark ? 'rgba(37,99,235,0.18)' : 'rgba(37,99,235,0.08)') : 'transparent',
                  color: sel ? c.primary : c.text, fontSize: 13, fontWeight: 600,
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                }}>
                  {p.label}
                  <DemandPeriodChip period={p} c={c} />
                </button>
              );
            })}
          </div>
        )}

        {/* Bilgi bandı: bu liste sipariş DEĞİL */}
        <div style={{
          marginTop: 16, padding: '14px 16px', borderRadius: 12,
          background: dark ? 'rgba(37,99,235,0.12)' : 'rgba(37,99,235,0.06)',
          border: `1px solid ${c.primary}33`,
          display: 'flex', gap: 12, alignItems: 'flex-start',
        }}>
          <span style={{ fontSize: 18 }}>ℹ️</span>
          <div style={{ fontSize: 13, lineHeight: 1.55, color: c.text }}>
            <b>Bu liste sipariş değildir.</b> {period ? period.label : ''} dönemi için <b>tahmini ihtiyacınızı</b> bildiriyorsunuz.
            Toplama kapandığında modül yöneticisi tüm departmanların listelerini <b>birleştirip bütçe</b> oluşturur ve
            <b> toplu satın alma</b> yapar. Acil/plansız ihtiyaçlar için normal <b>sepet</b> akışını kullanın.
            {period && period.closesAt && period.status === 'collecting' &&
              <> <span style={{ color: c.muted }}>Son toplama: <b>{period.closesAt}</b>.</span></>}
          </div>
        </div>

        {/* Kapalı/arşiv dönem uyarısı */}
        {readOnly && period && (
          <div style={{ marginTop: 14, fontSize: 13, color: c.muted, fontStyle: 'italic' }}>
            Bu dönemde toplama kapalı — liste salt-okunur.
          </div>
        )}

        {/* İçerik */}
        {myItems.length === 0 ? (
          <div style={{
            marginTop: 24, padding: '48px 24px', textAlign: 'center',
            border: `1px dashed ${c.border}`, borderRadius: 14, color: c.muted,
          }}>
            <div style={{ fontSize: 32, marginBottom: 8 }}>🗓️</div>
            <div style={{ fontSize: 15, fontWeight: 600, color: c.text }}>Bu dönem için henüz ihtiyaç eklemediniz</div>
            <div style={{ fontSize: 13, marginTop: 6 }}>Katalogdan ürünlerde <b>“Döneme Ekle”</b> butonunu kullanın.</div>
            {!readOnly && (
              <button onClick={() => window.__navigate && window.__navigate('catalog')} style={{
                marginTop: 16, appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
                padding: '10px 18px', borderRadius: 10, background: c.primary, color: '#fff', fontSize: 13.5, fontWeight: 600,
              }}>Kataloğa git</button>
            )}
          </div>
        ) : (
          <>
            <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 20 }}>
              {groupKeys.map((mid) => {
                const mod = MODS[mid] || { name: mid, color: c.primary };
                return (
                  <div key={mid} style={{
                    background: c.card, border: `1px solid ${c.border}`, borderRadius: 14,
                    padding: isMobile ? '14px 16px' : '18px 22px',
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ width: 9, height: 9, borderRadius: 999, background: mod.color || c.primary }} />
                      <span style={{ fontSize: 13.5, fontWeight: 700, color: c.text }}>{mod.name}</span>
                      <span style={{ fontSize: 12, color: c.muted }}>· {groups[mid].length} kalem</span>
                    </div>
                    {groups[mid].map((it) => (
                      <DemandLineRow key={it.id} it={it} c={c} readOnly={readOnly}
                        onQty={dmd.setQty} onNote={dmd.setNote} onRemove={dmd.remove} />
                    ))}
                  </div>
                );
              })}
            </div>

            {/* Özet */}
            <div style={{
              marginTop: 20, padding: '18px 22px', borderRadius: 14,
              background: c.card, border: `1px solid ${c.border}`,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12,
            }}>
              <div style={{ fontSize: 13, color: c.muted }}>
                {totalQty} adet · {myItems.length} kalem · {groupKeys.length} modül
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 12, color: c.muted }}>Tahmini tutar (KDV hariç)</div>
                <div style={{ fontSize: 22, fontWeight: 700, color: c.text }}>{formatTL(netTotal)}</div>
                <div style={{ fontSize: 12, color: c.subtle, marginTop: 2 }}>KDV dahil {formatTL(grossTotal)}</div>
              </div>
            </div>

            {!readOnly && (
              <div style={{ marginTop: 14, display: 'flex', justifyContent: 'flex-end' }}>
                <button onClick={() => { if (window.confirm('Bu dönemdeki tüm ihtiyaç kalemleriniz silinsin mi?')) dmd.clearMine(period.id); }} style={{
                  appearance: 'none', border: `1px solid ${c.border}`, background: 'transparent',
                  color: c.muted, fontSize: 12.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                  padding: '8px 14px', borderRadius: 10,
                }}>Listemi temizle</button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { DemandPage, DemandLineRow, DemandPeriodChip });
