// ── Inbox: conversation list + thread ─────────────────────────

const INBOX_FILTERS = [
  { id: 'all',      label: 'همه' },
  { id: 'open',     label: 'باز' },
  { id: 'pending',  label: 'در انتظار' },
  { id: 'resolved', label: 'حل‌شده' },
];

function AssistantBar({ on, onToggle }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, padding: '11px 14px', marginBottom: 12,
      borderRadius: 14, border: '1px solid ' + (on ? 'var(--accent)' : 'var(--line)'),
      background: on ? 'var(--surface)' : 'var(--field)',
    }}>
      <div style={{
        width: 34, height: 34, borderRadius: 10, flexShrink: 0,
        background: on ? 'var(--accent)' : 'var(--surface-2)', color: on ? 'var(--accent-ink)' : 'var(--ink-2)',
        border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name="robot" size={19} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--ink)' }}>دستیار فروش</div>
        <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>
          {on ? 'روشن — پاسخ‌ها خودکار با کمک AI ارسال می‌شوند' : 'خاموش — پاسخ‌دهی دستی است'}
        </div>
      </div>
      <button onClick={onToggle} style={{
        width: 46, height: 28, borderRadius: 999, border: 'none', cursor: 'pointer', position: 'relative',
        background: on ? 'var(--accent)' : 'var(--surface-2)', transition: 'background .2s', flexShrink: 0,
      }}>
        <span style={{
          position: 'absolute', top: 3, width: 22, height: 22, borderRadius: '50%', background: '#fff',
          boxShadow: '0 1px 3px rgba(0,0,0,0.25)', transition: 'all .2s', right: on ? 3 : 21,
        }} />
      </button>
    </div>
  );
}

function InboxList({ convs, onOpen, assistant, onToggleAssistant }) {
  const [filter, setFilter] = useState('all');
  const [q, setQ] = useState('');
  const counts = {
    all: convs.length,
    open: convs.filter(c => c.status === 'open').length,
    pending: convs.filter(c => c.status === 'pending').length,
    resolved: convs.filter(c => c.status === 'resolved').length,
  };
  let list = filter === 'all' ? convs : convs.filter(c => c.status === filter);
  if (q.trim()) {
    list = list.filter(c => {
      const cu = CUSTOMERS.find(x => x.id === c.customerId);
      return cu.name.includes(q) || c.preview.includes(q);
    });
  }
  return (
    <div style={{ padding: '0 14px 16px' }}>
      {/* sales assistant toggle */}
      <AssistantBar on={assistant} onToggle={onToggleAssistant} />
      {/* search */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px',
        background: 'var(--field)', borderRadius: 12, border: '1px solid var(--line)',
        color: 'var(--ink-3)', marginBottom: 12,
      }}>
        <Icon name="search" size={18} />
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="جستجوی مشتری یا پیام…" style={{
          flex: 1, border: 'none', background: 'none', outline: 'none',
          font: 'inherit', fontSize: 14, color: 'var(--ink)',
        }} />
      </div>
      {/* filters */}
      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4, marginBottom: 6 }} className="noscroll">
        {INBOX_FILTERS.map(f => (
          <Chip key={f.id} active={filter === f.id} onClick={() => setFilter(f.id)} count={counts[f.id]}>{f.label}</Chip>
        ))}
      </div>
      {/* list */}
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {list.map(c => {
          const cu = CUSTOMERS.find(x => x.id === c.customerId);
          return (
            <div key={c.id} onClick={() => onOpen(c.id)} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '13px 4px',
              borderBottom: '1px solid var(--line)', cursor: 'pointer',
            }}>
              <Avatar mono={cu.mono} size={46} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <StatusDot status={c.status} />
                  <span style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--ink)', whiteSpace: 'nowrap' }}>{cu.name}</span>
                  <span style={{ marginRight: 'auto', fontSize: 11, color: 'var(--ink-3)' }}>{c.time}</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 3 }}>
                  <span style={{ flex: 1, fontSize: 12.5, color: c.unread ? 'var(--ink)' : 'var(--ink-2)', fontWeight: c.unread ? 500 : 400, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.preview}</span>
                  {c.unread > 0 && <span style={{
                    background: 'var(--accent)', color: 'var(--accent-ink)', fontSize: 10.5,
                    fontWeight: 700, minWidth: 18, height: 18, borderRadius: 9, padding: '0 5px',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{fa(c.unread)}</span>}
                </div>
                {(() => { const fu = convFollowup(c); return fu ? (
                  <div style={{
                    display: 'flex', alignItems: 'center', gap: 5, marginTop: 6,
                    background: 'rgba(217,83,79,0.10)', borderRadius: 8, padding: '5px 8px',
                  }}>
                    <Icon name="clock" size={12} sw={2} style={{ color: '#d9534f' }} />
                    <span style={{ fontSize: 11, fontWeight: 700, color: '#d9534f', flexShrink: 0 }}>نیاز به پیگیری:</span>
                    <span style={{ fontSize: 11, color: 'var(--ink-2)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{fu.reason}</span>
                  </div>
                ) : null; })()}
              </div>
            </div>
          );
        })}
        {list.length === 0 && (
          <div style={{ textAlign: 'center', color: 'var(--ink-3)', fontSize: 13, padding: '48px 0' }}>گفتگویی یافت نشد</div>
        )}
      </div>
    </div>
  );
}

