// pesito — Live Calculator with iOS sliders + honest results

const Calculator = ({ lang, principal, setPrincipal, term, setTerm }) => {
  // formula: daily 0.30%, comisión apertura 2%, total = principal*(1+daily*14*term) approx
  const dailyRate = 0.003;
  const apertura = Math.round(principal * 0.02);
  const interest = principal * dailyRate * 14 * term;
  const total = Math.round(principal + interest + apertura);
  const quincenal = Math.round(total / term);
  // CAT illustrative — scales with term, fixed range to feel honest
  const cat = Math.round(420 + (term <= 4 ? 180 : term <= 8 ? 100 : term <= 16 ? 30 : -40));

  const t = lang === 'es' ? {
    eyebrow: 'Calculadora honesta',
    title: ['¿Cuánto', 'vas a pagar?'],
    sub: 'Mueve los dos botones. Los números se mueven contigo. Sin asteriscos, sin sorpresas.',
    monto: 'Monto',
    plazo: 'Plazo',
    quincenas: 'quincenas',
    quincena: 'quincena',
    pagoQuincenal: 'Pago quincenal',
    cat: 'CAT informativo',
    catNote: 'sin IVA',
    tasaDiaria: 'Tasa diaria',
    apertura: 'Comisión apertura',
    apertura2: 'única, 2% del monto',
    total: 'Total a pagar',
    sinPenal: 'Págalo antes y se baja. Sin penalización, palabra de pesito.',
    cta: 'Pedir este préstamo',
    chips: ['Sin asterisco', 'Sin penalización', 'CAT a la vista', 'SPEI directo'],
  } : {
    eyebrow: 'Честный калькулятор',
    title: ['Сколько', 'вы заплатите?'],
    sub: 'Двигайте две ручки. Цифры двигаются с вами. Без звёздочек, без сюрпризов.',
    monto: 'Сумма',
    plazo: 'Срок',
    quincenas: 'двухнед.',
    quincena: 'двухнед.',
    pagoQuincenal: 'Платёж раз в 2 нед.',
    cat: 'Полная стоимость (CAT)',
    catNote: 'без НДС',
    tasaDiaria: 'Дневная ставка',
    apertura: 'Комиссия за открытие',
    apertura2: 'одноразово, 2%',
    total: 'Всего к оплате',
    sinPenal: 'Заплатите раньше — заплатите меньше. Без штрафа, слово pesito.',
    cta: 'Взять этот заём',
    chips: ['Без звёздочек', 'Без штрафов', 'CAT на виду', 'SPEI напрямую'],
  };

  const principalPct = ((principal - 500) / (50000 - 500)) * 100;
  const termPct = ((term - 2) / (24 - 2)) * 100;

  // Build "lo que te ahorras" comparison vs predatory lender at CAT 1200%
  const competitorTotal = Math.round(principal + (principal * 0.0085 * 14 * term) + apertura);
  const savings = competitorTotal - total;

  return (
    <section id="calc" className="section">
      <div className="wrap">
        <div style={{ maxWidth: 720, marginBottom: 40 }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>{t.eyebrow}</div>
          <h2 className="display" style={{ fontSize: 'clamp(40px, 6vw, 76px)', margin: 0, fontWeight: 600 }}>
            {t.title[0]}<br/>
            <span style={{ color: 'var(--brand)' }}>{t.title[1]}</span>
          </h2>
          <p style={{ fontSize: 17, color: 'var(--char-2)', marginTop: 16, maxWidth: 540 }}>{t.sub}</p>
        </div>

        <div className="calc-grid">
          {/* Inputs panel */}
          <div className="card" style={{ padding: 28 }}>
            {/* Monto */}
            <div style={{ marginBottom: 32 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-soft)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{t.monto}</span>
                <span className="display tabular" style={{ fontSize: 40, fontWeight: 600, lineHeight: 1 }}>
                  <Rolling value={principal} format={(v) => '$' + Math.round(v).toLocaleString('en-US')} />
                  <span style={{ fontSize: 16, color: 'var(--ink-soft)', marginLeft: 6 }}>MXN</span>
                </span>
              </div>
              <input type="range" className="ios" min="500" max="50000" step="500"
                value={principal} onChange={(e) => setPrincipal(+e.target.value)}
                style={{ '--p': principalPct + '%' }} />
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-soft)', marginTop: 4 }}>
                <span>$500</span><span>$50,000</span>
              </div>
            </div>

            {/* Plazo */}
            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-soft)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{t.plazo}</span>
                <span className="display tabular" style={{ fontSize: 40, fontWeight: 600, lineHeight: 1 }}>
                  {term}<span style={{ fontSize: 14, color: 'var(--ink-soft)', marginLeft: 8, fontFamily: 'var(--font-body)', fontWeight: 500 }}>{term === 1 ? t.quincena : t.quincenas}</span>
                </span>
              </div>
              <input type="range" className="ios" min="2" max="24" step="1"
                value={term} onChange={(e) => setTerm(+e.target.value)}
                style={{ '--p': termPct + '%' }} />
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-soft)', marginTop: 4 }}>
                <span>2</span>
                <span>{lang === 'es' ? `≈ ${Math.round(term * 14 / 30 * 10) / 10} meses` : `≈ ${Math.round(term * 14 / 30 * 10) / 10} мес.`}</span>
                <span>24</span>
              </div>
            </div>

            {/* chips of trust */}
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 28, paddingTop: 20, borderTop: '1px solid var(--line)' }}>
              {t.chips.map((c, i) => (
                <span key={i} className="chip">
                  <span style={{ width: 5, height: 5, borderRadius: 999, background: 'var(--green)', display: 'inline-block' }} />
                  {c}
                </span>
              ))}
            </div>
          </div>

          {/* Results panel */}
          <div className="card-ink" style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 0, position: 'relative', overflow: 'hidden' }}>
            {/* corner accent */}
            <div style={{ position: 'absolute', top: 0, right: 0, width: 120, height: 120,
              background: 'radial-gradient(circle at top right, oklch(0.55 0.17 28 / 0.5), transparent 70%)' }} />

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
              <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase', letterSpacing: '0.12em', fontWeight: 600 }}>
                {t.pagoQuincenal}
              </span>
              <span style={{
                fontSize: 10, fontFamily: 'var(--font-mono)', color: 'rgba(255,255,255,0.5)',
                border: '1px solid rgba(255,255,255,0.15)',
                padding: '2px 6px', borderRadius: 4,
              }}>SOFOM · MX</span>
            </div>

            <div className="display tabular" style={{ fontSize: 'clamp(64px, 9vw, 96px)', fontWeight: 600, lineHeight: 0.95, color: '#fff', marginBottom: 4 }}>
              <Rolling value={quincenal} format={(v) => '$' + Math.round(v).toLocaleString('en-US')} />
            </div>
            <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.6)', marginBottom: 28 }}>
              {lang === 'es' ? `cada 14 días, ${term} veces` : `каждые 14 дней, ${term} раз`}
            </div>

            {/* breakdown rows */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14, paddingTop: 20, borderTop: '1px solid rgba(255,255,255,0.12)' }}>
              <CalcRow label={t.cat} value={cat + '%'} note={t.catNote} accent="var(--brand)" />
              <CalcRow label={t.tasaDiaria} value="0.30%" note={lang === 'es' ? 'fija' : 'фикс.'} />
              <CalcRow label={t.apertura} value={'$' + apertura.toLocaleString('en-US')} note={t.apertura2} />
              <div style={{ borderTop: '1px dashed rgba(255,255,255,0.15)', marginTop: 4, paddingTop: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span style={{ fontSize: 14, color: 'rgba(255,255,255,0.7)' }}>{t.total}</span>
                <span className="display tabular" style={{ fontSize: 32, fontWeight: 600, color: '#fff' }}>
                  <Rolling value={total} format={(v) => '$' + Math.round(v).toLocaleString('en-US')} />
                </span>
              </div>
            </div>

            <div style={{
              marginTop: 22, padding: 14,
              background: 'rgba(255,255,255,0.06)',
              borderRadius: 12,
              fontSize: 13, color: 'rgba(255,255,255,0.85)',
              display: 'flex', gap: 10, alignItems: 'flex-start',
            }}>
              <I.sparkle style={{ flexShrink: 0, marginTop: 2, color: 'var(--sun)' }} />
              <span>{t.sinPenal}</span>
            </div>
          </div>
        </div>

        {/* mini comparativa */}
        <div style={{ marginTop: 32 }}>
          <ComparisonStrip lang={lang} our={total} their={competitorTotal} savings={savings} principal={principal} />
        </div>
      </div>
    </section>
  );
};

