// ─── داشبورد فروشنده ─────────────────────────────────────────

// تبدیل عدد به فارسی
const _fa = (n) => String(n == null ? '' : n).replace(/[0-9]/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
const _money = (n) => {
  if (!n) return '—';
  const m = Math.round(n / 1000000);
  if (m >= 1) return _fa(m.toLocaleString('en-US')) + ' M';
  return _fa(Math.round(n).toLocaleString('en-US'));
};
const _moneyFull = (n) => n ? _fa(Math.round(n).toLocaleString('en-US')) + ' تومان' : '—';

// تبدیل YYYY-MM به شمسی (تقریبی برای نمایش)
const _periodLabel = (period) => {
  if (!period) return '';
  const [y, m] = period.split('-').map(Number);
  const months = ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'];
  const jalaliYear = y - 621;
  const idx = ((m - 4) + 12) % 12; // تقریب ساده
  return `${months[m - 1]} ${_fa(jalaliYear)}`;
};

const _periodShort = (period) => {
  if (!period) return '';
  const months = ['فرو','ارد','خرد','تیر','مرد','شهر','مهر','آبن','آذر','دی','بهم','اسف'];
  const m = parseInt(period.split('-')[1]) - 1;
  return months[m] || period;
};

const SD_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 SellerDashboard = ({ seller }) => {
  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };

  const [period, setPeriod] = useState(() => new Date().toISOString().slice(0, 7));
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [callLead, setCallLead] = useState(null);

  const load = (p) => {
    setLoading(true);
    fetch(`/api/seller/dashboard?period=${p || period}`, { headers })
      .then(r => r.json()).then(d => { if (d.success) setData(d.data); })
      .finally(() => setLoading(false));
  };

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

  const periodOptions = () => {
    const opts = [];
    const now = new Date();
    for (let i = 0; i < 4; i++) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const p = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
      opts.push(p);
    }
    return opts;
  };

  if (loading && !data) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '60vh', color: '#475569' }}>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontSize: 32, marginBottom: 12 }}>⏳</div>
        <div>در حال بارگذاری...</div>
      </div>
    </div>
  );

  return (
    <div style={{ padding: '0 0 40px', maxWidth: 960, margin: '0 auto' }}>

      {/* ─── انتخاب دوره ─── */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 20, flexWrap: 'wrap' }}>
        {periodOptions().map(p => (
          <button key={p} onClick={() => setPeriod(p)} style={{
            padding: '6px 16px', borderRadius: 8, fontSize: 12, cursor: 'pointer',
            border: `1px solid ${period === p ? '#6366F1' : 'rgba(255,255,255,0.08)'}`,
            background: period === p ? 'rgba(99,102,241,0.18)' : 'rgba(255,255,255,0.03)',
            color: period === p ? '#818CF8' : '#64748b', fontWeight: period === p ? 600 : 400,
            transition: 'all 0.12s',
          }}>{_periodLabel(p)}</button>
        ))}
      </div>

      {data && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

          {/* ─── کارت درآمد ─── */}
          <IncomeCard data={data} />

          {/* ─── جوایز ─── */}
          {data.bonuses && data.bonuses.length > 0 && (
            <BonusCard bonuses={data.bonuses} />
          )}

          {/* ─── هشدار برگشتی ─── */}
          {data.stats && data.stats.return_count > 0 && (
            <div style={{ padding: '12px 16px', borderRadius: 12, background: 'rgba(248,113,113,0.08)', border: '1px solid rgba(248,113,113,0.25)', display:'flex', alignItems:'center', gap:12 }}>
              <span style={{ fontSize:22 }}>↩️</span>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13, fontWeight:600, color:'#F87171' }}>
                  {_fa(data.stats.return_count)} لید این ماه از شما برگشته
                </div>
                <div style={{ fontSize:11, color:'#64748b', marginTop:3 }}>
                  لیدهایی که بدون تماس کافی از حساب شما خارج شده‌اند — این آمار در عملکرد شما ثبت می‌شود
                </div>
              </div>
            </div>
          )}

          {/* ─── فعالیت‌های امروز ─── */}
          <ActivityCard activities={data.activities} onCall={setCallLead} />

          {/* ─── فرصت‌های داغ ─── */}
          {data.hot_leads && data.hot_leads.length > 0 && (
            <HotLeadsCard leads={data.hot_leads} onCall={setCallLead} />
          )}
        </div>
      )}

      {/* ─── مودال ثبت تماس ─── */}
      {callLead && (
        <SellerCallModal
          lead={callLead}
          token={token}
          onClose={() => setCallLead(null)}
          onDone={() => { setCallLead(null); load(period); }}
        />
      )}
    </div>
  );
};

