// Balance screen — calmer, human-first. Big numbers hidden by default (privacy-style dots),
// friendly copy, one simple chart, no ticker-style tiles.
function BalanceScreen({ onBell, setTab, tweaks, openContractRequest }) {
  const [hoverIdx, setHoverIdx] = React.useState(PROJECTION.values.length - 4);
  const [revealed, setRevealed] = React.useState(tweaks.showNumbersDefault);

  React.useEffect(() => { setRevealed(tweaks.showNumbersDefault); }, [tweaks.showNumbersDefault]);

  const values = PROJECTION.values;
  const labels = PROJECTION.labels;
  const actualCount = PROJECTION.actualCount;

  const bhRef = React.useRef(null);
  const onMove = (e) => {
    const r = bhRef.current?.getBoundingClientRect();
    if (!r) return;
    const x = (e.touches ? e.touches[0].clientX : e.clientX) - r.left;
    const i = Math.max(0, Math.min(values.length - 1, Math.round((x / r.width) * (values.length - 1))));
    setHoverIdx(i);
  };

  // Friendly phrasing — no percentages, no ticker-style copy
  const moodCopy = {
    calm:     { greet: 'Todo va bien, Camila', sub: 'Tu dinero está trabajando.' },
    neutral:  { greet: 'Hola, Camila',           sub: 'Esto es lo que tienes hoy.' },
    detailed: { greet: 'Buenos días, Camila',    sub: 'Tu portafolio al ' + fmtDateES(new Date('2026-04-21')) + '.' },
  }[tweaks.tone];

  const hide = !revealed;

  return (
    <div style={{ background: FA.bgSoft, minHeight: '100%', paddingBottom: 120, fontFamily: FA.sans }}>
      {/* Soft hero — much gentler than the bold gradient */}
      <div style={{
        background: tweaks.softHero
          ? 'linear-gradient(180deg, #eff8ff 0%, #f6f9fc 100%)'
          : FA.heroGrad,
        borderRadius: '0 0 28px 28px',
        paddingBottom: 28, position: 'relative', overflow: 'hidden',
      }}>
        {!tweaks.softHero && (
          <>
            <div style={{ position: 'absolute', top: -60, right: -40, width: 220, height: 220, borderRadius: '50%',
              background: 'radial-gradient(circle, rgba(255,255,255,0.22) 0%, transparent 60%)' }}/>
            <div style={{ position: 'absolute', bottom: -80, left: -40, width: 220, height: 220, borderRadius: '50%',
              background: 'radial-gradient(circle, rgba(56,189,248,0.35) 0%, transparent 60%)' }}/>
          </>
        )}

        <AppHeader onBell={onBell} unread={2} theme={tweaks.softHero ? 'light' : 'hero'}/>

        <div style={{ padding: '4px 24px 0' }}>
          <div style={{
            fontSize: 14, fontWeight: 500,
            color: tweaks.softHero ? FA.muted : 'rgba(255,255,255,0.8)',
          }}>{moodCopy.greet}</div>
          <div style={{
            fontSize: 22, fontWeight: 600, letterSpacing: -0.4, marginTop: 6,
            color: tweaks.softHero ? FA.ink : '#fff',
            lineHeight: 1.25,
          }}>{moodCopy.sub}</div>

          {/* Privacy-first balance. Tap to reveal. */}
          <button onClick={() => setRevealed(!revealed)} style={{
            marginTop: 22, background: 'transparent', border: 'none', padding: 0,
            textAlign: 'left', cursor: 'pointer',
          }}>
            <div style={{
              fontSize: 11.5, fontWeight: 500, letterSpacing: 0.6, textTransform: 'uppercase',
              color: tweaks.softHero ? FA.muted : 'rgba(255,255,255,0.72)',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              Disponible
              <span style={{ opacity: 0.6, fontSize: 10 }}>{revealed ? '· toca para ocultar' : '· toca para ver'}</span>
            </div>
            <div style={{
              fontSize: 38, fontWeight: 700,
              color: tweaks.softHero ? FA.ink : '#fff',
              fontFamily: revealed ? FA.mono : FA.sans,
              letterSpacing: -1.2, lineHeight: 1.05, marginTop: 6,
              fontVariantNumeric: 'tabular-nums',
            }}>
              {hide ? '••••••' : fmtUSD(BALANCE.available)}
            </div>
          </button>
        </div>
      </div>

      {/* Simple "what's coming" card — no percentages, no ranges, one clear idea */}
      <div style={{ padding: '16px' }}>
        <Card pad={20}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14,
          }}>
            <div style={{
              width: 34, height: 34, borderRadius: 10, background: FA.skySoft,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="trend" size={17} color={FA.blue} strokeWidth={2}/>
            </div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 650, color: FA.ink, letterSpacing: -0.2 }}>
                Lo que esperas recibir
              </div>
              <div style={{ fontSize: 12, color: FA.muted, marginTop: 1 }}>
                En los próximos meses
              </div>
            </div>
          </div>

          <div ref={bhRef} onMouseMove={onMove} onTouchMove={onMove}
               style={{ position: 'relative', padding: 0, margin: '0 -4px' }}>
            <LineChart points={values} width={320} height={120} stroke={FA.blue}
                       highlight={tweaks.density === 'spacious' ? null : hoverIdx}
                       showGrid={tweaks.density !== 'spacious'}
                       min={Math.min(...values) - 20}/>
            {tweaks.density !== 'spacious' && (
              <div style={{
                position: 'absolute', top: 14, bottom: 22,
                left: `${(actualCount - 0.5) / (values.length - 1) * 100}%`,
                borderLeft: '1px dashed rgba(14,165,233,0.4)', pointerEvents: 'none',
              }}>
                <div style={{
                  position: 'absolute', top: -4, left: -24, fontSize: 9, color: FA.skyDeep,
                  fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5,
                }}>hoy</div>
              </div>
            )}
          </div>

          <div style={{
            display: 'flex', justifyContent: 'space-between',
            padding: '6px 2px 0', fontSize: 10, color: FA.muted,
            fontVariantNumeric: 'tabular-nums',
          }}>
            {labels.filter((_, i) => tweaks.density === 'spacious' ? i % 3 === 0 : true).map((l) => (
              <span key={l}>{l}</span>
            ))}
          </div>

          <div style={{
            marginTop: 18, paddingTop: 14, borderTop: '1px solid ' + FA.hairline,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            <div style={{ fontSize: 13, color: FA.inkSoft, lineHeight: 1.4 }}>
              {hide ? (
                <>Tendencia <span style={{ color: FA.ok, fontWeight: 600 }}>en crecimiento</span></>
              ) : (
                <>Estimado: <span style={{ fontWeight: 650, color: FA.ink, fontFamily: FA.mono }}>{fmtUSD(BALANCE.expected12m)}</span> <span style={{ color: FA.muted }}>en 12 meses</span></>
              )}
            </div>
          </div>
        </Card>
      </div>

      {/* What's next — humanized next action card (replaces stat tiles) */}
      <div style={{ padding: '0 16px 4px' }}>
        <div style={{
          padding: '4px 4px 10px',
          fontSize: 11.5, color: FA.muted, fontWeight: 600,
          textTransform: 'uppercase', letterSpacing: 0.6,
        }}>Qué sigue</div>
        <Card pad={0}>
          <NextRow
            title="En vencimiento · Verde Agro"
            sub="En una semana"
            icon="download" tone="ok"
            onClick={() => openContractRequest && openContractRequest(CONTRACTS.find(c => c.id === 'FA-0419'))}/>
          <NextRow
            title="Firmar con Textiles Norte"
            sub="Mañana · contrato pendiente"
            icon="pen" tone="warn"
            cta="Firmar"
            onClick={() => setTab('contracts')}/>
          <NextRow
            title="Firmar con Hidroeléctrica Chacra"
            sub="Esta semana · contrato pendiente"
            icon="pen" tone="warn"
            cta="Firmar"
            last={tweaks.density === 'spacious'}
            onClick={() => setTab('contracts')}/>
          {tweaks.density !== 'spacious' && (
            <NextRow
              title="3 contratos trabajando para ti"
              sub="Todos al día"
              icon="check" tone="info" last
              onClick={() => setTab('contracts')}/>
          )}
        </Card>
      </div>

      {/* Activity — hidden in spacious mode for maximum calm */}
      {tweaks.density !== 'spacious' && (
        <div style={{ padding: '4px 16px' }}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '14px 4px 8px',
          }}>
            <div style={{ fontSize: 11.5, color: FA.muted, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6 }}>
              Movimientos recientes
            </div>
            <button onClick={() => setTab('contracts')} style={{
              background: 'none', border: 'none', padding: 0,
              fontSize: 12, color: FA.blue, fontWeight: 600, cursor: 'pointer',
            }}>Ver todo</button>
          </div>
          <Card pad={0}>
            <SoftActivityRow label="Pago recibido de Cobre Andino" when="Ayer" kind="in" amount={hide ? null : 135000}/>
            <SoftActivityRow label="Intereses de Grupo Marítimo"   when="hace 3 días" kind="in" amount={hide ? null : 8200}/>
            <SoftActivityRow label="Nueva inversión en Andina"      when="hace 8 días" kind="out" last amount={hide ? null : -25000}/>
          </Card>
        </div>
      )}
    </div>
  );
}

