// checkout.jsx — Payment screen (Desktop + Mobile). Credit card + IBAN tabs.

const { useState: _pS, useState } = React;

function luhnMask(v) {
  const digits = v.replace(/\D/g, '').slice(0, 16);
  return digits.replace(/(.{4})/g, '$1 ').trim();
}
function expMask(v) {
  const d = v.replace(/\D/g, '').slice(0, 4);
  if (d.length <= 2) return d;
  return d.slice(0, 2) + '/' + d.slice(2);
}

function CheckoutCard({ L, lang, listing }) {
  const l = listing;
  const subtotal = l.price;
  const buyerFee = Math.round(subtotal * 0.05); // %5 alıcı komisyonu (escrow + KDV)
  const total = subtotal + buyerFee;
  const sellerFee = Math.round(subtotal * 0.05); // %5 satıcı komisyonu (info only)
  const sellerNet = subtotal - sellerFee;

  const [method, setMethod] = _pS('card');
  const [card, setCard] = _pS({ num: '4242 4242 4242 4242', name: 'SERHAT AKIN', exp: '09/28', cvv: '•••' });
  const [installment, setInstallment] = _pS(1);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 28, alignItems: 'flex-start' }}>
      {/* LEFT — method picker + form */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        {/* Method tabs */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <MethodCard active={method === 'card'} onClick={() => setMethod('card')}
                      icon="tag" title={L.pay_method_card} sub="Visa · Mastercard · Troy"/>
          <MethodCard active={method === 'iban'} onClick={() => setMethod('iban')}
                      icon="shield" title={L.pay_method_iban} sub="Anlık · masrafsız"/>
        </div>

        {method === 'card' ? (
          <div className="is-card" style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
            {/* Visual card preview */}
            <div style={{
              position: 'relative', padding: 20, borderRadius: 16, color: '#fff',
              background: 'var(--grad)', boxShadow: '0 14px 40px -12px oklch(0.66 0.25 350 / 0.5)',
              overflow: 'hidden', minHeight: 160,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', opacity: 0.9 }}>instasatis · secure</span>
                <span style={{ width: 34, height: 24, borderRadius: 4, background: 'linear-gradient(135deg, rgba(255,255,255,.85), rgba(255,255,255,.55))' }}/>
              </div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 22, letterSpacing: '.14em', marginTop: 28, fontWeight: 500 }}>
                {card.num || '•••• •••• •••• ••••'}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16, fontFamily: 'var(--font-mono)', fontSize: 11 }}>
                <div>
                  <div style={{ opacity: 0.7, fontSize: 9, letterSpacing: '.1em' }}>CARD HOLDER</div>
                  <div style={{ marginTop: 2, fontSize: 13 }}>{card.name || '—'}</div>
                </div>
                <div>
                  <div style={{ opacity: 0.7, fontSize: 9, letterSpacing: '.1em' }}>EXPIRES</div>
                  <div style={{ marginTop: 2, fontSize: 13 }}>{card.exp || '••/••'}</div>
                </div>
              </div>
              <div style={{ position: 'absolute', right: -20, top: -20, width: 110, height: 110, borderRadius: '50%', background: 'rgba(255,255,255,.12)' }}/>
            </div>

            <div>
              <Label>{L.pay_card_number}</Label>
              <input className="is-input" value={card.num} onChange={e => setCard({ ...card, num: luhnMask(e.target.value) })} inputMode="numeric"/>
            </div>
            <div>
              <Label>{L.pay_card_name}</Label>
              <input className="is-input" value={card.name} onChange={e => setCard({ ...card, name: e.target.value.toUpperCase() })}/>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <div>
                <Label>{L.pay_card_exp}</Label>
                <input className="is-input" value={card.exp} onChange={e => setCard({ ...card, exp: expMask(e.target.value) })} placeholder="MM/YY"/>
              </div>
              <div>
                <Label>{L.pay_card_cvv}</Label>
                <input className="is-input" value={card.cvv} onChange={e => setCard({ ...card, cvv: e.target.value.replace(/\D/g,'').slice(0,4) })} placeholder="•••"/>
              </div>
            </div>

            {/* Installments */}
            <div>
              <Label>{L.pay_installment}</Label>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
                {[1, 3, 6, 9].map(n => {
                  const per = Math.ceil(total / n);
                  return (
                    <button key={n} onClick={() => setInstallment(n)}
                            style={{
                              border: 0, padding: '10px 8px', borderRadius: 10, cursor: 'pointer',
                              background: installment === n ? 'var(--grad)' : 'var(--chip)',
                              color: installment === n ? '#fff' : 'var(--ink-2)',
                              display: 'flex', flexDirection: 'column', gap: 2, textAlign: 'center',
                            }}>
                      <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14 }}>{n === 1 ? 'Tek' : n}</span>
                      <span style={{ fontSize: 10, opacity: .85, fontFamily: 'var(--font-mono)' }}>{fmtPrice(per, lang)}</span>
                    </button>
                  );
                })}
              </div>
            </div>

            <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--ink-3)', fontSize: 12 }}>
              <Icon name="lock" size={12}/> {L.pay_3d}
            </div>
          </div>
        ) : (
          <div className="is-card" style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ display: 'flex', gap: 10 }}>
              <div style={{ flex: 1, padding: 14, borderRadius: 12, background: 'var(--chip)' }}>
                <div className="is-kicker" style={{ marginBottom: 6 }}>{L.pay_iban_owner}</div>
                <div style={{ fontWeight: 600 }}>OKxProject Yazılım A.Ş.</div>
              </div>
              <div style={{ padding: 14, borderRadius: 12, background: 'var(--chip)' }}>
                <div className="is-kicker" style={{ marginBottom: 6 }}>Banka</div>
                <div style={{ fontWeight: 600 }}>Garanti BBVA</div>
              </div>
            </div>

            <div>
              <Label>{L.pay_iban_num}</Label>
              <div style={{ position: 'relative' }}>
                <input className="is-input" readOnly value="TR33 0006 2000 1234 0006 6677 88" style={{ fontFamily: 'var(--font-mono)', letterSpacing: '.06em' }}/>
                <button style={{ position: 'absolute', right: 6, top: 6, padding: '6px 10px', borderRadius: 8, border: 0, background: 'var(--grad)', color: '#fff', fontSize: 11, fontWeight: 600, cursor: 'pointer' }}>Kopyala</button>
              </div>
            </div>

            <div>
              <Label>Açıklama (zorunlu)</Label>
              <div style={{ position: 'relative' }}>
                <input className="is-input" readOnly value={`IS-2026-${l.id.toUpperCase()}-9183`} style={{ fontFamily: 'var(--font-mono)' }}/>
                <button style={{ position: 'absolute', right: 6, top: 6, padding: '6px 10px', borderRadius: 8, border: 0, background: 'var(--chip)', color: 'var(--ink)', fontSize: 11, fontWeight: 600, cursor: 'pointer' }}>Kopyala</button>
              </div>
            </div>

            <div style={{ padding: 14, borderRadius: 12, background: 'color-mix(in oklab, var(--warn) 12%, var(--card))', border: '1px solid color-mix(in oklab, var(--warn) 40%, transparent)', fontSize: 13, color: 'var(--ink-2)', display: 'flex', gap: 10 }}>
              <Icon name="bolt" size={16} color="var(--warn)"/> {L.pay_iban_note}
            </div>
          </div>
        )}
      </div>

      {/* RIGHT — order summary */}
      <aside className="is-card" style={{ padding: 22, position: 'sticky', top: 88, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div className="is-kicker">{L.pay_order_summary}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--line-2)' }}>
          <div style={{ width: 56 }}>
            <PostGrid handle={l.handle} postsStyle={l.postsStyle} cols={2} rows={2} gap={2} radius={6}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 15 }}>{l.handle}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', textTransform: 'uppercase' }}>{L[`niche_${l.niche}`]} · {fmtNum(l.followers)} {L.card_followers}</div>
          </div>
        </div>
        <SumRow label={L.pay_subtotal} value={fmtPrice(subtotal, lang)}/>
        <FeeBreakdownRow lang={lang} buyerFee={buyerFee}/>
        <div style={{ height: 1, background: 'var(--line-2)' }}/>
        <SumRow label={L.pay_total} value={fmtPrice(total, lang)} big/>
        <SellerNetInfo lang={lang} sellerNet={sellerNet} sellerFee={sellerFee}/>
        <button className="is-btn is-btn-primary" style={{ justifyContent: 'center', padding: '14px', fontSize: 15, marginTop: 4 }}>
          <Icon name="lock" size={14}/> {method === 'card' ? L.pay_cta_card : L.pay_cta_iban}
        </button>
        <div style={{ paddingTop: 10, borderTop: '1px dashed var(--line)', marginTop: 4 }}>
          <TrustBar L={L} compact/>
        </div>
      </aside>
    </div>
  );
}

