// rd-history.jsx — full activity + profile / withdraw / sign out

// activity data — d = days ago, c = country ('br' | 'mx' | null for loads).
// gbp = amount taken from the GBP balance; local = the merchant-side local-currency amount (secondary).
const RD_TX_DATA = [
  { d: 0, label: 'Today', c: 'br', icon: 'cup', name: 'Água de coco', place: 'Quiosque Dois Irmãos', local: 'R$ 12,00', gbp: 1.70 },
  { d: 0, label: 'Today', c: 'br', icon: 'bowl', name: 'Açaí na tigela', place: 'Barraca da Lú', local: 'R$ 24,00', gbp: 3.40 },
  { d: 1, label: 'Yesterday', c: 'br', icon: 'moto', name: 'Moto táxi', place: 'Praia do Forte', local: 'R$ 15,00', gbp: 2.13 },
  { d: 1, label: 'Yesterday', c: null, icon: 'bank', name: 'Balance loaded', place: 'Bank transfer', gbp: 150.00, positive: true, sub: 'instant' },
  { d: 3, label: 'Friday 3 Jul', c: 'br', icon: 'cup', name: 'Café coado', place: 'Mercado Municipal', local: 'R$ 8,00', gbp: 1.13 },
  { d: 3, label: 'Friday 3 Jul', c: 'br', icon: 'bowl', name: 'Moqueca p/ dois', place: 'Restaurante Dona Célia', local: 'R$ 96,00', gbp: 13.62 },
  { d: 18, label: 'Thursday 18 Jun', c: 'mx', icon: 'bowl', name: 'Tacos al pastor', place: 'El Huequito · CDMX', local: 'MX$ 145', gbp: 5.66 },
  { d: 18, label: 'Thursday 18 Jun', c: 'mx', icon: 'cup', name: 'Café de olla', place: 'Mercado Roma', local: 'MX$ 60', gbp: 2.34 },
  { d: 19, label: 'Wednesday 17 Jun', c: 'mx', icon: 'moto', name: 'Museo entrada', place: 'Coyoacán', local: 'MX$ 250', gbp: 9.77 },
  { d: 19, label: 'Wednesday 17 Jun', c: null, icon: 'bank', name: 'Balance loaded', place: 'Bank transfer', gbp: 50.00, positive: true, sub: 'instant' },
  { d: 40, label: 'Wednesday 27 May', c: 'br', icon: 'cup', name: 'Caipirinha', place: 'Bar do Mineiro · Rio', local: 'R$ 28,00', gbp: 3.97 },
  { d: 41, label: 'Tuesday 26 May', c: 'br', icon: 'bowl', name: 'Feijoada completa', place: 'Casa da Feijoada · Rio', local: 'R$ 75,00', gbp: 10.64 },
];

const RD_TX_ICONS = { cup: (p) => <IcCup {...p} />, bowl: (p) => <IcBowl {...p} />, moto: (p) => <IcMoto {...p} />, bank: (p) => <IcBank {...p} /> };
const RD_TX_COUNTRIES = { br: { name: 'Brazil', Flag: FlagBR }, mx: { name: 'Mexico', Flag: FlagMX } };

function RdFilterChip({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 7, padding: '9px 14px', flexShrink: 0, cursor: 'pointer',
      background: active ? RD.ink : RD.paperHi, color: active ? RD.paper : RD.ink,
      border: `1.5px solid ${active ? RD.ink : RD.hairline}`, borderRadius: 'var(--r-chip)',
      fontFamily: RD.ui, fontWeight: 600, fontSize: 13.5, transition: 'background 120ms, color 120ms',
      WebkitTapHighlightColor: 'transparent',
    }}>{children}</button>
  );
}

// drag/swipe-scrollable rail that still lets chip taps through —
// only captures the pointer after ~6px of horizontal movement
function RdFilterRail({ children, bleed = 24 }) {
  const ref = React.useRef(null);
  const st = React.useRef(null);
  const k = () => {
    const el = ref.current, r = el.getBoundingClientRect();
    return r.width ? el.offsetWidth / r.width : 1;
  };
  const down = (e) => { st.current = { x: e.clientX * k(), s: ref.current.scrollLeft, drag: false, id: e.pointerId }; };
  const move = (e) => {
    if (!st.current) return;
    const dx = e.clientX * k() - st.current.x;
    if (!st.current.drag && Math.abs(dx) > 6) {
      st.current.drag = true;
      try { ref.current.setPointerCapture(st.current.id); } catch (err) {}
    }
    if (st.current.drag) ref.current.scrollLeft = st.current.s - dx;
  };
  const up = (e) => {
    if (st.current && st.current.drag) e.preventDefault();
    st.current = null;
  };
  return (
    <div style={{ position: 'relative', margin: `18px ${-bleed}px 0` }}>
      <div ref={ref} className="no-scrollbar" onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up}
        style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: `0 ${bleed}px`, cursor: 'grab', touchAction: 'pan-x', userSelect: 'none' }}>
        {children}
      </div>
      <div style={{ position: 'absolute', top: 0, bottom: 0, right: 0, width: 40, pointerEvents: 'none', background: 'linear-gradient(90deg, rgba(244,241,232,0), var(--paper))' }}></div>
    </div>
  );
}

