// Dashboard page — real stats
const Dashboard = () => {
  const { Icon, Badge, CategoryBadge, Donut, LineChart, Button, SlidePanel } = window.SB_UI;
  const { fa } = window.SB_DATA;
  const [leadStats, setLeadStats] = useState(null);
  const [convStats, setConvStats] = useState(null);
  const [recentLeads, setRecentLeads] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedLead, setSelectedLead] = useState(null);
  const [leadFilter, setLeadFilter] = useState('all'); // all | hot | follow_up | new

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

  const loadLeads = (f) => {
    const params = new URLSearchParams({ limit: 10 });
    if (f && f !== 'all') params.set('status', f);
    fetch(`/api/leads?${params}`, { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setRecentLeads(d.data.leads || []); });
  };

  useEffect(() => {
    Promise.all([
      fetch('/api/leads/stats/overview', { headers }).then(r => r.json()),
      fetch('/api/conversations/stats/overview', { headers }).then(r => r.json()),
    ]).then(([ls, cs]) => {
      if (ls.success) setLeadStats(ls.data.stats);
      if (cs.success) setConvStats(cs.data.stats);
    }).finally(() => setLoading(false));
    loadLeads('all');
  }, []);

  useEffect(() => { loadLeads(leadFilter); }, [leadFilter]);

  const STATUS_COLOR = {
    buyer: '#00D4AA', new: '#A5B4FC', follow_up: '#818CF8', interested: '#38BDF8',
    scheduled: '#A78BFA', lost: '#6B7280', cancelled: '#EF4444', bad_number: '#DC2626',
  };
  const STATUS_LABEL = {
    buyer: '💰 خریدار', new: '✨ جدید', follow_up: '🔄 پیگیری', interested: '👀 علاقه‌مند',
    scheduled: '📅 زمان‌بندی', lost: '❌ از دست رفته', cancelled: '🚫 کنسل',
  };
  const OUTCOME_LABEL = {
    answered: { label: 'جواب داد', color: '#34D399', icon: '✅' },
    no_answer: { label: 'بی‌پاسخ', color: '#F87171', icon: '📵' },
    call_later: { label: 'بعداً زنگ', color: '#818CF8', icon: '⏰' },
    follow_up: { label: 'پیگیری', color: '#818CF8', icon: '🔄' },
    scheduled: { label: 'زمان خرید', color: '#A78BFA', icon: '📅' },
    sold: { label: 'فروش شد', color: '#34D399', icon: '💰' },
    not_interested: { label: 'علاقه نداشت', color: '#6B7280', icon: '❌' },
    cancelled: { label: 'کنسل کرد', color: '#EF4444', icon: '🚫' },
    bad_number: { label: 'شماره اشتباه', color: '#DC2626', icon: '☎️' },
  };

  const statCards = leadStats && convStats ? [
    { label: 'مکالمات امروز', value: fa(convStats.today || 0), delta: `${fa(convStats.active || 0)} فعال`, icon: 'message-square', color: '#6C63FF' },
    { label: 'کل لیدها', value: fa(leadStats.total || 0), delta: `+${fa(leadStats.today || 0)} امروز`, icon: 'users', color: '#10B981' },
    { label: 'خریداران', value: fa(leadStats.buyer || 0), delta: leadStats.total > 0 ? `${fa(Math.round((leadStats.buyer / leadStats.total) * 100))}٪ از کل` : '۰٪', icon: 'trending-up', color: '#10B981' },
    { label: 'کل پیام‌ها', value: fa(convStats.total_messages || 0), delta: `${fa(convStats.total || 0)} مکالمه`, icon: 'hash', color: '#F59E0B' },
  ] : [];

  const donut = leadStats ? [
    { value: leadStats.new || 0, color: '#A5B4FC', label: 'جدید' },
    { value: leadStats.follow_up || 0, color: '#818CF8', label: 'پیگیری' },
    { value: leadStats.interested || 0, color: '#38BDF8', label: 'علاقه‌مند' },
    { value: leadStats.buyer || 0, color: '#00D4AA', label: 'خریدار' },
  ].filter(d => d.value > 0) : [];

  const chart = [82, 96, 115, 102, 134, 128, convStats?.today || 0];

  const LEAD_FILTERS = [
    { id: 'all',       label: 'همه',     count: leadStats?.total || 0 },
    { id: 'follow_up',  label: '🔄 پیگیری',    count: leadStats?.follow_up  || 0 },
    { id: 'new',        label: '✨ جدید',       count: leadStats?.new        || 0 },
  ];

  // تبدیل تاریخ به شمسی
  const toShamsi = (dateStr) => {
    if (!dateStr) return '—';
    try {
      const d = new Date(dateStr);
      const gy = d.getFullYear(), gm = d.getMonth()+1, gd = d.getDate();
      const g_d = [31,28,31,30,31,30,31,31,30,31,30,31];
      let gy2 = gm > 2 ? gy+1 : gy;
      let days = 355666 + (365*gy) + Math.floor((gy2+3)/4) - Math.floor((gy2+99)/100) + Math.floor((gy2+399)/400) + gd;
      for (let i = 0; i < gm-1; i++) days += g_d[i];
      let jy = -1595 + 33*Math.floor(days/12053); days %= 12053;
      jy += 4*Math.floor(days/1461); days %= 1461;
      if (days > 365) { jy += Math.floor((days-1)/365); days = (days-1)%365; }
      let jm, jdd;
      if (days < 186) { jm = 1 + Math.floor(days/31); jdd = 1 + (days%31); }
      else { days -= 186; jm = 7 + Math.floor(days/30); jdd = 1 + (days%30); }
      const hh = String(d.getHours()).padStart(2,'0');
      const mm = String(d.getMinutes()).padStart(2,'0');
      return `${jy}/${String(jm).padStart(2,'0')}/${String(jdd).padStart(2,'0')} — ${hh}:${mm}`;
    } catch { return (dateStr||'').slice(0,16); }
  };

  const LeadDetailComp = window.SB_LeadDetail;

  return (
    <div>
      {/* ─── کارت‌های آمار ─── */}
      {loading ? (
        <div className="grid grid-4">
          {[1,2,3,4].map(i => (
            <div key={i} className="stat-card" style={{ opacity: 0.4 }}>
              <div className="stat-label"><div className="stat-icon" /><span>در حال بارگذاری...</span></div>
              <div className="stat-value">—</div>
            </div>
          ))}
        </div>
      ) : (
        <div className="grid grid-4">
          {statCards.map((s, i) => (
            <div key={i} className="stat-card">
              <div className="stat-label">
                <div className="stat-icon" style={{ background: s.color + '22' }}>
                  <Icon name={s.icon} size={16} color={s.color} />
                </div>
                <span>{s.label}</span>
              </div>
              <div className="stat-value">{s.value}</div>
              <span className="stat-delta"><Icon name="trending-up" size={11} strokeWidth={2.4} />{s.delta}</span>
            </div>
          ))}
        </div>
      )}

      {/* ─── نمودارها ─── */}
      <div className="grid mt-24" style={{ gridTemplateColumns: '1.5fr 1fr' }}>
        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title"><Icon name="line-chart" size={16} color="var(--primary-2)" />مکالمات ۷ روز گذشته</div>
              <div className="card-sub">{convStats ? `امروز: ${fa(convStats.today)} مکالمه • کل: ${fa(convStats.total)}` : 'در حال بارگذاری...'}</div>
            </div>
            <div className="row gap-8">
              <span className="pill active text-xs" style={{ padding: '4px 10px' }}>هفته</span>
              <span className="pill text-xs" style={{ padding: '4px 10px' }}>ماه</span>
            </div>
          </div>
          <LineChart data={chart} height={240} />
        </div>

        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title"><Icon name="pie-chart" size={16} color="var(--primary-2)" />دسته‌بندی لیدها</div>
              <div className="card-sub">{leadStats ? `${fa(leadStats.total)} لید در سیستم` : 'در حال بارگذاری...'}</div>
            </div>
          </div>
          {donut.length > 0 ? (
            <div className="row gap-24" style={{ alignItems: 'center', justifyContent: 'center' }}>
              <div style={{ position: 'relative' }}>
                <Donut segments={donut} size={170} stroke={22} />
                <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', textAlign: 'center' }}>
                  <div>
                    <div className="text-xs text-3">مجموع</div>
                    <div className="bold" style={{ fontSize: 22 }}>{fa(leadStats?.total || 0)}</div>
                  </div>
                </div>
              </div>
              <div className="col gap-12" style={{ flex: 1 }}>
                {donut.map((d, i) => (
                  <div key={i} className="row between">
                    <div className="row gap-8">
                      <span style={{ width: 10, height: 10, background: d.color, borderRadius: 3, flexShrink: 0 }} />
                      <span className="text-sm">{d.label}</span>
                    </div>
                    <span className="mono text-sm bold">{fa(d.value)}</span>
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-3)' }}>
              <div className="text-sm">هنوز لیدی ثبت نشده</div>
            </div>
          )}
        </div>
      </div>

      {/* ─── لیدهای اخیر (کلیک‌پذیر + تاریخچه) ─── */}
      <div className="card mt-24">
        <div className="card-head">
          <div className="row gap-12" style={{ alignItems: 'center' }}>
            <div className="card-title">
              <Icon name="users" size={16} color="var(--primary-2)" />
              لیدها
            </div>
            {/* فیلترهای سریع */}
            <div className="row gap-4">
              {LEAD_FILTERS.map(f => (
                <button key={f.id} onClick={() => setLeadFilter(f.id)} style={{
                  padding: '3px 10px', borderRadius: 6, fontSize: 11, cursor: 'pointer',
                  border: `1px solid ${leadFilter === f.id ? 'rgba(99,102,241,0.5)' : 'rgba(255,255,255,0.07)'}`,
                  background: leadFilter === f.id ? 'rgba(99,102,241,0.15)' : 'transparent',
                  color: leadFilter === f.id ? '#818CF8' : '#64748b',
                  transition: 'all 0.12s',
                }}>
                  {f.label}
                  {f.count > 0 && <span style={{ marginRight: 4, fontFamily: 'JetBrains Mono', fontSize: 10, opacity: 0.7 }}>{fa(f.count)}</span>}
                </button>
              ))}
            </div>
          </div>
          <Button kind="ghost" size="sm" onClick={() => window.SB_setPage?.('leads')}>
            مشاهده همه <Icon name="arrow-left" size={13} />
          </Button>
        </div>

        {recentLeads.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 30, color: 'var(--text-3)' }}>
            <Icon name="users" size={28} color="var(--text-3)" />
            <div className="text-sm mt-12">لیدی یافت نشد</div>
          </div>
        ) : (
          <table className="table">
            <thead>
              <tr>
                <th>لید</th>
                <th>شماره</th>
                <th>وضعیت</th>
                <th>آخرین تماس</th>
                <th>تگ‌ها</th>
                <th>تاریخ ثبت</th>
                <th style={{ width: 36 }}></th>
              </tr>
            </thead>
            <tbody>
              {recentLeads.map((l, i) => {
                const name = l.full_name || l.username || 'ناشناس';
                const initials = name.slice(0,2) || '؟';
                const sc = STATUS_COLOR[l.status] || '#6B7280';
                const sl = STATUS_LABEL[l.status] || l.status;
                // آخرین نتیجه تماس
                let lastOutcome = null;
                try { if (l.last_call_json) { const d = JSON.parse(l.last_call_json); lastOutcome = OUTCOME_LABEL[d.outcome]; } } catch {}
                // تگ‌ها
                const tags = (l.tags || '').split(',').filter(Boolean).slice(0, 2);
                return (
                  <tr key={l.id} onClick={() => setSelectedLead(l)} style={{ cursor: 'pointer' }}>
                    <td>
                      <div className="row gap-8">
                        <div className="avatar" style={{ width: 30, height: 30, fontSize: 11 }}>{initials}</div>
                        <div>
                          <div className="semi text-sm">{name}</div>
                          {l.username && l.full_name && <div className="text-xs text-3">@{l.username}</div>}
                        </div>
                      </div>
                    </td>
                    <td className="mono text-xs text-2">{l.phone || '—'}</td>
                    <td>
                      <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 6, background: sc + '20', color: sc }}>
                        {sl}
                      </span>
                    </td>
                    <td>
                      {lastOutcome
                        ? <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 6, background: lastOutcome.color + '18', color: lastOutcome.color }}>{lastOutcome.icon} {lastOutcome.label}</span>
                        : <span style={{ color: '#374151', fontSize: 11 }}>—</span>
                      }
                    </td>
                    <td>
                      <div className="row gap-4">
                        {tags.map(t => (
                          <span key={t} style={{ fontSize: 10, padding: '2px 6px', borderRadius: 20, background: 'rgba(99,102,241,0.14)', color: '#818CF8' }}>#{t}</span>
                        ))}
                      </div>
                    </td>
                    <td className="text-xs text-3 mono">{toShamsi(l.updated_at)}</td>
                    <td>
                      <button className="icon-btn" style={{ width: 28, height: 28 }}><Icon name="chevron-left" size={13} /></button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

      {/* ─── آمار پلتفرم‌ها ─── */}
      <div className="card mt-16">
        <div className="card-head">
          <div className="card-title"><Icon name="bar-chart-2" size={16} color="var(--primary-2)" />آمار پلتفرم‌ها</div>
        </div>
        {leadStats ? (
          <div className="row gap-32" style={{ flexWrap: 'wrap' }}>
            {[
              { name: 'تلگرام', value: leadStats.telegram || 0, color: '#3B82F6', icon: 'send' },
              { name: 'بله', value: leadStats.bale || 0, color: '#10B981', icon: 'message-circle' },
              { name: 'اینستاگرام', value: 0, color: '#FF6B35', icon: 'instagram' },
            ].map(p => {
              const pct = leadStats.total > 0 ? Math.round((p.value / leadStats.total) * 100) : 0;
              return (
                <div key={p.name} style={{ flex: 1, minWidth: 160 }}>
                  <div className="row between" style={{ marginBottom: 8 }}>
                    <div className="row gap-8">
                      <Icon name={p.icon} size={14} color={p.color} />
                      <span className="text-sm semi">{p.name}</span>
                    </div>
                    <span className="mono text-sm">
                      <span className="bold">{fa(p.value)}</span>
                      <span className="text-3"> ({fa(pct)}٪)</span>
                    </span>
                  </div>
                  <div className="bar"><div className="bar-fill" style={{ width: pct + '%', background: p.color }} /></div>
                </div>
              );
            })}
            <div style={{ flex: 1, minWidth: 160, padding: '8px 14px', background: 'rgba(255,255,255,0.03)', borderRadius: 10 }}>
              <div className="row between mb-8">
                <span className="text-xs text-3">مکالمات بسته</span>
                <span className="mono text-sm semi">{fa(convStats?.closed || 0)}</span>
              </div>
              <div className="row between">
                <span className="text-xs text-3">مکالمات فعال</span>
                <span className="mono text-sm semi" style={{ color: '#34D399' }}>{fa(convStats?.active || 0)}</span>
              </div>
            </div>
          </div>
        ) : (
          <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-3)' }}>در حال بارگذاری...</div>
        )}
      </div>

      {/* ─── SlidePanel تاریخچه لید ─── */}
      <SlidePanel open={!!selectedLead} onClose={() => setSelectedLead(null)}>
        {selectedLead && LeadDetailComp && (
          <LeadDetailComp
            lead={selectedLead}
            onClose={() => setSelectedLead(null)}
            onUpdate={() => loadLeads(leadFilter)}
          />
        )}
      </SlidePanel>
    </div>
  );
};

window.Dashboard = Dashboard;