function MethodCard({ active, onClick, icon, title, sub }) {
  return (
    <button onClick={onClick} style={{
      textAlign: 'left', cursor: 'pointer', border: 0, padding: 16, borderRadius: 14,
      background: active ? 'var(--grad)' : 'var(--card)',
      color: active ? '#fff' : 'var(--ink)',
      boxShadow: active ? '0 8px 24px -8px oklch(0.66 0.25 350 / 0.4)' : '0 0 0 1px var(--line-2)',
      display: 'flex', alignItems: 'center', gap: 12,
      fontFamily: 'var(--font-body)',
    }}>
      <span style={{ width: 40, height: 40, borderRadius: 10, background: active ? 'rgba(255,255,255,.25)' : 'var(--chip)', display: 'grid', placeItems: 'center' }}>
        <Icon name={icon} size={18} color={active ? '#fff' : 'var(--accent)'}/>
      </span>
      <span>
        <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 15 }}>{title}</span>
        <span style={{ display: 'block', fontSize: 11, opacity: active ? 0.9 : 0.65, fontFamily: 'var(--font-mono)', marginTop: 2 }}>{sub}</span>
      </span>
    </button>
  );
}
function Label({ children }) {
  return <div className="is-kicker" style={{ marginBottom: 6 }}>{children}</div>;
}
function SumRow({ label, value, big }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
      <span style={{ color: big ? 'var(--ink)' : 'var(--ink-2)', fontSize: big ? 14 : 13 }}>{label}</span>
      <span style={{ fontFamily: 'var(--font-display)', fontWeight: big ? 800 : 600, fontSize: big ? 24 : 14, letterSpacing: '-0.02em' }} className={big ? 'is-grad-text' : ''}>{value}</span>
    </div>
  );
}

