// Leads page
const Leads = () => {
  const { Icon, CategoryBadge, Button, SlidePanel } = window.SB_UI;
  const { fa } = window.SB_DATA;
  const [leads, setLeads] = useState([]);
  const [stats, setStats] = useState({});
  const [filter, setFilter] = useState('all');
  const [tagSearch, setTagSearch] = useState('');
  const [search, setSearch] = useState('');
  const [selected, setSelected] = useState(null);
  const [loading, setLoading] = useState(true);

  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { Authorization: `Bearer ${token}` };

  const load = (statusFilter) => {
    setLoading(true);
    const params = new URLSearchParams({ limit: 100 });
    if (statusFilter && statusFilter !== 'all') params.set('status', statusFilter);
    if (search) params.set('search', search);

    Promise.all([
      fetch(`/api/leads?${params}`, { headers }).then(r => r.json()),
      fetch('/api/leads/stats/overview', { headers }).then(r => r.json()),
    ]).then(([leadsData, statsData]) => {
      if (leadsData.success) setLeads(leadsData.data?.leads || []);
      if (statsData.success) setStats(statsData.data?.stats || {});
    }).finally(() => setLoading(false));
  };

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

  const filters = [
    { id: 'all',  label: 'همه',    count: stats.total || 0 },
    { id: 'hot',  label: 'داغ',    count: stats.hot   || 0 },
    { id: 'warm', label: 'گرم',    count: stats.warm  || 0 },
    { id: 'new',  label: 'جدید',   count: 0 },
    { id: 'cold', label: 'سرد',    count: stats.cold  || 0 },
    { id: 'buyer',label: 'خریدار', count: stats.buyer || 0 },
  ];

  const statusColor = { hot: '#F87171', warm: '#FB923C', new: '#60A5FA', cold: '#94A3B8', buyer: '#34D399', lost: '#6B7280' };
  const statusLabel = { hot: 'داغ', warm: 'گرم', new: 'جدید', cold: 'سرد', buyer: 'خریدار', lost: 'از دست رفته' };

  const filtered = tagSearch.trim()
    ? leads.filter(l => (l.tags || '').toLowerCase().includes(tagSearch.replace(/^#/, '').toLowerCase()))
    : leads;

  return (
    <div>
      <div className="row between gap-16" style={{ flexWrap: 'wrap' }}>
        <div className="pills">
          {filters.map(f => (
            <button key={f.id} className={`pill ${filter === f.id ? 'active' : ''}`} onClick={() => setFilter(f.id)}>
              {f.label}<span className="count mono">{fa(f.count)}</span>
            </button>
          ))}
        </div>
        <div className="row gap-8">
          <div style={{ position: 'relative' }}>
            <Icon name="search" size={13} style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }} />
            <input value={search} onChange={e => setSearch(e.target.value)} onKeyDown={e => e.key === 'Enter' && load(filter)}
              placeholder="جستجو..." style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 8, padding: '6px 30px 6px 12px', color: 'var(--text-1)', fontSize: 13, outline: 'none', width: 140, direction: 'rtl' }} />
          </div>
          <div style={{ position: 'relative' }}>
            <Icon name="hash" size={13} style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }} />
            <input value={tagSearch} onChange={e => setTagSearch(e.target.value)}
              placeholder="هشتک..." style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 8, padding: '6px 30px 6px 12px', color: 'var(--text-1)', fontSize: 13, outline: 'none', width: 130, direction: 'rtl' }} />
          </div>
          <Button kind="ghost" icon="download">خروجی</Button>
        </div>
      </div>

      <div className="card mt-16" style={{ padding: 0, overflow: 'hidden' }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-3)' }}>در حال بارگذاری...</div>
        ) : filtered.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-3)' }}>لیدی یافت نشد</div>
        ) : (
          <table className="table">
            <thead>
              <tr>
                <th>اسم</th>
                <th>شماره</th>
                <th>پلتفرم</th>
                <th>هشتک‌ها</th>
                <th>امتیاز</th>
                <th>وضعیت</th>
                <th>تاریخ</th>
                <th style={{ width: 40 }}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(l => (
                <tr key={l.id} onClick={() => setSelected(l)} style={{ cursor: 'pointer' }}>
                  <td>
                    <div className="row gap-10">
                      <div className="avatar" style={{ width: 30, height: 30, fontSize: 11 }}>
                        {(l.full_name || l.username || '؟').slice(0, 2)}
                      </div>
                      <div>
                        <div className="semi text-sm">{l.full_name || l.username || 'ناشناس'}</div>
                        {l.username && l.full_name && <div className="text-xs text-3">@{l.username}</div>}
                      </div>
                    </div>
                  </td>
                  <td className="mono text-sm text-2">{l.phone || '—'}</td>
                  <td>
                    <span style={{ fontSize: 12, padding: '2px 8px', borderRadius: 6, background: l.platform === 'telegram' ? 'rgba(41,182,246,0.15)' : 'rgba(99,102,241,0.15)', color: l.platform === 'telegram' ? '#29B6F6' : '#818CF8' }}>
                      {l.platform === 'telegram' ? 'تلگرام' : 'بله'}
                    </span>
                  </td>
                  <td>
                    <div className="row gap-4" style={{ flexWrap: 'wrap' }}>
                      {(l.tags || '').split(',').filter(Boolean).slice(0, 3).map(tag => (
                        <span key={tag} onClick={e => { e.stopPropagation(); setTagSearch(tag); }}
                          style={{ fontSize: 10, padding: '2px 6px', borderRadius: 20, background: 'rgba(99,102,241,0.18)', color: '#818CF8', cursor: 'pointer', whiteSpace: 'nowrap' }}>
                          #{tag}
                        </span>
                      ))}
                    </div>
                  </td>
                  <td>
                    <div className="row gap-6">
                      <div style={{ width: 60, height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.08)', overflow: 'hidden' }}>
                        <div style={{ width: `${(l.score || 0) * 10}%`, height: '100%', background: l.score >= 7 ? '#F87171' : l.score >= 4 ? '#FB923C' : '#60A5FA', borderRadius: 2 }} />
                      </div>
                      <span className="mono text-xs text-3">{l.score || 0}</span>
                    </div>
                  </td>
                  <td>
                    <span style={{ fontSize: 11, padding: '3px 8px', borderRadius: 6, background: (statusColor[l.status] || '#6B7280') + '20', color: statusColor[l.status] || '#6B7280' }}>
                      {statusLabel[l.status] || l.status}
                    </span>
                  </td>
                  <td className="mono text-xs text-3">{l.created_at ? l.created_at.slice(0, 10) : ''}</td>
                  <td>
                    <button className="icon-btn" style={{ width: 28, height: 28 }}><Icon name="chevron-left" size={13} /></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <SlidePanel open={!!selected} onClose={() => setSelected(null)}>
        {selected && <LeadDetail lead={selected} onClose={() => setSelected(null)} onUpdate={() => load(filter)} />}
      </SlidePanel>
    </div>
  );
};

const LeadDetail = ({ lead, onClose, onUpdate }) => {
  const { Icon, Button } = window.SB_UI;
  const [status, setStatus] = useState(lead.status);
  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };

  const statusLabel = { hot: 'داغ', warm: 'گرم', new: 'جدید', cold: 'سرد', buyer: 'خریدار', lost: 'از دست رفته' };
  const statusColor = { hot: '#F87171', warm: '#FB923C', new: '#60A5FA', cold: '#94A3B8', buyer: '#34D399', lost: '#6B7280' };

  const changeStatus = (s) => {
    setStatus(s);
    fetch(`/api/leads/${lead.id}`, { method: 'PUT', headers, body: JSON.stringify({ status: s }) })
      .then(() => onUpdate && onUpdate());
  };

  return (
    <>
      <div className="slide-head">
        <button className="icon-btn" onClick={onClose} style={{ width: 32, height: 32 }}><Icon name="x" size={14} /></button>
        <div style={{ flex: 1 }}>
          <div className="row gap-12">
            <div className="avatar" style={{ width: 38, height: 38, fontSize: 13 }}>
              {(lead.full_name || lead.username || '؟').slice(0, 2)}
            </div>
            <div>
              <div className="bold">{lead.full_name || lead.username || 'ناشناس'}</div>
              <div className="text-xs text-3 mono">{lead.phone || 'بدون شماره'}</div>
            </div>
          </div>
        </div>
        <span style={{ fontSize: 11, padding: '3px 10px', borderRadius: 6, background: (statusColor[status] || '#6B7280') + '20', color: statusColor[status] || '#6B7280' }}>
          {statusLabel[status] || status}
        </span>
      </div>

      <div className="slide-body">
        <div className="col gap-24">

          <section>
            <div className="text-xs text-3 semi" style={{ marginBottom: 10, letterSpacing: 0.04, textTransform: 'uppercase' }}>اطلاعات</div>
            <div className="card" style={{ padding: 14 }}>
              <div className="grid grid-2 gap-12">
                <Info label="پلتفرم" value={lead.platform === 'telegram' ? 'تلگرام' : 'بله'} />
                <Info label="یوزرنیم" value={lead.username ? '@' + lead.username : '—'} mono />
                <Info label="امتیاز" value={`${lead.score || 0} از ۱۰`} />
                <Info label="تاریخ ثبت" value={lead.created_at ? lead.created_at.slice(0, 10) : '—'} mono />
              </div>
            </div>
          </section>

          {lead.tags && lead.tags.trim() && (
            <section>
              <div className="text-xs text-3 semi" style={{ marginBottom: 10, letterSpacing: 0.04, textTransform: 'uppercase' }}>هشتک‌ها</div>
              <div className="row gap-6" style={{ flexWrap: 'wrap' }}>
                {lead.tags.split(',').filter(Boolean).map(tag => (
                  <span key={tag} style={{ fontSize: 12, padding: '4px 10px', borderRadius: 20, background: 'rgba(99,102,241,0.18)', color: '#818CF8' }}>
                    #{tag}
                  </span>
                ))}
              </div>
            </section>
          )}

          <section>
            <div className="text-xs text-3 semi" style={{ marginBottom: 10, letterSpacing: 0.04, textTransform: 'uppercase' }}>تغییر وضعیت</div>
            <div className="row gap-8" style={{ flexWrap: 'wrap' }}>
              {['hot', 'warm', 'new', 'cold', 'buyer', 'lost'].map(s => (
                <button key={s} onClick={() => changeStatus(s)}
                  style={{
                    padding: '5px 14px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none',
                    background: status === s ? (statusColor[s] + '30') : 'rgba(255,255,255,0.06)',
                    color: status === s ? statusColor[s] : 'var(--text-2)',
                  }}>
                  {statusLabel[s]}
                </button>
              ))}
            </div>
          </section>

          <div className="row gap-8 mt-4">
            <Button kind="primary" icon="phone">تماس بگیر</Button>
            <Button kind="secondary" icon="message-circle">مشاهده مکالمه</Button>
          </div>
        </div>
      </div>
    </>
  );
};

const Info = ({ label, value, mono }) => (
  <div className="col gap-4">
    <div className="text-xs text-3">{label}</div>
    <div className={`text-sm semi ${mono ? 'mono' : ''}`}>{value}</div>
  </div>
);

window.Leads = Leads;
