const { useState, useEffect } = React;

function Dashboard() {
  const { navigate, t, bons, refreshBons } = window.useApp();
  const [stats, setStats] = useState({ month: { count: 0, ca: 0 }, total: { count: 0, ca: 0 } });

  useEffect(() => {
    refreshBons();
    setStats({ month: storage.statsThisMonth(), total: storage.statsTotal() });
  }, []);

  const recent = bons.slice(0, 5);
  const fmt = (n) => n.toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const fmtDate = (iso) => new Date(iso).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short' });

  return (
    <div style={ds.screen}>
      {/* Header */}
      <div style={ds.header}>
        <div>
          <div style={ds.greeting}>{t('appName')}</div>
          <div style={ds.date}>{new Date().toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long' })}</div>
        </div>
        <div style={ds.logoMark}>VTC</div>
      </div>

      <div style={ds.body}>
        {/* Stats */}
        <div style={ds.statsRow}>
          <StatCard label={t('thisMonth')} value={stats.month.count} sub="bons" gold />
          <StatCard label={t('caTTC')} value={`${fmt(stats.month.ca)} €`} sub="ce mois" />
          <StatCard label={t('totalBons')} value={stats.total.count} sub="total" />
        </div>

        {/* Recent */}
        <div style={ds.sectionRow}>
          <span style={ds.sectionTitle}>{t('recentBons')}</span>
          {bons.length > 5 && (
            <button style={ds.viewAll} onClick={() => navigate('history')}>{t('viewAll')} →</button>
          )}
        </div>

        {recent.length === 0 ? (
          <div style={ds.empty}>
            <div style={ds.emptyIcon}>📋</div>
            <div style={ds.emptyTitle}>{t('noBons')}</div>
            <div style={ds.emptyHint}>{t('noBonsHint')}</div>
          </div>
        ) : (
          <div style={ds.bonList}>
            {recent.map(bon => (
              <BonCard key={bon.id} bon={bon} fmtDate={fmtDate} fmt={fmt} navigate={navigate} />
            ))}
          </div>
        )}
      </div>

      {/* FAB */}
      <button style={ds.fab} onClick={() => navigate('new')} aria-label={t('newBon')}>
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.2" strokeLinecap="round">
          <line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
        </svg>
      </button>
    </div>
  );
}

function StatCard({ label, value, sub, gold }) {
  return (
    <div style={{ ...ds.statCard, ...(gold ? ds.statCardGold : {}) }}>
      <div style={{ ...ds.statValue, ...(gold ? { color: 'var(--gold)' } : {}) }}>{value}</div>
      <div style={ds.statLabel}>{label}</div>
      <div style={ds.statSub}>{sub}</div>
    </div>
  );
}

function BonCard({ bon, fmtDate, fmt, navigate }) {
  return (
    <div style={ds.bonCard} onClick={() => navigate('preview', { bonId: bon.id })}>
      <div style={ds.bonLeft}>
        <div style={ds.bonClient}>{bon.clientName || '—'}</div>
        <div style={ds.bonSub}>
          {bon.pickupAddress && bon.dropoffAddress
            ? `${bon.pickupAddress.substring(0, 18)}… → ${bon.dropoffAddress.substring(0, 14)}…`
            : bon.pickupAddress || bon.dropoffAddress || ''}
        </div>
        <div style={ds.bonId}>{bon.id}</div>
      </div>
      <div style={ds.bonRight}>
        {bon.priceTTC ? <div style={ds.bonPrice}>{fmt(parseFloat(bon.priceTTC))} €</div> : null}
        <div style={ds.bonDate}>{fmtDate(bon.createdAt)}</div>
        <ChevronRight />
      </div>
    </div>
  );
}

function ChevronRight() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--text-3)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="9 18 15 12 9 6"/>
    </svg>
  );
}

const ds = {
  screen: { display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--bg)' },
  header: {
    background: 'var(--dark)', color: 'white',
    padding: '16px 20px 20px',
    paddingTop: 'calc(16px + var(--safe-top))',
    display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
    flexShrink: 0,
  },
  greeting: { fontSize: 24, fontWeight: 700, letterSpacing: '-0.5px' },
  date: { fontSize: 13, color: 'rgba(255,255,255,0.5)', marginTop: 2, textTransform: 'capitalize' },
  logoMark: {
    width: 44, height: 44, borderRadius: 10,
    background: 'var(--gold)', color: 'white',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontSize: 13, fontWeight: 800, letterSpacing: 1,
  },
  body: { flex: 1, overflowY: 'auto', padding: '20px 16px', paddingBottom: 80, display: 'flex', flexDirection: 'column', gap: 20 },
  statsRow: { display: 'flex', gap: 10 },
  statCard: {
    flex: 1, background: 'var(--surface)', borderRadius: 'var(--radius)',
    padding: '14px 10px', textAlign: 'center',
    boxShadow: 'var(--shadow)', border: '1px solid var(--border)',
  },
  statCardGold: { border: '1.5px solid var(--gold-light)', background: '#fffbf2' },
  statValue: { fontSize: 22, fontWeight: 700, color: 'var(--text)', lineHeight: 1 },
  statLabel: { fontSize: 11, color: 'var(--text-3)', marginTop: 4, fontWeight: 500 },
  statSub: { fontSize: 10, color: 'var(--text-3)', marginTop: 1 },
  sectionRow: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' },
  sectionTitle: { fontSize: 15, fontWeight: 700, color: 'var(--text)' },
  viewAll: { background: 'none', border: 'none', color: 'var(--gold)', fontSize: 13, fontFamily: 'var(--font)', cursor: 'pointer', fontWeight: 600 },
  empty: { textAlign: 'center', padding: '48px 24px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 },
  emptyIcon: { fontSize: 48, marginBottom: 8 },
  emptyTitle: { fontSize: 16, fontWeight: 600, color: 'var(--text)' },
  emptyHint: { fontSize: 14, color: 'var(--text-2)' },
  bonList: { display: 'flex', flexDirection: 'column', gap: 8 },
  bonCard: {
    background: 'var(--surface)', borderRadius: 'var(--radius)',
    padding: '14px 16px', display: 'flex', justifyContent: 'space-between',
    alignItems: 'center', boxShadow: 'var(--shadow)',
    border: '1px solid var(--border)', cursor: 'pointer', gap: 12,
  },
  bonLeft: { flex: 1, minWidth: 0 },
  bonClient: { fontSize: 15, fontWeight: 600, color: 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
  bonSub: { fontSize: 12, color: 'var(--text-2)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
  bonId: { fontSize: 11, color: 'var(--text-3)', marginTop: 3 },
  bonRight: { display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3, flexShrink: 0 },
  bonPrice: { fontSize: 15, fontWeight: 700, color: 'var(--text)' },
  bonDate: { fontSize: 12, color: 'var(--text-2)' },
  fab: {
    position: 'fixed', bottom: 'calc(72px + var(--safe-bottom))', right: 20,
    width: 56, height: 56, borderRadius: 28,
    background: 'var(--dark)', border: 'none',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    boxShadow: '0 4px 16px rgba(0,0,0,0.25)', cursor: 'pointer',
    transition: 'transform 0.15s',
  },
};

Object.assign(window, { Dashboard });