// Detaylı komisyon kırılımı — alıcı ödeyecek
function FeeBreakdownRow({ lang, buyerFee }) {
  const [open, setOpen] = useState(false);
  return (
    <div style={{ background: 'var(--bg-2)', borderRadius: 10, padding: '10px 12px', border: '1px solid var(--line-2)' }}>
      <button onClick={() => setOpen(o => !o)}
              style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                width: '100%', background: 'transparent', border: 0, cursor: 'pointer',
                padding: 0, color: 'inherit',
              }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--ink-2)' }}>
          {lang === 'tr' ? 'Hizmet bedeli' : 'Service fee'}
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--accent)', background: 'color-mix(in oklab, var(--accent) 12%, transparent)', padding: '2px 6px', borderRadius: 4 }}>%5</span>
          <Icon name={open ? 'chevron-up' : 'chevron-down'} size={12}/>
        </span>
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14 }}>{fmtPrice(buyerFee, lang)}</span>
      </button>
      {open && (
        <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px dashed var(--line-2)', display: 'flex', flexDirection: 'column', gap: 6, fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="shield" size={11} color="var(--success)"/>
            {lang === 'tr' ? 'Escrow / emanet hesap' : 'Escrow holding'}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="check" size={11} color="var(--success)"/>
            {lang === 'tr' ? 'KDV dahil işlem ücreti' : 'Transaction fee (incl. VAT)'}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="lock" size={11} color="var(--success)"/>
            {lang === 'tr' ? '7 gün koşulsuz iade garantisi' : '7-day money-back guarantee'}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="users" size={11} color="var(--success)"/>
            {lang === 'tr' ? '7/24 destek + uyuşmazlık arabuluculuğu' : '24/7 support + dispute mediation'}
          </div>
        </div>
      )}
    </div>
  );
}