const CalcRow = ({ label, value, note, accent }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', marginBottom: 2 }}>{label}</div>
      {note && <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)', fontFamily: 'var(--font-mono)' }}>{note}</div>}
    </div>
    <div className="display tabular" style={{ fontSize: 22, fontWeight: 600, color: accent || '#fff', lineHeight: 1.1, flexShrink: 0 }}>{value}</div>
  </div>
);

const ComparisonStrip = ({ lang, our, their, savings, principal }) => {
  const t = lang === 'es' ? {
    title: 'Lo mismo, en otro lado',
    sub: 'Mismo monto, mismo plazo, en una financiera "rápida y fácil" típica del país.',
    them: 'Otra financiera',
    us: 'pesito',
    save: 'Te ahorras',
    note: 'Tomado de promedios de mercado en CAT 1,200%. La mentira más cara siempre es la que no leíste.',
  } : {
    title: 'То же самое, в другом месте',
    sub: 'Та же сумма, тот же срок, у типичного "быстрого" кредитора.',
    them: 'Другой кредитор',
    us: 'pesito',
    save: 'Вы экономите',
    note: 'По средним рыночным CAT 1200%. Самая дорогая ложь — та, которую вы не прочитали.',
  };
  const ourPct = (our / their) * 100;
  return (
    <div className="card" style={{ padding: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 4 }}>{t.title}</div>
          <div style={{ fontSize: 14, color: 'var(--char-2)', maxWidth: 460 }}>{t.sub}</div>
        </div>
        <div className="chip chip-green" style={{ fontSize: 14, padding: '6px 14px' }}>
          <I.sparkle /> {t.save} ${savings.toLocaleString('en-US')} MXN
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <BarRow label={t.them} value={'$' + their.toLocaleString('en-US')} pct={100} color="var(--surface-3)" textColor="var(--char-2)" />
        <BarRow label={t.us} value={'$' + our.toLocaleString('en-US')} pct={ourPct} color="var(--brand)" textColor="#fff" highlight />
      </div>

      <div style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 14, fontStyle: 'italic' }}>{t.note}</div>
    </div>
  );
};

const BarRow = ({ label, value, pct, color, textColor, highlight }) => (
  <div>
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 6 }}>
      <span style={{ fontWeight: 600, color: highlight ? 'var(--brand)' : 'var(--char)' }}>{label}</span>
      <span className="tabular" style={{ fontWeight: 600 }}>{value}</span>
    </div>
    <div style={{ height: 32, background: 'var(--surface-2)', borderRadius: 8, position: 'relative', overflow: 'hidden' }}>
      <div style={{
        width: pct + '%',
        height: '100%',
        background: color,
        borderRadius: 8,
        transition: 'width 400ms cubic-bezier(0.2, 0.8, 0.2, 1)',
        display: 'flex', alignItems: 'center', justifyContent: 'flex-end',
        paddingRight: 12,
        color: textColor,
        fontSize: 12, fontWeight: 600,
      }} />
    </div>
  </div>
);

Object.assign(window, { Calculator });
