const { useState, useEffect } = React;

function History() {
  const { navigate, t, bons, refreshBons } = window.useApp();
  const [query, setQuery] = useState('');

  useEffect(() => { refreshBons(); }, []);

  const filtered = bons.filter(b =>
    !query || b.clientName?.toLowerCase().includes(query.toLowerCase()) ||
    b.id?.toLowerCase().includes(query.toLowerCase()) ||
    b.pickupAddress?.toLowerCase().includes(query.toLowerCase()) ||
    b.dropoffAddress?.toLowerCase().includes(query.toLowerCase())
  );

  const fmtDate = (iso) => new Date(iso).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short', year: 'numeric' });
  const fmtPrice = (v) => v ? `${parseFloat(v).toLocaleString('fr-FR', { minimumFractionDigits: 2 })} €` : null;

  return (
    <div style={hs.screen}>
      <div style={hs.header}>
        <span style={hs.headerTitle}>{t('historyTitle')}</span>
        <span style={hs.count}>{bons.length} bon{bons.length !== 1 ? 's' : ''}</span>
      </div>

      {/* Search */}
      <div style={hs.searchWrap}>
        <div style={hs.searchInner}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--text-3)" strokeWidth="2" strokeLinecap="round" style={{ flexShrink: 0 }}>
            <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
          </svg>
          <input
            style={hs.searchInput}
            placeholder={t('searchPlaceholder')}
            value={query}
            onChange={e => setQuery(e.target.value)}
          />
          {query && (
            <button style={hs.clearBtn} onClick={() => setQuery('')}>✕</button>
          )}
        </div>
      </div>

      <div style={hs.list}>
        {filtered.length === 0 ? (
          <div style={hs.empty}>
            {query ? t('noResults') : t('noBons')}
          </div>
        ) : (
          filtered.map(bon => (
            <div key={bon.id} style={hs.card} onClick={() => navigate('preview', { bonId: bon.id })}>
              <div style={hs.cardLeft}>
                <div style={hs.clientName}>{bon.clientName || '—'}</div>
                {(bon.pickupAddress || bon.dropoffAddress) && (
                  <div style={hs.route}>
                    <span style={hs.routeDot}>📍</span>
                    <span style={hs.routeText}>{bon.pickupAddress || '?'}</span>
                    <span style={hs.routeArrow}>→</span>
                    <span style={hs.routeText}>{bon.dropoffAddress || '?'}</span>
                  </div>
                )}
                <div style={hs.meta}>
                  <span style={hs.bonId}>{bon.id}</span>
                  <span style={hs.dot}>·</span>
                  <span style={hs.metaDate}>{fmtDate(bon.createdAt)}</span>
                </div>
              </div>
              <div style={hs.cardRight}>
                {fmtPrice(bon.priceTTC) && <div style={hs.price}>{fmtPrice(bon.priceTTC)}</div>}
                <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>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

const hs = {
  screen: { display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--bg)' },
  header: {
    background: 'var(--dark)', color: '#fff',
    padding: '16px 20px 14px',
    paddingTop: 'calc(16px + var(--safe-top))',
    display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
    flexShrink: 0,
  },
  headerTitle: { fontSize: 22, fontWeight: 700, letterSpacing: '-0.4px' },
  count: { fontSize: 13, color: 'rgba(255,255,255,0.5)', paddingBottom: 2 },
  searchWrap: { background: 'var(--dark)', padding: '0 16px 14px', flexShrink: 0 },
  searchInner: {
    display: 'flex', alignItems: 'center', gap: 8,
    background: 'rgba(255,255,255,0.1)', borderRadius: 'var(--radius-sm)',
    padding: '9px 12px',
  },
  searchInput: {
    flex: 1, background: 'none', border: 'none', outline: 'none',
    color: '#fff', fontSize: 15, fontFamily: 'var(--font)',
  },
  clearBtn: { background: 'none', border: 'none', color: 'rgba(255,255,255,0.5)', cursor: 'pointer', fontSize: 14 },
  list: { flex: 1, overflowY: 'auto', padding: '12px 16px', paddingBottom: 80, display: 'flex', flexDirection: 'column', gap: 8 },
  empty: { textAlign: 'center', color: 'var(--text-2)', fontSize: 15, padding: 40 },
  card: {
    background: 'var(--surface)', borderRadius: 'var(--radius)',
    padding: '14px 14px', display: 'flex', justifyContent: 'space-between',
    alignItems: 'center', border: '1px solid var(--border)',
    boxShadow: 'var(--shadow)', cursor: 'pointer', gap: 10,
  },
  cardLeft: { flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 3 },
  clientName: { fontSize: 15, fontWeight: 700, color: 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
  route: { display: 'flex', alignItems: 'center', gap: 3, fontSize: 12, color: 'var(--text-2)' },
  routeDot: { fontSize: 10 },
  routeText: { maxWidth: 90, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
  routeArrow: { color: 'var(--text-3)', flexShrink: 0 },
  meta: { display: 'flex', alignItems: 'center', gap: 5, marginTop: 1 },
  bonId: { fontSize: 11, color: 'var(--gold-dark)', fontWeight: 600 },
  dot: { fontSize: 10, color: 'var(--text-3)' },
  metaDate: { fontSize: 11, color: 'var(--text-3)' },
  cardRight: { display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4, flexShrink: 0 },
  price: { fontSize: 15, fontWeight: 700, color: 'var(--text)' },
};

Object.assign(window, { History });
