// EarningsScreen — User-facing earnings dashboard.
// Total earned, breakdown per store, breakdown per day, upcoming pipeline.

const { useMemo: useMemoE, useState: useStateE } = React;

function StatCard({ label, amount, sub, tone = 'ink' }) {
  const colors = {
    ink:     { fg: 'var(--ink)',    bg: 'var(--surface)', border: 'var(--border)' },
    accent:  { fg: '#fff',          bg: 'var(--accent)',  border: 'transparent' },
    muted:   { fg: 'var(--muted)',  bg: 'var(--surface)', border: 'var(--border)' },
  }[tone];
  return (
    <div style={{
      background: colors.bg, color: colors.fg,
      border: `1px solid ${colors.border}`,
      borderRadius: 16, padding: '14px 14px',
      display: 'flex', flexDirection: 'column', gap: 4,
    }}>
      <div style={{
        fontSize: 11, opacity: 0.7, letterSpacing: '0.02em',
      }}>{label}</div>
      <div style={{
        fontSize: 18, fontWeight: 700, lineHeight: 1.2,
        fontFamily: 'JetBrains Mono, ui-monospace, monospace',
        fontVariantNumeric: 'tabular-nums',
      }}>{amount}</div>
      {sub && <div style={{ fontSize: 11, opacity: 0.65 }}>{sub}</div>}
    </div>
  );
}

function Bar({ value, max, color }) {
  const pct = max > 0 ? (value / max) * 100 : 0;
  return (
    <div style={{
      height: 6, borderRadius: 99, background: 'var(--icon-bg)',
      overflow: 'hidden',
    }}>
      <div style={{
        height: '100%', width: `${pct}%`, background: color,
        transition: 'width 320ms ease',
      }} />
    </div>
  );
}