// ─── کارت درآمد و پورسانت ────────────────────────────────────
const IncomeCard = ({ data }) => {
  const { target, sales, plan, next_tier } = data;
  const gross = sales?.gross || 0;
  const commission = sales?.commission || 0;
  const progress = target > 0 ? Math.min(gross / target, 1) : null;
  const tiers = plan?.tiers || [];

  return (
    <div style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 12, padding: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
        <div style={{ fontSize: 20 }}>💰</div>
        <div style={{ fontWeight: 700, fontSize: 15, color: '#e2e8f0' }}>درآمد {_periodLabel(data.period)}</div>
        {plan && <span style={{ fontSize: 11, padding: '2px 9px', borderRadius: 20, background: 'rgba(99,102,241,0.15)', color: '#818CF8', marginRight: 'auto' }}>طرح: {plan.name}</span>}
      </div>

      {/* ─── تارگت + نوار پیشرفت ─── */}
      {target > 0 && (
        <div style={{ marginBottom: 18 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
            <div>
              <span style={{ fontSize: 12, color: '#64748b' }}>فروش: </span>
              <span style={{ fontSize: 15, fontWeight: 700, color: '#e2e8f0', fontFamily: 'JetBrains Mono' }}>{_money(gross)}</span>
            </div>
            <div>
              <span style={{ fontSize: 12, color: '#64748b' }}>تارگت: </span>
              <span style={{ fontSize: 13, color: '#94a3b8', fontFamily: 'JetBrains Mono' }}>{_money(target)}</span>
            </div>
          </div>
          <div style={{ height: 10, borderRadius: 5, background: 'rgba(255,255,255,0.07)', overflow: 'hidden' }}>
            <div style={{
              height: '100%', borderRadius: 5, transition: 'width 0.6s ease',
              width: `${Math.round((progress || 0) * 100)}%`,
              background: progress >= 1 ? '#34D399' : progress >= 0.7 ? '#FB923C' : '#6366F1',
            }} />
          </div>
          <div style={{ fontSize: 11, color: '#475569', marginTop: 5, textAlign: 'left', fontFamily: 'JetBrains Mono' }}>
            {progress !== null ? `${_fa(Math.round(progress * 100))}٪` : ''}
          </div>
        </div>
      )}

      {/* ─── لایه‌های پورسانت ─── */}
      {tiers.length > 0 && (
        <div style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 11, color: '#64748b', marginBottom: 8, fontWeight: 600 }}>لایه‌های پورسانت</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {tiers.sort((a, b) => (a.from_amount || 0) - (b.from_amount || 0)).map((tier, i) => {
              const tierMin = tier.from_amount || 0;
              const tierMax = tier.to_amount;
              const isActive = gross > tierMin && (tierMax === null || gross <= tierMax);
              const isPast = tierMax !== null && gross > tierMax;
              return (
                <div key={tier.id} style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '8px 12px', borderRadius: 8,
                  background: isActive ? 'rgba(99,102,241,0.12)' : isPast ? 'rgba(52,211,153,0.06)' : 'rgba(255,255,255,0.03)',
                  border: `1px solid ${isActive ? 'rgba(99,102,241,0.3)' : isPast ? 'rgba(52,211,153,0.15)' : 'rgba(255,255,255,0.05)'}`,
                }}>
                  <span style={{ fontSize: 14 }}>{isPast ? '✓' : isActive ? '▶' : '○'}</span>
                  <div style={{ flex: 1, fontSize: 12, color: isActive ? '#e2e8f0' : isPast ? '#64748b' : '#475569' }}>
                    {_money(tierMin)} — {tierMax ? _money(tierMax) : '∞'}
                  </div>
                  <span style={{
                    fontSize: 13, fontWeight: 700, fontFamily: 'JetBrains Mono',
                    color: isActive ? '#818CF8' : isPast ? '#34D399' : '#475569',
                  }}>
                    {tier.type === 'percentage' ? `${_fa(tier.rate)}٪` : `${_money(tier.rate)} / فروش`}
                  </span>
                  {isPast && (
                    <span style={{ fontSize: 11, color: '#34D399', fontFamily: 'JetBrains Mono' }}>
                      {_moneyFull(Math.min(gross, tierMax || gross) - tierMin) !== '—'
                        ? `+${_money((Math.min(gross, tierMax || gross) - tierMin) * tier.rate / 100)}`
                        : ''}
                    </span>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ─── جمع پورسانت ─── */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 14px', borderRadius: 10, background: 'rgba(99,102,241,0.1)', border: '1px solid rgba(99,102,241,0.2)' }}>
        <span style={{ fontSize: 13, color: '#94a3b8' }}>پورسانت محاسبه‌شده</span>
        <span style={{ fontSize: 18, fontWeight: 800, color: '#818CF8', fontFamily: 'JetBrains Mono' }}>{_moneyFull(commission)}</span>
      </div>

      {/* ─── انگیزه: لایه بعدی ─── */}
      {next_tier && (
        <div style={{ marginTop: 10, padding: '9px 14px', borderRadius: 8, background: 'rgba(251,146,60,0.08)', border: '1px solid rgba(251,146,60,0.2)', display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 14 }}>⚡</span>
          <span style={{ fontSize: 12, color: '#FB923C' }}>
            {_money(next_tier.needed)} دیگه بفروش ←
            نرخ پورسانتت به&nbsp;
            <strong>{next_tier.tier.type === 'percentage' ? `${_fa(next_tier.tier.rate)}٪` : `${_money(next_tier.tier.rate)} / فروش`}</strong>
            &nbsp;می‌رسه
          </span>
        </div>
      )}
    </div>
  );
};

// ─── کارت جوایز ────────────────────────────────────────────
const BonusCard = ({ bonuses }) => {
  const COND_LABEL = {
    consecutive_periods: 'دوره متوالی',
    single_period_amount: 'جهش ماهانه',
    total_year_amount: 'فروش سالانه',
  };

  return (
    <div style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 12, padding: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
        <div style={{ fontSize: 20 }}>🎯</div>
        <div style={{ fontWeight: 700, fontSize: 15, color: '#e2e8f0' }}>جوایز</div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {bonuses.map((bs, i) => {
          const earned = bs.earned;
          const isConsecutive = bs.bonus.condition_type === 'consecutive_periods';
          const progress = isConsecutive ? bs.progress : Math.min(bs.progress / bs.bonus.threshold, 1);

          return (
            <div key={i} style={{
              padding: '14px 16px', borderRadius: 10,
              background: earned ? 'rgba(52,211,153,0.08)' : 'rgba(255,255,255,0.03)',
              border: `1px solid ${earned ? 'rgba(52,211,153,0.25)' : 'rgba(255,255,255,0.07)'}`,
            }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 10 }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: earned ? '#34D399' : '#e2e8f0' }}>
                    {earned ? '🏆 ' : ''}{bs.bonus.name}
                  </div>
                  <div style={{ fontSize: 11, color: '#475569', marginTop: 2 }}>
                    {COND_LABEL[bs.bonus.condition_type]}
                    {bs.bonus.description ? ` — ${bs.bonus.description}` : ''}
                  </div>
                </div>
                <div style={{ fontSize: 14, fontWeight: 700, color: '#34D399', fontFamily: 'JetBrains Mono', whiteSpace: 'nowrap', flexShrink: 0 }}>
                  {_moneyFull(bs.bonus.bonus_amount)}
                </div>
              </div>

              {isConsecutive && bs.detail ? (
                <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                  {bs.detail.map((d, j) => (
                    <div key={j} style={{ textAlign: 'center' }}>
                      <div style={{
                        width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
                        background: d.hit ? 'rgba(52,211,153,0.2)' : j === bs.detail.length - 1 ? 'rgba(99,102,241,0.15)' : 'rgba(255,255,255,0.06)',
                        border: `2px solid ${d.hit ? '#34D399' : j === bs.detail.length - 1 ? '#6366F1' : 'rgba(255,255,255,0.1)'}`,
                        fontSize: 13,
                      }}>
                        {d.hit ? '✓' : j === bs.detail.length - 1 ? '←' : '○'}
                      </div>
                      <div style={{ fontSize: 9, color: '#475569', marginTop: 3 }}>{_periodShort(d.period)}</div>
                    </div>
                  ))}
                  <div style={{ fontSize: 12, color: '#64748b', marginRight: 6 }}>
                    {earned ? '🎉 جایزه گرفتی!' : `${_fa(bs.progress)} از ${_fa(bs.bonus.threshold)}`}
                  </div>
                </div>
              ) : (
                <div>
                  <div style={{ height: 6, borderRadius: 3, background: 'rgba(255,255,255,0.07)', overflow: 'hidden', marginBottom: 4 }}>
                    <div style={{
                      height: '100%', borderRadius: 3, transition: 'width 0.6s',
                      width: `${Math.round(progress * 100)}%`,
                      background: earned ? '#34D399' : '#818CF8',
                    }} />
                  </div>
                  <div style={{ fontSize: 11, color: '#64748b', display: 'flex', justifyContent: 'space-between' }}>
                    <span>{_money(bs.progress)}</span>
                    <span>{_money(bs.bonus.threshold)}</span>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ─── کارت فعالیت‌های امروز ────────────────────────────────────
const ActivityCard = ({ activities, onCall }) => {
  const { overdue = [], today = [], new_today = [] } = activities || {};
  const total = overdue.length + today.length + new_today.length;

  const STATUS_COLOR = { hot: '#F87171', warm: '#FB923C', scheduled: '#A78BFA', interested: '#60A5FA', new: '#818CF8', follow_up: '#94A3B8' };
  const STATUS_LABEL = { hot: 'داغ', warm: 'گرم', scheduled: 'زمان‌بندی', interested: 'علاقه‌مند', new: 'جدید', follow_up: 'پیگیری' };

  const ActRow = ({ r, color, urgency }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', borderRadius: 8, background: 'rgba(255,255,255,0.03)' }}>
      <div style={{ width: 6, height: 6, borderRadius: '50%', background: color, flexShrink: 0 }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: '#e2e8f0', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.full_name || r.username || r.name || 'ناشناس'}</div>
        {r.phone && <div style={{ fontSize: 10, color: '#475569', fontFamily: 'JetBrains Mono' }}>{r.phone}</div>}
      </div>
      <span style={{ fontSize: 10, padding: '2px 7px', borderRadius: 20, background: (STATUS_COLOR[r.status] || '#6B7280') + '20', color: STATUS_COLOR[r.status] || '#6B7280', whiteSpace: 'nowrap', flexShrink: 0 }}>
        {STATUS_LABEL[r.status] || r.status}
      </span>
      <button onClick={() => onCall(r)} style={{ padding: '5px 12px', borderRadius: 7, background: 'rgba(99,102,241,0.18)', border: '1px solid rgba(99,102,241,0.3)', color: '#818CF8', fontSize: 11, cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0 }}>
        📞 تماس
      </button>
    </div>
  );

  return (
    <div style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 12, padding: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
        <div style={{ fontSize: 20 }}>📋</div>
        <div style={{ fontWeight: 700, fontSize: 15, color: '#e2e8f0' }}>کارهای امروز</div>
        {total > 0 && (
          <div style={{ display: 'flex', gap: 6, marginRight: 'auto' }}>
            {overdue.length > 0   && <span style={{ fontSize: 11, padding: '2px 9px', borderRadius: 20, background: 'rgba(248,113,113,0.15)', color: '#F87171' }}>⚠️ {_fa(overdue.length)} سررسید گذشته</span>}
            {today.length > 0    && <span style={{ fontSize: 11, padding: '2px 9px', borderRadius: 20, background: 'rgba(251,146,60,0.15)', color: '#FB923C' }}>📅 {_fa(today.length)} امروز</span>}
            {new_today.length > 0 && <span style={{ fontSize: 11, padding: '2px 9px', borderRadius: 20, background: 'rgba(96,165,250,0.15)', color: '#60A5FA' }}>🆕 {_fa(new_today.length)} جدید</span>}
          </div>
        )}
      </div>

      {total === 0 ? (
        <div style={{ padding: '24px', textAlign: 'center', color: '#475569', fontSize: 13 }}>
          <div style={{ fontSize: 24, marginBottom: 8 }}>✅</div>
          همه کارها انجام شده!
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {overdue.length > 0 && (
            <>
              <div style={{ fontSize: 11, color: '#F87171', fontWeight: 700, padding: '2px 0' }}>⚠️ سررسید گذشته</div>
              {overdue.slice(0, 5).map(r => <ActRow key={r.id} r={r} color="#F87171" urgency="overdue" />)}
            </>
          )}
          {today.length > 0 && (
            <>
              <div style={{ fontSize: 11, color: '#FB923C', fontWeight: 700, padding: '4px 0 2px' }}>📅 امروز</div>
              {today.slice(0, 5).map(r => <ActRow key={r.id} r={r} color="#FB923C" urgency="today" />)}
            </>
          )}
          {new_today.length > 0 && (
            <>
              <div style={{ fontSize: 11, color: '#60A5FA', fontWeight: 700, padding: '4px 0 2px' }}>🆕 لیدهای جدید</div>
              {new_today.slice(0, 5).map(r => <ActRow key={r.id} r={r} color="#60A5FA" urgency="new" />)}
            </>
          )}
        </div>
      )}
    </div>
  );
};

// ─── لیدهای داغ / فرصت‌ها ────────────────────────────────────
const HotLeadsCard = ({ leads, onCall }) => {
  const STATUS_COLOR = { hot: '#F87171', warm: '#FB923C', scheduled: '#A78BFA', interested: '#60A5FA' };
  const STATUS_LABEL = { hot: '🔥 داغ', warm: '🌡️ گرم', scheduled: '📅 زمان‌بندی', interested: '👀 علاقه‌مند' };

  return (
    <div style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 12, padding: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
        <div style={{ fontSize: 20 }}>🔥</div>
        <div style={{ fontWeight: 700, fontSize: 15, color: '#e2e8f0' }}>فرصت‌های داغ</div>
        <span style={{ fontSize: 11, color: '#64748b', marginRight: 'auto' }}>{_fa(leads.length)} لید</span>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {leads.map(lead => {
          let lastOutcome = null;
          try { lastOutcome = lead.last_call_json ? JSON.parse(lead.last_call_json).outcome : null; } catch {}
          const ol = lastOutcome && SD_OUTCOME_LABEL[lastOutcome];

          return (
            <div key={lead.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 8, background: 'rgba(255,255,255,0.03)', cursor: 'pointer', transition: 'background 0.1s' }}
              onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.06)'}
              onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.03)'}>
              <div style={{ width: 8, height: 8, borderRadius: '50%', background: STATUS_COLOR[lead.status] || '#6B7280', flexShrink: 0 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: '#e2e8f0', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{lead.name}</div>
                <div style={{ fontSize: 10, color: '#475569', display: 'flex', gap: 8, marginTop: 2 }}>
                  {lead.phone && <span style={{ fontFamily: 'JetBrains Mono' }}>{lead.phone}</span>}
                  {lead.call_count > 0 && <span>📞 {_fa(lead.call_count)} تماس</span>}
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
                <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 20, background: (STATUS_COLOR[lead.status] || '#6B7280') + '20', color: STATUS_COLOR[lead.status] || '#6B7280', whiteSpace: 'nowrap' }}>
                  {STATUS_LABEL[lead.status] || lead.status}
                </span>
                {ol && <span style={{ fontSize: 11, padding: '2px 7px', borderRadius: 20, background: ol.color + '18', color: ol.color }}>{ol.icon}</span>}
                <button onClick={(e) => { e.stopPropagation(); onCall(lead); }} style={{ padding: '5px 12px', borderRadius: 7, background: 'rgba(99,102,241,0.18)', border: '1px solid rgba(99,102,241,0.3)', color: '#818CF8', fontSize: 11, cursor: 'pointer' }}>
                  📞 تماس
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ─── مودال سریع ثبت تماس (برای فروشنده) ─────────────────────
const LOST_REASONS = [
  { id: 'price',          label: '💸 قیمت گران است' },
  { id: 'budget',         label: '💰 بودجه ندارد' },
  { id: 'timing',         label: '⏳ زمان مناسب نیست' },
  { id: 'competitor',     label: '🏃 رفت پیش رقیب' },
  { id: 'no_need',        label: '🙅 نیازی ندارد' },
  { id: 'already_bought', label: '🛒 جای دیگری خریده' },
  { id: 'other',          label: '📌 سایر' },
];

const SellerCallModal = ({ lead, token, onClose, onDone }) => {
  const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };
  const [outcome, setOutcome] = useState('');
  const [note, setNote] = useState('');
  const [followUpAt, setFollowUpAt] = useState('');
  const [saleAmount, setSaleAmount] = useState('');
  const [lostReason, setLostReason] = useState('');
  const [saving, setSaving] = useState(false);
  const [activeTab, setActiveTab] = useState('call'); // call | history | tags
  // ─── تگ‌گذاری ───
  const [currentTags, setCurrentTags] = useState((lead.tags || '').split(',').filter(Boolean));
  const [tagInput, setTagInput] = useState('');
  const [tagSaving, setTagSaving] = useState(false);
  // ─── تاریخچه ───
  const [history, setHistory] = useState(null);
  const [histLoading, setHistLoading] = useState(false);

  const loadHistory = () => {
    if (history !== null) return; // cache
    setHistLoading(true);
    fetch(`/api/seller/leads/${lead.id}/history`, { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setHistory(d.data.events || []); })
      .finally(() => setHistLoading(false));
  };

  // تبدیل تاریخ به شمسی ساده
  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 addTag = () => {
    const t = tagInput.trim().replace(/^#/, '').replace(/,/g, '').replace(/\s+/g, '_');
    if (!t || currentTags.includes(t)) { setTagInput(''); return; }
    const newTags = [...currentTags, t];
    setTagSaving(true);
    fetch(`/api/seller/leads/${lead.id}/tags`, {
      method: 'PUT', headers,
      body: JSON.stringify({ tags: newTags.join(',') }),
    }).then(r => r.json()).then(d => {
      if (d.success) setCurrentTags(newTags);
    }).finally(() => { setTagSaving(false); setTagInput(''); });
  };

  const removeTag = (tag) => {
    const newTags = currentTags.filter(t => t !== tag);
    fetch(`/api/seller/leads/${lead.id}/tags`, {
      method: 'PUT', headers,
      body: JSON.stringify({ tags: newTags.join(',') }),
    }).then(r => r.json()).then(d => {
      if (d.success) setCurrentTags(newTags);
    });
  };

  const OUTCOME_STATUS = {
    answered: 'follow_up', no_answer: 'follow_up', call_later: 'follow_up',
    follow_up: 'follow_up', scheduled: 'follow_up', sold: 'buyer',
    not_interested: 'lost', cancelled: 'cancelled', bad_number: 'bad_number',
  };

  const needsLostReason = ['not_interested', 'cancelled'].includes(outcome);

  const save = () => {
    if (!note.trim() && !outcome) return;
    setSaving(true);
    const body = { note, outcome, new_status: OUTCOME_STATUS[outcome] || null, follow_up_at: followUpAt || null };
    if (outcome === 'sold' && saleAmount) body.sale_amount = parseFloat(saleAmount) || 0;
    if (needsLostReason && lostReason) body.lost_reason = lostReason;
    fetch(`/api/seller/leads/${lead.id}/call-log`, { method: 'POST', headers, body: JSON.stringify(body) })
      .then(r => r.json()).then(d => { if (d.success) onDone(); })
      .finally(() => setSaving(false));
  };

  const defaultFollowUp = () => {
    const d = new Date(); d.setDate(d.getDate() + 1);
    return d.toISOString().slice(0, 16);
  };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }} onClick={onClose}>
      <div style={{ width: '100%', maxWidth: 440, background: '#13131f', border: '1px solid #2a2a3d', borderRadius: 14, boxShadow: '0 20px 60px rgba(0,0,0,0.7)' }} onClick={e => e.stopPropagation()}>
        {/* هدر */}
        <div style={{ padding: '14px 18px 0', borderBottom: '1px solid #2a2a3d' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0' }}>{lead.full_name || lead.username || lead.name || 'ناشناس'}</div>
              <div style={{ fontSize: 11, color: '#64748b', marginTop: 2 }}>{lead.phone || 'بدون شماره'}</div>
            </div>
            <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#64748b', fontSize: 18, padding: 4 }}>✕</button>
          </div>
          {/* تب‌ها */}
          <div style={{ display: 'flex', gap: 0 }}>
            {[
              { id: 'call',    label: '📞 ثبت تماس' },
              { id: 'history', label: '📋 تاریخچه' },
              { id: 'tags',    label: '🏷️ تگ‌ها' },
            ].map(t => (
              <button key={t.id} onClick={() => { setActiveTab(t.id); if (t.id === 'history') loadHistory(); }} style={{
                flex: 1, padding: '7px 0', fontSize: 12, cursor: 'pointer', border: 'none',
                borderBottom: activeTab === t.id ? '2px solid #6366F1' : '2px solid transparent',
                background: 'transparent',
                color: activeTab === t.id ? '#818CF8' : '#64748b',
                fontWeight: activeTab === t.id ? 600 : 400, transition: 'all .15s',
              }}>{t.label}</button>
            ))}
          </div>
        </div>

        {/* ─── تب تگ‌ها ─── */}
        {activeTab === 'tags' && (
          <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minHeight: 32 }}>
              {currentTags.length === 0
                ? <span style={{ fontSize: 12, color: '#374151' }}>هنوز تگی ندارد</span>
                : currentTags.map(tag => (
                  <span key={tag} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12, padding: '3px 8px 3px 10px', borderRadius: 20, background: 'rgba(99,102,241,0.14)', color: '#818CF8', border: '1px solid rgba(99,102,241,0.25)' }}>
                    #{tag}
                    <button onClick={() => removeTag(tag)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#818CF8', opacity: 0.7, padding: 0, lineHeight: 1, fontSize: 14 }}>×</button>
                  </span>
                ))
              }
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <input value={tagInput} onChange={e => setTagInput(e.target.value)}
                onKeyDown={e => { if (e.key === 'Enter') addTag(); }}
                placeholder="تگ جدید... (Enter)"
                style={{ flex: 1, background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(99,102,241,0.25)', borderRadius: 8, padding: '7px 10px', color: '#e2e8f0', fontSize: 12, outline: 'none', direction: 'rtl' }} />
              <button onClick={addTag} disabled={tagSaving || !tagInput.trim()} style={{
                padding: '7px 14px', borderRadius: 8, fontSize: 12, cursor: 'pointer',
                background: 'rgba(99,102,241,0.18)', border: '1px solid rgba(99,102,241,0.3)',
                color: '#818CF8', fontWeight: 600, opacity: tagInput.trim() ? 1 : 0.4,
              }}>+ افزودن</button>
            </div>
          </div>
        )}

        {/* ─── تب تاریخچه ─── */}
        {activeTab === 'history' && (
          <div style={{ padding: 16, maxHeight: 420, overflowY: 'auto' }}>
            {histLoading && (
              <div style={{ textAlign: 'center', padding: '28px 0', color: '#64748b', fontSize: 12 }}>در حال بارگذاری...</div>
            )}
            {!histLoading && history !== null && history.length === 0 && (
              <div style={{ textAlign: 'center', padding: '28px 0', color: '#475569', fontSize: 12 }}>
                هنوز فعالیتی ثبت نشده
              </div>
            )}
            {!histLoading && history !== null && history.length > 0 && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {history.map((ev, i) => {
                  // ─── رویداد ارجاع ───
                  if (ev.event_type === 'refer') {
                    let data = {};
                    try { data = JSON.parse(ev.new_value || '{}'); } catch {}
                    return (
                      <div key={ev.id} style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(251,146,60,0.07)', border: '1px solid rgba(251,146,60,0.2)' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <span style={{ fontSize: 14 }}>🔀</span>
                          <div style={{ flex: 1 }}>
                            <div style={{ fontSize: 12, fontWeight: 600, color: '#FB923C' }}>ارجاع به {data.seller_name || '—'}</div>
                            {data.reason && <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 2 }}>دلیل: {data.reason}</div>}
                          </div>
                          <span style={{ fontSize: 10, color: '#475569', fontFamily: 'JetBrains Mono', flexShrink: 0 }}>{_toShamsi(ev.created_at)}</span>
                        </div>
                      </div>
                    );
                  }
                  // ─── رویداد تماس ───
                  if (ev.event_type === 'call') {
                    let data = {};
                    try { data = JSON.parse(ev.new_value || '{}'); } catch {}
                    const o = SD_OUTCOME_LABEL[data.outcome];
                    return (
                      <div key={ev.id} style={{
                        padding: '10px 12px', borderRadius: 8,
                        background: i === 0 ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.02)',
                        border: `1px solid rgba(255,255,255,${i === 0 ? '0.08' : '0.04'})`,
                      }}>
                        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
                          <div style={{ flex: 1 }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                              {o
                                ? <span style={{ fontSize: 11, padding: '2px 7px', borderRadius: 20, background: o.color+'18', color: o.color }}>{o.icon} {o.label}</span>
                                : <span style={{ fontSize: 11, color: '#475569' }}>—</span>
                              }
                              {/* نام فروشنده‌ای که ثبت کرده */}
                              {ev.seller_name && (
                                <span style={{ fontSize: 10, padding: '2px 7px', borderRadius: 20, background: 'rgba(99,102,241,0.12)', color: '#818CF8' }}>
                                  👤 {ev.seller_name}
                                </span>
                              )}
                              {data.follow_up_at && (
                                <span style={{ fontSize: 10, color: '#fbbf24' }}>🔔 {_toShamsi(data.follow_up_at)}</span>
                              )}
                            </div>
                            {data.note && (
                              <div style={{ fontSize: 12, color: '#94a3b8', marginTop: 6, lineHeight: 1.7, direction: 'rtl' }}>{data.note}</div>
                            )}
                          </div>
                          <span style={{ fontSize: 10, color: '#475569', fontFamily: 'JetBrains Mono', flexShrink: 0 }}>{_toShamsi(ev.created_at)}</span>
                        </div>
                      </div>
                    );
                  }
                  return null;
                })}
              </div>
            )}
          </div>
        )}

        {activeTab === 'call' && <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* نتیجه تماس */}
          <div>
            <div style={{ fontSize: 11, color: '#64748b', marginBottom: 8 }}>نتیجه تماس</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {Object.entries(SD_OUTCOME_LABEL).map(([id, o]) => (
                <button key={id} onClick={() => { setOutcome(id); setLostReason(''); }} style={{
                  padding: '5px 10px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: 'none',
                  background: outcome === id ? o.color + '28' : 'rgba(255,255,255,0.06)',
                  color: outcome === id ? o.color : '#94a3b8',
                  fontWeight: outcome === id ? 600 : 400, transition: 'all 0.12s',
                }}>{o.icon} {o.label}</button>
              ))}
            </div>
          </div>

          {/* ─── دلیل باخت ─── */}
          {needsLostReason && (
            <div style={{ padding: '12px 14px', borderRadius: 8, background: 'rgba(107,114,128,0.08)', border: '1px solid rgba(107,114,128,0.25)' }}>
              <div style={{ fontSize: 11, color: '#6B7280', marginBottom: 8, fontWeight: 600 }}>❓ دلیل از دست رفتن لید</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {LOST_REASONS.map(r => (
                  <button key={r.id} onClick={() => setLostReason(r.id)} style={{
                    padding: '5px 10px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: 'none',
                    background: lostReason === r.id ? 'rgba(107,114,128,0.3)' : 'rgba(255,255,255,0.06)',
                    color: lostReason === r.id ? '#e2e8f0' : '#64748b',
                    fontWeight: lostReason === r.id ? 600 : 400, transition: 'all 0.12s',
                  }}>{r.label}</button>
                ))}
              </div>
            </div>
          )}

          {outcome === 'sold' && (
            <div style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(52,211,153,0.08)', border: '1px solid rgba(52,211,153,0.25)' }}>
              <div style={{ fontSize: 11, color: '#34D399', marginBottom: 6, fontWeight: 600 }}>💰 مبلغ فروش (تومان)</div>
              <input type="number" value={saleAmount} onChange={e => setSaleAmount(e.target.value)} placeholder="مثلا: 2500000"
                style={{ width: '100%', padding: '8px 12px', borderRadius: 8, background: 'rgba(52,211,153,0.08)', border: '1px solid rgba(52,211,153,0.3)', color: '#34D399', fontSize: 14, outline: 'none', fontFamily: 'JetBrains Mono', boxSizing: 'border-box', direction: 'ltr' }} />
            </div>
          )}

          {/* یادآور */}
          <div>
            <div style={{ fontSize: 11, color: '#64748b', marginBottom: 6 }}>🔔 یادآور بعدی <span style={{ opacity: 0.6 }}>(اختیاری)</span></div>
            <div style={{ display: 'flex', gap: 6 }}>
              <input type="datetime-local" value={followUpAt} onChange={e => setFollowUpAt(e.target.value)}
                style={{ flex: 1, background: '#1a1a2e', border: '1px solid #2a2a3d', borderRadius: 8, padding: '6px 8px', color: '#e2e8f0', fontSize: 12, outline: 'none', colorScheme: 'dark' }} />
              <button onClick={() => setFollowUpAt(defaultFollowUp())} style={{ padding: '6px 10px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid #3730a3', background: 'rgba(99,102,241,0.12)', color: '#818CF8', whiteSpace: 'nowrap' }}>فردا</button>
            </div>
          </div>

          {/* یادداشت */}
          <div>
            <div style={{ fontSize: 11, color: '#64748b', marginBottom: 6 }}>یادداشت</div>
            <textarea value={note} onChange={e => setNote(e.target.value)} rows={3} placeholder="خلاصه مکالمه..."
              style={{ width: '100%', background: '#1a1a2e', border: '1px solid #2a2a3d', borderRadius: 8, padding: 10, color: '#e2e8f0', fontSize: 12, resize: 'none', outline: 'none', direction: 'rtl', fontFamily: 'inherit', boxSizing: 'border-box' }} />
          </div>

          <button onClick={save} disabled={saving || (!note.trim() && !outcome)} style={{
            padding: '10px 16px', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer', border: 'none',
            background: saving || (!note.trim() && !outcome) ? 'rgba(99,102,241,0.3)' : '#6366F1',
            color: 'white', transition: 'all 0.15s',
          }}>{saving ? '⏳ در حال ذخیره...' : '💾 ذخیره فعالیت'}</button>
        </div>}
      </div>
    </div>
  );
};

window.SellerDashboard = SellerDashboard;
