// ── Dashboard screen ──────────────────────────────────────────

// vertical bar chart for 7-day activity — only today (آخرین ستون) پررنگ است
function BarChart({ data, height = 116 }) {
  const max = Math.max(...data.map(d => d.v));
  const today = data.length - 1;
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 7, height }}>
        {data.map((d, i) => {
          const on = i === today;
          return (
            <div key={i} style={{
              flex: 1, display: 'flex', flexDirection: 'column',
              alignItems: 'center', gap: 8, height: '100%',
              justifyContent: 'flex-end',
            }}>
              <span style={{
                fontSize: 11, fontWeight: 700, color: on ? 'var(--ink)' : 'var(--ink-3)',
                fontFeatureSettings: "'tnum'",
              }}>{fa(d.v)}</span>
              <div style={{
                width: '100%', maxWidth: 26, borderRadius: 7,
                height: ((d.v / max) * (height - 40)) + 6,
                background: on ? 'var(--accent)' : 'var(--surface)',
                border: '1px solid ' + (on ? 'var(--accent)' : 'var(--line-2)'),
              }} />
            </div>
          );
        })}
      </div>
      <div style={{ display: 'flex', gap: 7, marginTop: 8 }}>
        {data.map((d, i) => (
          <span key={i} style={{
            flex: 1, textAlign: 'center', fontSize: 9.5,
            color: i === today ? 'var(--ink)' : 'var(--ink-3)', fontWeight: i === today ? 700 : 500,
          }}>{d.day.replace('‌', '')}</span>
        ))}
      </div>
    </div>
  );
}

function PeakHours({ data }) {
  const max = Math.max(...data.map(d => d.v));
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height: 44 }}>
      {data.map((d, i) => (
        <div key={i} title={fa(d.h) + ':۰۰'} style={{
          flex: 1, borderRadius: 3, minWidth: 0,
          height: Math.max(4, (d.v / max) * 44),
          background: d.v >= 88 ? 'var(--accent)' : 'var(--surface-2)',
          border: '1px solid var(--line)',
        }} />
      ))}
    </div>
  );
}

function Funnel({ data }) {
  const max = data[0].count;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {data.map((s, i) => {
        const pct = s.count / max;
        const conv = i === 0 ? 100 : Math.round((s.count / data[i-1].count) * 100);
        return (
          <div key={i}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5, alignItems: 'baseline' }}>
              <span style={{ fontSize: 12.5, color: 'var(--ink)', fontWeight: 500 }}>{s.stage}</span>
              <span style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink)' }}>
                {fa(s.count)}
                <span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500, marginRight: 6 }}>
                  {fa(conv)}٪
                </span>
              </span>
            </div>
            <div style={{ height: 9, borderRadius: 999, background: 'var(--surface-2)', overflow: 'hidden' }}>
              <div style={{
                width: (pct * 100) + '%', height: '100%', borderRadius: 999,
                background: i === data.length - 1 ? 'var(--accent)' : 'var(--ink)',
                opacity: i === data.length - 1 ? 1 : 0.18 + i * 0.16,
              }} />
            </div>
          </div>
        );
      })}
    </div>
  );
}

function KpiCard({ k }) {
  // طول عددِ نمایشی را حساب کن تا فونت با بزرگ‌شدن عدد کوچک شود (اندازه‌ی خانه ثابت بماند)
  const valText = typeof k.value === 'number' ? fa(k.value) : String(k.value);
  const digits = valText.replace(/[^0-9۰-۹:]/g, '').length;
  const vfs = digits <= 3 ? 28 : digits === 4 ? 25 : digits === 5 ? 21 : digits === 6 ? 18 : 16;
  return (
    <Card style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 10, height: 112, boxSizing: 'border-box' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 6 }}>
        <span style={{ fontSize: 11.5, color: 'var(--ink-2)', fontWeight: 500, lineHeight: 1.4, minWidth: 0 }}>{k.label}</span>
        <Delta value={k.delta} />
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 8 }}>
        <span style={{ fontSize: vfs, fontWeight: 800, color: 'var(--ink)', lineHeight: 1, letterSpacing: '-.02em', whiteSpace: 'nowrap' }}>
          {typeof k.value === 'number' ? fa(k.value) : k.value}
          {k.unit && <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-3)', marginRight: 3 }}>{k.unit}</span>}
        </span>
        <Sparkline data={k.spark} w={56} h={24} />
      </div>
    </Card>
  );
}

const OVERVIEW_PERIODS = [
  { id: 'day',   label: 'امروز',    title: 'نمای کلی امروز',   sub: 'پنج‌شنبه، ۱۰ خرداد ۱۴۰۴' },
  { id: 'week',  label: 'هفته',     title: 'نمای کلی هفته',    sub: '۴ تا ۱۰ خرداد ۱۴۰۴' },
  { id: 'month', label: 'ماه',      title: 'نمای کلی ماه',     sub: 'خرداد ۱۴۰۴' },
  { id: 'year',  label: 'سال',      title: 'نمای کلی امسال',   sub: 'سال ۱۴۰۴' },
];