function nowStamp() {
  const n = new Date();
  return fa(n.getHours()) + ':' + fa(String(n.getMinutes()).padStart(2, '0'));
}

function ConversationView({ conv, onBack, onOpenCustomer, onUpdate, assistant }) {
  const cu = CUSTOMERS.find(x => x.id === conv.customerId);
  const [msgs, setMsgs] = useState(conv.messages);
  const [text, setText] = useState('');
  const [showQR, setShowQR] = useState(false);
  const endRef = useRef(null);
  const autoReplied = useRef(false);
  useEffect(() => { endRef.current && endRef.current.scrollTo({ top: endRef.current.scrollHeight }); }, [msgs]);

  // دستیار فروش: اگر روشن باشد و آخرین پیام از مشتری بی‌پاسخ مانده، خودکار پاسخ می‌دهد
  useEffect(() => {
    if (!assistant || autoReplied.current) return;
    const last = msgs[msgs.length - 1];
    if (last && last.from === 'them') {
      autoReplied.current = true;
      setMsgs(m => [...m, { typing: true }]);
      const reply = aiReplyFor(conv);
      setTimeout(() => setMsgs(m => m.filter(x => !x.typing).concat({ from: 'me', ai: true, text: reply, t: nowStamp() })), 1400);
    }
  }, [assistant]);

  function send(t) {
    const v = (t ?? text).trim();
    if (!v) return;
    const now = new Date();
    const stamp = fa(now.getHours()) + ':' + fa(String(now.getMinutes()).padStart(2, '0'));
    setMsgs(m => [...m, { from: 'me', text: v, t: stamp }]);
    setText(''); setShowQR(false);
    onUpdate && onUpdate(conv.id, v);
    // ارسال واقعی به روبیکا (اگر سرور در دسترس باشد)
    fetch(`/api/conversations/${conv.id}/reply`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ text: v }),
    }).then(() => { if (typeof window.loadRealData === 'function') window.loadRealData(); })
      .catch(() => { /* حالت پیش‌نمایش بدون سرور */ });
  }

  const st = STATUS[conv.status];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* header */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px 12px',
        borderBottom: '1px solid var(--line)', background: 'var(--surface)',
      }}>
        <button onClick={onBack} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink)', padding: 4, display: 'flex' }}>
          <Icon name="chevron-right" size={24} />
        </button>
        <div onClick={() => onOpenCustomer(cu.id)} style={{ display: 'flex', alignItems: 'center', gap: 10, flex: 1, cursor: 'pointer', minWidth: 0 }}>
          <Avatar mono={cu.mono} size={38} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)' }}>{cu.name}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11.5, color: 'var(--ink-2)' }}>
              <StatusDot status={conv.status} size={7} />{st.label} · {conv.assignee}
            </div>
          </div>
        </div>
        <button onClick={() => onOpenCustomer(cu.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-2)', padding: 4, display: 'flex' }}>
          <Icon name="info" size={22} />
        </button>
      </div>

      {/* messages */}
      <div ref={endRef} style={{ flex: 1, overflowY: 'auto', padding: '16px 14px', display: 'flex', flexDirection: 'column', gap: 8, background: 'var(--bg)' }}>
        <div style={{ textAlign: 'center', fontSize: 10.5, color: 'var(--ink-3)', margin: '0 0 6px' }}>امروز</div>
        {assistant && (
          <div style={{
            alignSelf: 'center', display: 'inline-flex', alignItems: 'center', gap: 6,
            background: 'var(--surface)', border: '1px solid var(--accent)', borderRadius: 999,
            padding: '5px 12px', marginBottom: 4, color: 'var(--ink-2)', fontSize: 11, fontWeight: 600,
          }}>
            <Icon name="robot" size={13} style={{ color: 'var(--accent)' }} />دستیار فروش روشن است
          </div>
        )}
        {msgs.map((m, i) => m.typing ? (
          <div key={i} style={{ alignSelf: 'flex-start', background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 14, borderBottomRightRadius: 4, padding: '11px 14px', display: 'flex', gap: 4 }}>
            {[0,1,2].map(d => <span key={d} className="td" style={{ animationDelay: d*0.18+'s' }} />)}
          </div>
        ) : (
          <div key={i} style={{
            alignSelf: m.from === 'me' ? 'flex-end' : 'flex-start', maxWidth: '78%',
            background: m.from === 'me' ? 'var(--accent)' : 'var(--surface)',
            color: m.from === 'me' ? 'var(--accent-ink)' : 'var(--ink)',
            border: m.from === 'me' ? 'none' : '1px solid var(--line)',
            borderRadius: 16, padding: '9px 13px',
            borderBottomRightRadius: m.from === 'me' ? 4 : 16,
            borderBottomLeftRadius: m.from === 'me' ? 16 : 4,
          }}>
            {m.ai && (
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 9.5, fontWeight: 700, opacity: 0.7, marginBottom: 3 }}>
                <Icon name="robot" size={11} />دستیار
              </div>
            )}
            <div style={{ fontSize: 13.5, lineHeight: 1.6 }}>{m.text}</div>
            <div style={{ fontSize: 9.5, opacity: 0.55, marginTop: 3, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 3, justifyContent: 'flex-start' }}>
              {m.from === 'me' && <Icon name="check-double" size={12} />}{m.t}
            </div>
          </div>
        ))}
      </div>

      {/* پیش‌نویس هوشمند دستیار — وقتی پیام مشتری بی‌پاسخ است */}
      {(() => {
        const last = msgs[msgs.length - 1];
        if (!last || last.from !== 'them' || last.typing) return null;
        const suggestion = aiReplyFor(conv);
        if (!suggestion) return null;
        return (
          <div style={{ padding: '8px 14px 0', background: 'var(--surface)' }}>
            <div style={{
              border: '1px solid var(--line)', borderRadius: 14, padding: '10px 12px',
              background: 'var(--surface-2)', display: 'flex', flexDirection: 'column', gap: 8,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, fontWeight: 700, color: 'var(--ink-2)' }}>
                <Icon name="robot" size={13} /> پیش‌نویس دستیار هوشمند
              </div>
              <div style={{ fontSize: 13, lineHeight: 1.7, color: 'var(--ink)' }}>{suggestion}</div>
              <div style={{ display: 'flex', gap: 8 }}>
                <button onClick={() => send(suggestion)} style={{
                  flex: 1, font: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer',
                  background: 'var(--accent)', color: 'var(--accent-ink)', border: 'none',
                  borderRadius: 10, padding: '9px 0', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
                }}><Icon name="send" size={15} style={{ transform: 'scaleX(-1)' }} /> ارسال</button>
                <button onClick={() => setText(suggestion)} style={{
                  font: 'inherit', fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
                  background: 'var(--field)', color: 'var(--ink-2)', border: '1px solid var(--line)',
                  borderRadius: 10, padding: '9px 16px',
                }}>ویرایش</button>
              </div>
            </div>
          </div>
        );
      })()}

      {/* quick replies */}
      {showQR && (
        <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '10px 14px 4px', background: 'var(--surface)' }} className="noscroll">
          {QUICK_REPLIES.map((q, i) => (
            <button key={i} onClick={() => send(q)} style={{
              font: 'inherit', fontSize: 12.5, color: 'var(--ink)', background: 'var(--surface-2)',
              border: '1px solid var(--line)', borderRadius: 999, padding: '8px 13px', whiteSpace: 'nowrap', cursor: 'pointer', flexShrink: 0,
            }}>{q}</button>
          ))}
        </div>
      )}

      {/* input */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px 12px', borderTop: '1px solid var(--line)', background: 'var(--surface)' }}>
        <button onClick={() => setShowQR(s => !s)} style={{
          width: 40, height: 40, borderRadius: '50%', flexShrink: 0, cursor: 'pointer',
          background: showQR ? 'var(--accent)' : 'var(--field)', color: showQR ? 'var(--accent-ink)' : 'var(--ink-2)',
          border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="bolt" size={19} />
        </button>
        <input value={text} onChange={e => setText(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()}
          placeholder="پیام بنویسید…" style={{
            flex: 1, border: '1px solid var(--line)', background: 'var(--field)', borderRadius: 22,
            padding: '11px 16px', font: 'inherit', fontSize: 14, color: 'var(--ink)', outline: 'none',
          }} />
        <button onClick={() => send()} disabled={!text.trim()} style={{
          width: 42, height: 42, borderRadius: '50%', flexShrink: 0,
          background: text.trim() ? 'var(--accent)' : 'var(--surface-2)',
          color: text.trim() ? 'var(--accent-ink)' : 'var(--ink-3)',
          border: 'none', cursor: text.trim() ? 'pointer' : 'default',
          display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all .15s',
        }}>
          <Icon name="send" size={20} style={{ transform: 'scaleX(-1)' }} />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { InboxList, ConversationView });