// Satıcı net bilgisi — info only (alıcı görür ki şeffaflık olsun)
function SellerNetInfo({ lang, sellerNet, sellerFee }) {
  return (
    <div style={{
      marginTop: 4, padding: '10px 12px',
      background: 'color-mix(in oklab, var(--success) 5%, transparent)',
      border: '1px dashed color-mix(in oklab, var(--success) 30%, transparent)',
      borderRadius: 10, fontSize: 12, color: 'var(--ink-2)',
      display: 'flex', alignItems: 'flex-start', gap: 8,
    }}>
      <Icon name="info" size={13} color="var(--success)"/>
      <div style={{ lineHeight: 1.5 }}>
        <strong style={{ color: 'var(--ink)' }}>
          {lang === 'tr' ? 'Satıcıya geçecek tutar: ' : 'Seller will receive: '}
        </strong>
        <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{fmtPrice(sellerNet, lang)}</span>
        <div style={{ marginTop: 2, color: 'var(--ink-3)', fontSize: 11 }}>
          {lang === 'tr'
            ? `İlan tutarından %5 satıcı komisyonu (${fmtPrice(sellerFee, lang)}) düşülür. Devir tamamlanınca ödeme serbest kalır.`
            : `Listing price minus 5% seller commission (${fmtPrice(sellerFee, lang)}). Released after transfer completes.`}
        </div>
      </div>
    </div>
  );
}

function CheckoutScreen({ L, lang, setLang, theme, listing, onBack, onAuth }) {
  const l = listing || LISTINGS[0];
  return (
    <ScreenFrame theme={theme} width="100%" height="100%">
      <div data-screen-label="09 Checkout (Desktop)" style={{ minHeight: '100%' }}>
        <TopNav L={L} lang={lang} setLang={setLang} active="home" onAuth={onAuth}/>
        <div style={{ maxWidth: 1200, margin: '0 auto', padding: '28px 32px' }}>
          <a onClick={onBack} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--ink-3)', fontSize: 13, cursor: 'pointer', marginBottom: 14 }}>
            <Icon name="chevron-left" size={14}/> {L.nav_explore}
          </a>
          <h1 className="is-h1" style={{ fontSize: 38, margin: '0 0 6px' }}>{L.pay_title}</h1>
          <p style={{ color: 'var(--ink-2)', fontSize: 15, marginBottom: 26 }}>{L.pay_sub}</p>
          <CheckoutCard L={L} lang={lang} listing={l}/>
        </div>
      </div>
    </ScreenFrame>
  );
}