function Dashboard({ biz, onOpenConv, onSwitchBiz, onTab }) {
  const [period, setPeriod] = useState('day');
  const p = OVERVIEW_PERIODS.find(x => x.id === period);
  const followups = CONVERSATIONS.filter(c => convFollowup(c));
  return (
    <div style={{ padding: '0 14px 16px' }}>
      {/* greeting */}
      <div style={{ padding: '4px 4px 14px' }}>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 3 }}>{p.sub}</div>
        <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--ink)', letterSpacing: '-.02em' }}>
          {p.title}
        </div>
      </div>

      {/* period selector */}
      <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--surface-2)', borderRadius: 12, marginBottom: 14 }}>
        {OVERVIEW_PERIODS.map(op => {
          const on = op.id === period;
          return (
            <button key={op.id} onClick={() => setPeriod(op.id)} style={{
              flex: 1, font: 'inherit', fontSize: 12.5, fontWeight: on ? 700 : 500, cursor: 'pointer',
              padding: '8px 0', borderRadius: 9, border: 'none',
              background: on ? 'var(--surface)' : 'transparent',
              color: on ? 'var(--ink)' : 'var(--ink-2)',
              boxShadow: on ? '0 1px 3px rgba(0,0,0,0.10)' : 'none',
            }}>{op.label}</button>
          );
        })}
      </div>

      {/* KPIs 2x2 — change with selected period */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--gap)' }}>
        {(KPIS_BY_PERIOD[period] || KPIS).map(k => <KpiCard key={k.id} k={k} />)}
      </div>

      {/* conversations needing follow-up — directly under the overview */}
      <div style={{ marginTop: 22 }}>
        <SectionLabel action={
          <button onClick={() => onTab('inbox')} style={{
            font: 'inherit', fontSize: 11.5, color: 'var(--ink-2)', background: 'none',
            border: 'none', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 2,
          }}>همه<Icon name="chevron-left" size={13} /></button>
        }>گفتگوهای نیاز به پیگیری</SectionLabel>
        <Card pad={false} style={{ overflow: 'hidden' }}>
          {followups.length === 0 && (
            <div style={{ textAlign: 'center', color: 'var(--ink-3)', fontSize: 12.5, padding: '26px 0' }}>
              هیچ گفتگوی نیازمند پیگیری‌ای نیست 🎉
            </div>
          )}
          {followups.map((c, i) => {
            const cu = CUSTOMERS.find(x => x.id === c.customerId);
            const fu = convFollowup(c);
            return (
              <div key={c.id} onClick={() => onOpenConv(c.id)} style={{
                display: 'flex', alignItems: 'center', gap: 11, padding: '12px 14px',
                borderTop: i ? '1px solid var(--line)' : 'none', cursor: 'pointer',
              }}>
                <Avatar mono={cu.mono} size={38} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)', whiteSpace: 'nowrap' }}>{cu.name}</span>
                    <StatusDot status={c.status} />
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 3, color: '#d9534f' }}>
                    <Icon name="clock" size={12} sw={2} />
                    <span style={{ fontSize: 11.5, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{fu.reason}</span>
                  </div>
                </div>
                <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>{c.time}</span>
              </div>
            );
          })}
        </Card>
      </div>

      {/* activity */}
      <div style={{ marginTop: 22 }}>
        <SectionLabel action={<span style={{ fontSize: 11, color: 'var(--ink-3)' }}>مکالمات جدید</span>}>
          فعالیت ۷ روز اخیر
        </SectionLabel>
        <Card>
          <BarChart data={ACTIVITY} />
        </Card>
      </div>

      {/* peak hours */}
      <div style={{ marginTop: 22 }}>
        <SectionLabel action={<span style={{ fontSize: 11, color: 'var(--ink-3)' }}>۲۴ ساعته</span>}>
          ساعات پیک پاسخ‌گویی
        </SectionLabel>
        <Card>
          <PeakHours data={PEAK_HOURS} />
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 10.5, color: 'var(--ink-3)' }}>
            <span>۱۲ شب</span><span>۱۲ ظهر</span><span>پیک: ۱۸–۲۰</span><span>۱۱ شب</span>
          </div>
        </Card>
      </div>

      {/* funnel */}
      <div style={{ marginTop: 22 }}>
        <SectionLabel action={
          <button onClick={() => onTab('customers')} style={{
            font: 'inherit', fontSize: 11.5, color: 'var(--ink-2)', background: 'none',
            border: 'none', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 2,
          }}>جزئیات<Icon name="chevron-left" size={13} /></button>
        }>قیف فروش</SectionLabel>
        <Card><Funnel data={FUNNEL} /></Card>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