function NextRow({ title, sub, icon, tone, cta, onClick, last }) {
  const tones = {
    warn: { bg: '#fef3c7', fg: '#92400e' },
    ok:   { bg: '#dcfce7', fg: FA.ok },
    info: { bg: FA.skySoft, fg: FA.blue },
  }[tone];
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 14, padding: '16px',
      borderBottom: last ? 'none' : '1px solid ' + FA.hairline,
      border: 'none', background: 'transparent', width: '100%',
      textAlign: 'left', cursor: 'pointer', fontFamily: FA.sans,
    }}>
      <div style={{
        width: 38, height: 38, borderRadius: 12, background: tones.bg,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>
        <Icon name={icon} size={17} color={tones.fg} strokeWidth={2}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: FA.ink, letterSpacing: -0.1 }}>{title}</div>
        <div style={{ fontSize: 12, color: FA.muted, marginTop: 2 }}>{sub}</div>
      </div>
      {cta ? (
        <span style={{
          background: FA.ink, color: '#fff', padding: '7px 12px', borderRadius: 9,
          fontSize: 12, fontWeight: 600,
        }}>{cta}</span>
      ) : (
        <Icon name="chev" size={14} color={FA.muted} strokeWidth={2}/>
      )}
    </button>
  );
}

function SoftActivityRow({ label, when, kind, amount, last }) {
  const isIn = kind === 'in';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
      borderBottom: last ? 'none' : '1px solid ' + FA.hairline,
    }}>
      <div style={{
        width: 8, height: 8, borderRadius: 4,
        background: isIn ? FA.ok : FA.sky, flexShrink: 0, marginLeft: 4,
      }}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, color: FA.ink, fontWeight: 550 }}>{label}</div>
        <div style={{ fontSize: 11.5, color: FA.muted, marginTop: 2 }}>{when}</div>
      </div>
      {amount !== null && amount !== undefined && (
        <div style={{
          fontSize: 13, fontWeight: 600, color: isIn ? FA.ok : FA.inkSoft,
          fontFamily: FA.mono, letterSpacing: -0.2, fontVariantNumeric: 'tabular-nums',
        }}>{fmtUSD(amount, { sign: true })}</div>
      )}
    </div>
  );
}

Object.assign(window, { BalanceScreen });