function EarningsScreen({ onBack }) {
  const app = window.useAppStore();
  const earnings = useMemoE(
    () => window.computeEarnings(app.currentUserId),
    [app.assignments, app.stores, app.currentUserId]
  );

  const [tab, setTab] = useStateE('stores'); // 'stores' | 'days'

  const maxStore = Math.max(...earnings.perStore.map(s => s.total), 1);
  const maxDay   = Math.max(...earnings.perDay.map(d => d.total), 1);

  return (
    <div style={{
      direction: 'rtl', background: 'var(--bg)', height: '100%',
      fontFamily: 'Vazirmatn, system-ui, sans-serif', color: 'var(--ink)',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      {/* header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 18px 8px', flexShrink: 0,
      }}>
        <button onClick={onBack} style={{
          all: 'unset', cursor: 'pointer',
          width: 38, height: 38, borderRadius: 99,
          background: 'var(--surface)', border: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--ink)',
        }}>
          <window.IconChevron size={16} dir="right" />
        </button>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 15, fontWeight: 700 }}>درآمد و حقوق</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>خرداد ۱۴۰۵</div>
        </div>
        <div style={{ width: 38 }} />
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '6px 18px 18px' }}>
        {/* hero */}
        <div style={{
          background: 'var(--ink)', color: 'var(--bg)',
          borderRadius: 18, padding: '18px 18px',
          marginBottom: 12, position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            fontSize: 11, color: 'rgba(255,255,255,0.55)',
            letterSpacing: '0.04em', marginBottom: 8,
          }}>کسب‌شده تا کنون</div>
          <div style={{
            fontSize: 30, fontWeight: 700, lineHeight: 1.1,
            fontFamily: 'JetBrains Mono, ui-monospace, monospace',
            fontVariantNumeric: 'tabular-nums',
          }}>{window.fmtToman(earnings.earnedTotal)}</div>
          <div style={{
            display: 'flex', gap: 16, marginTop: 14,
            fontSize: 11, color: 'rgba(255,255,255,0.7)',
          }}>
            <div>
              <div style={{ opacity: 0.6, marginBottom: 2 }}>تکمیل شده</div>
              <div style={{
                fontSize: 14, fontWeight: 700, color: '#fff',
                fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                fontVariantNumeric: 'tabular-nums',
              }}>{window.faNumS(earnings.visitsDone)} ویزیت</div>
            </div>
            <div style={{ width: 1, background: 'rgba(255,255,255,0.18)' }} />
            <div>
              <div style={{ opacity: 0.6, marginBottom: 2 }}>امروز</div>
              <div style={{
                fontSize: 14, fontWeight: 700, color: '#fff',
                fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                fontVariantNumeric: 'tabular-nums',
              }}>{window.faNumS(earnings.visitsToday)} ویزیت</div>
            </div>
          </div>
          {/* decorative grid */}
          <div style={{
            position: 'absolute', top: -20, left: -20, opacity: 0.06,
            fontSize: 140, fontWeight: 700, color: '#fff',
            fontFamily: 'JetBrains Mono, ui-monospace, monospace',
          }}>﷼</div>
        </div>

        {/* small stats row */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8,
          marginBottom: 18,
        }}>
          <StatCard
            label="پیش‌بینی پیش‌رو"
            amount={window.fmtToman(earnings.upcoming)}
            sub={`${window.faNumS(earnings.visitsUpcoming)} ویزیت برنامه‌ریزی شده`}
          />
          <StatCard
            label="میانگین هر ویزیت"
            amount={window.fmtToman(
              earnings.perStore.length > 0
                ? Math.round(
                    (earnings.earnedTotal + earnings.upcoming) /
                    (earnings.visitsDone + earnings.visitsToday + earnings.visitsUpcoming || 1)
                  )
                : 0
            )}
            sub="تعرفه میانگین"
          />
        </div>

        {/* tab switcher */}
        <div style={{
          display: 'flex', gap: 4, padding: 4,
          background: 'var(--icon-bg)', borderRadius: 12,
          marginBottom: 12,
        }}>
          {[
            { id: 'stores', label: 'بر اساس فروشگاه' },
            { id: 'days',   label: 'بر اساس روز' },
          ].map(t => (
            <button key={t.id}
              onClick={() => setTab(t.id)}
              style={{
                all: 'unset', cursor: 'pointer', flex: 1,
                textAlign: 'center', padding: '8px 6px',
                borderRadius: 9,
                background: tab === t.id ? 'var(--surface)' : 'transparent',
                color: tab === t.id ? 'var(--ink)' : 'var(--muted)',
                fontSize: 12.5, fontWeight: 600,
                boxShadow: tab === t.id ? '0 1px 2px rgba(0,0,0,0.08)' : 'none',
                transition: 'all 160ms ease',
              }}>{t.label}</button>
          ))}
        </div>

        {/* per-store */}
        {tab === 'stores' && (
          <div style={{
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderRadius: 16, overflow: 'hidden',
          }}>
            {earnings.perStore.length === 0 && (
              <div style={{
                padding: '24px 18px', textAlign: 'center',
                fontSize: 13, color: 'var(--muted)',
              }}>ویزیتی ثبت نشده است</div>
            )}
            {earnings.perStore.map((s, i) => {
              const store = window.getStoreById(s.storeId);
              return (
                <div key={s.storeId} style={{
                  padding: '12px 14px',
                  borderTop: i ? '1px solid var(--border)' : 'none',
                }}>
                  <div style={{
                    display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
                    gap: 8, marginBottom: 5,
                  }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>
                      {store?.name}
                    </div>
                    <div style={{
                      fontSize: 13, fontWeight: 700, color: 'var(--accent)',
                      fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                      fontVariantNumeric: 'tabular-nums',
                    }}>{window.fmtToman(s.total)}</div>
                  </div>
                  <div style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                    gap: 8, marginBottom: 6,
                    fontSize: 11, color: 'var(--muted)',
                  }}>
                    <span>{window.faNumS(s.count)} ویزیت × {window.fmtToman(store?.price || 0)}</span>
                  </div>
                  <Bar value={s.total} max={maxStore} color="var(--accent)" />
                </div>
              );
            })}
          </div>
        )}

        {/* per-day */}
        {tab === 'days' && (
          <div style={{
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderRadius: 16, overflow: 'hidden',
          }}>
            {earnings.perDay.length === 0 && (
              <div style={{
                padding: '24px 18px', textAlign: 'center',
                fontSize: 13, color: 'var(--muted)',
              }}>روزی ثبت نشده است</div>
            )}
            {earnings.perDay.map((d, i) => (
              <div key={d.day} style={{
                padding: '12px 14px',
                borderTop: i ? '1px solid var(--border)' : 'none',
              }}>
                <div style={{
                  display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
                  gap: 8, marginBottom: 5,
                }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>
                    {window.faNumS(d.day)} خرداد
                  </div>
                  <div style={{
                    fontSize: 13, fontWeight: 700, color: 'var(--accent)',
                    fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                    fontVariantNumeric: 'tabular-nums',
                  }}>{window.fmtToman(d.total)}</div>
                </div>
                <div style={{
                  fontSize: 11, color: 'var(--muted)', marginBottom: 6,
                }}>{window.faNumS(d.count)} ویزیت</div>
                <Bar value={d.total} max={maxDay} color="var(--accent)" />
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

window.EarningsScreen = EarningsScreen;