function RdHistory({ grain = true, onBack }) {
  const [days, setDays] = React.useState(30);   // 7 | 30 | 90
  const [country, setCountry] = React.useState('all'); // all | br | mx

  const inPeriod = RD_TX_DATA.filter(tx => tx.d < days);
  const txs = inPeriod.filter(tx => country === 'all' || tx.c === country);
  const spend = txs.filter(tx => !tx.positive);
  const total = spend.reduce((s, tx) => s + tx.gbp, 0);

  // per-country split within the period (spend only)
  const split = ['br', 'mx'].map(c => {
    const rows = inPeriod.filter(tx => tx.c === c && !tx.positive);
    return { c, ...RD_TX_COUNTRIES[c], count: rows.length, gbp: rows.reduce((s, tx) => s + tx.gbp, 0) };
  }).filter(s => s.count > 0);
  const maxGbp = Math.max(...split.map(s => s.gbp), 1);

  // group filtered txs by date label
  const groups = [];
  txs.forEach(tx => {
    const g = groups[groups.length - 1];
    if (g && g.label === tx.label) g.rows.push(tx); else groups.push({ label: tx.label, rows: [tx] });
  });

  return (
    <RdScreen label="Activity" grain={grain}>
      <div className="no-scrollbar" style={{ height: '100%', overflowY: 'auto', padding: '66px 24px 42px' }}>
        <RdTopBar title="Activity" onBack={onBack} />

        {/* total spend for the selected period — the headline number */}
        <div style={{ marginTop: 24, padding: '20px 20px 22px', background: RD.ink, borderRadius: 'var(--r-card)', color: RD.paper, position: 'relative', overflow: 'hidden' }}>
          <div className="rd-label" style={{ color: 'rgba(244,241,232,0.6)' }}>
            Total spend · last {days} days{country !== 'all' ? ' · ' + RD_TX_COUNTRIES[country].name : ''}
          </div>
          <div className="rd-display rd-num" style={{ fontSize: 46, color: '#fff', marginTop: 10 }}>{fmtGBPNum(total)}</div>
          <div className="rd-body rd-num" style={{ fontSize: 14, color: 'rgba(244,241,232,0.75)', marginTop: 6 }}>
            {spend.length} payment{spend.length === 1 ? '' : 's'} · zero card fees · rate locked per payment
          </div>

          {/* by country — quiet bars, only when comparing */}
          {country === 'all' && split.length > 1 && (
            <div style={{ marginTop: 18, paddingTop: 16, borderTop: '1.5px solid rgba(244,241,232,0.14)' }}>
              {split.map((s, i) => (
                <div key={s.c} style={{ marginTop: i === 0 ? 0 : 12 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <s.Flag w={15} />
                    <span className="rd-h3" style={{ fontSize: 13.5, color: RD.paper, flex: 1 }}>{s.name}</span>
                    <span className="rd-num" style={{ fontFamily: RD.ui, fontWeight: 700, fontSize: 13.5, color: '#fff' }}>{fmtGBPNum(s.gbp)}</span>
                  </div>
                  <div style={{ height: 5, borderRadius: 3, background: 'rgba(244,241,232,0.14)', marginTop: 7, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${(s.gbp / maxGbp) * 100}%`, borderRadius: 3, background: RD.teal }}></div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* filters — period, then country; drag or swipe to scroll */}
        <RdFilterRail bleed={24}>
          {[7, 30, 90].map(dd => (
            <RdFilterChip key={dd} active={days === dd} onClick={() => setDays(dd)}>{dd} days</RdFilterChip>
          ))}
          <div style={{ width: 1.5, alignSelf: 'stretch', background: RD.hairline, flexShrink: 0, margin: '4px 2px' }}></div>
          <RdFilterChip active={country === 'all'} onClick={() => setCountry('all')}>All</RdFilterChip>
          {['br', 'mx'].map(c => {
            const C = RD_TX_COUNTRIES[c];
            return <RdFilterChip key={c} active={country === c} onClick={() => setCountry(c)}><C.Flag w={15} />{C.name}</RdFilterChip>;
          })}
        </RdFilterRail>

        {/* grouped list */}
        {groups.length === 0 ? (
          <div className="rd-body" style={{ fontSize: 15, color: RD.ink3, marginTop: 36, textAlign: 'center' }}>
            No payments {country !== 'all' ? 'in ' + RD_TX_COUNTRIES[country].name + ' ' : ''}in the last {days} days.
          </div>
        ) : groups.map(g => (
          <React.Fragment key={g.label}>
            <div className="rd-label" style={{ color: RD.ink3, margin: '22px 0 4px' }}>{g.label}</div>
            {g.rows.map((tx, i) => {
              const C = tx.c ? RD_TX_COUNTRIES[tx.c] : null;
              const primary = (tx.positive ? '+' : '−') + '£' + tx.gbp.toFixed(2);
              return <RdActivityRow key={tx.name + i} Icon={RD_TX_ICONS[tx.icon]} Flag={C && C.Flag}
                name={tx.name} place={tx.place} local={primary}
                secondary={tx.positive ? tx.sub : tx.local} positive={tx.positive} last={i === g.rows.length - 1} />;
            })}
          </React.Fragment>
        ))}
      </div>
    </RdScreen>
  );
}

function RdProfileRow({ Icon, label, value, valueColor, last = false }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '15px 0', borderBottom: last ? 'none' : `1.5px solid ${RD.hairline}` }}>
      <Icon size={20} color={RD.ink2} />
      <span className="rd-body" style={{ fontSize: 15, color: RD.ink2, flex: 1 }}>{label}</span>
      <span className="rd-h3 rd-num" style={{ fontSize: 15, color: valueColor || RD.ink }}>{value}</span>
    </div>
  );
}

function RdRailRow({ Flag, name, rail, Mark, status, statusColor, last = false }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '14px 0', borderBottom: last ? 'none' : `1.5px solid ${RD.hairline}` }}>
      <Flag w={18} />
      <span className="rd-h3" style={{ fontSize: 15, color: RD.ink }}>{name}</span>
      {Mark ? <Mark h={12} /> : <span className="rd-num" style={{ fontFamily: RD.ui, fontWeight: 600, fontSize: 12.5, color: RD.ink3 }}>{rail}</span>}
      <span style={{ flex: 1 }}></span>
      <span className="rd-h3" style={{ fontSize: 13.5, color: statusColor }}>{status}</span>
    </div>
  );
}

function RdProfile({ grain = true, live = true, staticPhase, pixApproved = true, onBack, onSignOut }) {
  const [phase, setPhase] = React.useState(staticPhase || 'main'); // main | withdraw | sent
  const [cents, setCents] = React.useState(5000); // GBP cents
  const timer = React.useRef(null);
  React.useEffect(() => () => clearTimeout(timer.current), []);
  const BAL = 14250;
  const over = cents > BAL;
  const key = (k) => setCents(c => k === 'del' ? Math.floor(c / 10) : Math.min(c * 10 + Number(k), 99999999));

  if (phase === 'withdraw' || phase === 'sent') {
    const sent = phase === 'sent';
    return (
      <RdScreen label="Withdraw" grain={grain}>
        <div style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '66px 24px 42px' }}>
          <RdTopBar title="Withdraw" onBack={() => setPhase('main')} />
          {sent ? (
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', paddingTop: 44 }}>
              <div style={{ width: 74, height: 74, borderRadius: '50%', background: RD.teal, display: 'flex', alignItems: 'center', justifyContent: 'center', animation: live ? 'rd-pop 300ms ease both' : 'none' }}>
                <IcCheck size={40} color={RD.tealInk} />
              </div>
              <div className="rd-display" style={{ fontSize: 40, color: RD.ink, marginTop: 24 }}>On its way.</div>
              <div className="rd-body" style={{ fontSize: 16, color: RD.ink2, marginTop: 10, maxWidth: 320 }}>
                {fmtGBP(cents)} is heading back to Monzo. No conversion, no fee — back in your account within 2 hours.
              </div>
              <div style={{ flex: 1 }}></div>
              <RdButton kind="ink" onClick={onBack} style={{ minHeight: 64 }}>Done</RdButton>
            </div>
          ) : (
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', paddingTop: 16 }}>
              <div className="rd-label" style={{ color: RD.ink3 }}>Back to Monzo</div>
              <div className="rd-display rd-num" style={{ fontSize: 58, color: over ? RD.coral : RD.ink, marginTop: 8 }}>{fmtGBP(cents)}</div>
              <div className="rd-body" style={{ fontSize: 14.5, color: RD.ink2, marginTop: 14, paddingTop: 12, borderTop: `1.5px solid ${RD.hairline}`, display: 'flex', alignItems: 'center', gap: 7 }}>
                {over ? (<span style={{ color: RD.ink2 }}>You have {fmtGBP(BAL)} available</span>) : (<><IcCheck size={15} color={RD.tealDeep} />No conversion, no fee.</>)}
              </div>
              <button onClick={() => setCents(BAL)} style={{ alignSelf: 'flex-start', marginTop: 12, padding: '8px 14px', background: RD.paperHi, border: `1.5px solid ${RD.hairline}`, borderRadius: 'var(--r-chip)', fontFamily: RD.ui, fontWeight: 600, fontSize: 13.5, color: RD.ink, cursor: 'pointer' }}>Withdraw all · {fmtGBP(BAL)}</button>
              <div style={{ flex: 1 }}></div>
              <RdKeypad onKey={key} />
              <RdButton kind="primary" onClick={() => { if (live && !over && cents > 0) setPhase('sent'); }} style={{ minHeight: 66, marginTop: 14, opacity: over || cents === 0 ? 0.45 : 1 }}>
                {over ? 'Not enough balance' : 'Withdraw ' + fmtGBP(cents)}
              </RdButton>
            </div>
          )}
        </div>
      </RdScreen>
    );
  }

  return (
    <RdScreen label="Profile" grain={grain}>
      <div className="no-scrollbar" style={{ height: '100%', overflowY: 'auto', padding: '66px 24px 42px', display: 'flex', flexDirection: 'column' }}>
        <RdTopBar title="Profile" onBack={onBack} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 15, marginTop: 26 }}>
          <div style={{ width: 62, height: 62, borderRadius: '50%', background: RD.ink, color: RD.paper, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: RD.disp, fontWeight: 800, fontSize: 21 }}>GC</div>
          <div>
            <div className="rd-h1" style={{ fontSize: 24, color: RD.ink }}>George Coulter</div>
            <div className="rd-body" style={{ fontSize: 14, color: RD.ink3, marginTop: 2 }}>george.coulter@gmail.com</div>
          </div>
        </div>

        <div style={{ marginTop: 26 }}>
          <RdProfileRow Icon={IcShield} label="Passport" value="Verified ✓" valueColor={RD.tealDeep} />
          <RdProfileRow Icon={IcBank} label="Home bank" value="Monzo · linked" />
          <RdProfileRow Icon={IcUser} label="Home currency" value="GBP" />
          <RdProfileRow Icon={IcClockEnd} label="Daily limit" value="R$ 3.000" last={true} />
        </div>

        {/* payment networks — which local rails are approved for this account */}
        <div className="rd-label" style={{ color: RD.ink3, margin: '28px 0 2px' }}>Pay like a local in</div>
        <RdRailRow Flag={FlagBR} name="Brazil" Mark={PixMark}
          status={pixApproved ? 'Approved ✓' : 'Pending…'}
          statusColor={pixApproved ? RD.tealDeep : RD.sunset} />
        <RdRailRow Flag={FlagCO} name="Colombia" rail="Bre-B" status="Coming soon" statusColor={RD.ink3} />
        <RdRailRow Flag={FlagMX} name="Mexico" rail="SPEI" status="Coming soon" statusColor={RD.ink3} />
        <RdRailRow Flag={FlagAR} name="Argentina" rail="MODO" status="Coming soon" statusColor={RD.ink3} />
        <RdRailRow Flag={FlagBO} name="Bolivia" rail="QR Simple" status="Coming soon" statusColor={RD.ink3} last={true} />

        <div style={{ flex: 1, minHeight: 30 }}></div>
        <RdButton kind="paper" onClick={() => setPhase('withdraw')} style={{ minHeight: 60, fontSize: 17 }}
          icon={<IcOut size={20} color={RD.ink} />}>Withdraw to bank</RdButton>
        <RdButton kind="ghost" onClick={onSignOut} style={{ marginTop: 8 }}>Sign out</RdButton>
      </div>
    </RdScreen>
  );
}

Object.assign(window, { RdHistory, RdProfile, RdProfileRow, RdRailRow });