function CheckoutMobile({ L, lang, theme, listing, onBack }) {
  const l = listing || LISTINGS[0];
  const subtotal = l.price;
  const buyerFee = Math.round(subtotal * 0.05);
  const total = subtotal + buyerFee;
  const sellerFee = Math.round(subtotal * 0.05);
  const sellerNet = subtotal - sellerFee;
  const [method, setMethod] = _pS('card');

  return (
    <MobileChrome>
      <div data-screen-label="10 Checkout (Mobile)" style={{ height: '100%', overflow: 'auto', paddingBottom: 120 }}>
        <div style={{ padding: '8px 16px 8px', display: 'flex', alignItems: 'center', gap: 10 }}>
          <button onClick={onBack} style={{ width: 36, height: 36, borderRadius: '50%', border: 0, background: 'var(--chip)', cursor: 'pointer', display: 'grid', placeItems: 'center' }}>
            <Icon name="chevron-left" size={16}/>
          </button>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20 }}>{L.pay_title}</div>
        </div>

        {/* Order summary strip */}
        <div className="is-card" style={{ margin: '6px 16px 14px', padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 50 }}>
            <PostGrid handle={l.handle} postsStyle={l.postsStyle} cols={2} rows={2} gap={2} radius={6}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14 }}>{l.handle}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>{fmtNum(l.followers)} {L.card_followers}</div>
          </div>
          <div className="is-grad-text" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 18, letterSpacing: '-0.02em' }}>{fmtPrice(total, lang)}</div>
        </div>

        {/* Method picker */}
        <div style={{ padding: '0 16px 14px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <MethodCard active={method === 'card'} onClick={() => setMethod('card')} icon="tag" title={L.pay_method_card} sub="Visa · MC · Troy"/>
          <MethodCard active={method === 'iban'} onClick={() => setMethod('iban')} icon="shield" title={L.pay_method_iban} sub="Anlık · masrafsız"/>
        </div>

        {/* Form */}
        <div style={{ padding: '0 16px' }}>
          {method === 'card' ? (
            <div className="is-card" style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div style={{
                padding: 16, borderRadius: 14, background: 'var(--grad)', color: '#fff',
                boxShadow: '0 10px 28px -10px oklch(0.66 0.25 350 / 0.5)',
              }}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.12em', textTransform: 'uppercase', opacity: 0.85 }}>instasatis · secure</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 17, letterSpacing: '.14em', marginTop: 20 }}>4242 4242 4242 4242</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, fontSize: 11, fontFamily: 'var(--font-mono)' }}>
                  <span>SERHAT AKIN</span><span>09/28</span>
                </div>
              </div>
              <div>
                <Label>{L.pay_card_number}</Label>
                <input className="is-input" defaultValue="4242 4242 4242 4242"/>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                <div>
                  <Label>{L.pay_card_exp}</Label>
                  <input className="is-input" defaultValue="09/28"/>
                </div>
                <div>
                  <Label>{L.pay_card_cvv}</Label>
                  <input className="is-input" defaultValue="•••"/>
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-3)', fontSize: 11 }}>
                <Icon name="lock" size={11}/> {L.pay_3d}
              </div>
            </div>
          ) : (
            <div className="is-card" style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div>
                <Label>{L.pay_iban_owner}</Label>
                <div style={{ fontWeight: 600 }}>OKxProject Yazılım A.Ş.</div>
              </div>
              <div>
                <Label>{L.pay_iban_num}</Label>
                <div style={{ position: 'relative' }}>
                  <input className="is-input" readOnly value="TR33 0006 2000 1234 0006 6677 88" style={{ fontFamily: 'var(--font-mono)', letterSpacing: '.04em', fontSize: 12 }}/>
                  <button style={{ position: 'absolute', right: 5, top: 5, padding: '5px 9px', borderRadius: 7, border: 0, background: 'var(--grad)', color: '#fff', fontSize: 10, fontWeight: 600 }}>Kopyala</button>
                </div>
              </div>
              <div style={{ padding: 12, borderRadius: 10, background: 'color-mix(in oklab, var(--warn) 12%, var(--card))', border: '1px solid color-mix(in oklab, var(--warn) 40%, transparent)', fontSize: 12, color: 'var(--ink-2)' }}>
                {L.pay_iban_note}
              </div>
            </div>
          )}
        </div>

        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0, padding: '14px 16px 28px',
          background: 'color-mix(in oklab, var(--card) 92%, transparent)',
          backdropFilter: 'blur(18px)', borderTop: '1px solid var(--line-2)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', letterSpacing: '.1em', textTransform: 'uppercase' }}>{L.pay_total}</div>
            <div className="is-grad-text" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 24, letterSpacing: '-0.02em', lineHeight: 1 }}>{fmtPrice(total, lang)}</div>
          </div>
          <button className="is-btn is-btn-primary" style={{ padding: '14px 18px', fontSize: 13 }}>
            <Icon name="lock" size={13}/> {method === 'card' ? L.pay_cta_card : L.pay_cta_iban}
          </button>
        </div>
      </div>
    </MobileChrome>
  );
}

Object.assign(window, { CheckoutScreen, CheckoutMobile });
