// Payment / checkout page — SMALL MOBILE layout (≤389px).
// Self-contained — owns its own primitives so edits don't leak to other breakpoints.
// Self-contained: owns its own primitives so edits don't leak to other breakpoints.

const SMOB_PAY_BG = '#fffbf9';

const SMobField = ({ label, value, onChange, placeholder, error, type = 'text', inputMode, autoComplete, maxLength, style }) =>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, ...(style || {}) }}>
    <label style={{ fontFamily: 'Inter', fontWeight: 500, color: '#101010', letterSpacing: '-0.02em', fontSize: 16 }}>{label}</label>
    <div style={{
    background: SMOB_PAY_BG, display: 'flex', alignItems: 'center',
    border: error ? '1px solid #d6553e' : '1px solid #f0e6dc',
    transition: 'border-color 160ms', height: 54, borderRadius: 8, padding: "0px 8px"
  }}>
      <input value={value} onChange={(e) => onChange(e.target.value)}
    type={type} inputMode={inputMode} autoComplete={autoComplete} maxLength={maxLength}
    placeholder={placeholder} aria-label={label}
    style={{
      flex: 1, minWidth: 0, height: '100%', border: 'none', background: 'transparent',
      outline: 'none', fontFamily: 'Inter', fontWeight: 500, fontSize: 16,
      color: '#101010', letterSpacing: '-0.01em'
    }} />
    </div>
    {error && <div style={{ fontFamily: 'Inter', fontWeight: 500, fontSize: 13, color: '#d6553e', paddingLeft: 4 }}>{error}</div>}
  </div>;


const SMobSelect = ({ label, value, onChange, options, error, style }) =>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, ...(style || {}) }}>
    <label style={{ fontFamily: 'Inter', fontWeight: 500, color: '#101010', letterSpacing: '-0.02em', fontSize: 16 }}>{label}</label>
    <div style={{
    background: SMOB_PAY_BG, display: 'flex', alignItems: 'center',
    border: error ? '1px solid #d6553e' : '1px solid #f0e6dc',
    transition: 'border-color 160ms', padding: '0 16px', height: 54, borderRadius: 8, position: 'relative'
  }}>
      <select value={value} onChange={(e) => onChange(e.target.value)} aria-label={label}
    style={{
      flex: 1, minWidth: 0, height: '100%', border: 'none', background: 'transparent',
      outline: 'none', fontFamily: 'Inter', fontWeight: 500, fontSize: 16,
      color: '#101010', letterSpacing: '-0.01em', appearance: 'none',
      WebkitAppearance: 'none', MozAppearance: 'none', cursor: 'pointer', paddingRight: 28
    }}>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
      <svg width="14" height="14" viewBox="0 0 20 20" style={{ position: 'absolute', right: 14, pointerEvents: 'none' }}>
        <path d="M5 8l5 5 5-5" stroke="#101010" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none" />
      </svg>
    </div>
    {error && <div style={{ fontFamily: 'Inter', fontWeight: 500, fontSize: 13, color: '#d6553e', paddingLeft: 4 }}>{error}</div>}
  </div>;


const SMobCardGlyph = ({ brand }) => {
  const bg = brand === 'visa' ? '#1a1f71' :
  brand === 'mastercard' ? '#1a1a1a' :
  brand === 'amex' ? '#2e77bb' :
  brand === 'discover' ? '#ff6000' :
  '#3a3a3a';
  return (
    <div style={{
      width: 26, height: 17, borderRadius: 3, background: bg, flexShrink: 0,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'Inter', fontWeight: 700, fontSize: 6, color: '#fff', letterSpacing: '0.05em',
      position: 'relative'
    }}>
      <div style={{ position: 'absolute', left: 2, top: 2, width: 5, height: 4, background: '#f0c674', borderRadius: 1 }} />
      <span style={{ position: 'absolute', right: 2, bottom: 2 }}>
        {brand === 'visa' ? 'VISA' : brand === 'amex' ? 'AMEX' : brand === 'discover' ? 'D' : '•••'}
      </span>
    </div>);

};


const SMobCombinedCardField = ({ card, exp, cvc, onCardChange, onExpChange, onCvcChange, error }) => {
  const expRef = React.useRef(null);
  const cvcRef = React.useRef(null);
  const brand = detectCardBrand(card);

  const handleCard = (v) => {
    const formatted = formatCardNumber(v);
    onCardChange(formatted);
    const digits = formatted.replace(/\D/g, '');
    if (digits.length >= 16 && expRef.current) expRef.current.focus();
  };
  const handleExp = (v) => {
    const formatted = formatExp(v);
    onExpChange(formatted);
    if (formatted.replace(/\D/g, '').length >= 4 && cvcRef.current) cvcRef.current.focus();
  };
  const handleCvc = (v) => onCvcChange((v || '').replace(/\D/g, '').slice(0, 4));

  const inputBase = {
    height: '100%', border: 'none', background: 'transparent', outline: 'none',
    fontFamily: 'Inter', fontWeight: 500, fontSize: 16,
    color: '#101010', letterSpacing: '-0.01em'
  };
  const boxBase = {
    background: SMOB_PAY_BG, display: 'flex', alignItems: 'center', gap: 6,
    border: error ? '1px solid #d6553e' : '1px solid #f0e6dc',
    transition: 'border-color 160ms', padding: '0 10px', height: 54, borderRadius: 8
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <label style={{ fontFamily: 'Inter', fontWeight: 500, color: '#101010', letterSpacing: '-0.02em', fontSize: 16 }}>
        Card
      </label>
      <div style={boxBase}>
        <SMobCardGlyph brand={brand} />
        <input value={card} onChange={(e) => handleCard(e.target.value)}
        inputMode="numeric" autoComplete="cc-number"
        placeholder="1234 1234 1234 1234" aria-label="Card number" maxLength={23}
        style={{ ...inputBase, flex: 1, minWidth: 0 }} />
      </div>
      <div style={{ display: 'flex', gap: 8, minWidth: 0 }}>
        <div style={{ ...boxBase, flex: 1, minWidth: 0 }}>
          <input ref={expRef} value={exp} onChange={(e) => handleExp(e.target.value)}
          inputMode="numeric" autoComplete="cc-exp"
          placeholder="MM / YY" aria-label="Expiry date" maxLength={7}
          style={{ ...inputBase, flex: 1, minWidth: 0, width: 0 }} />
        </div>
        <div style={{ ...boxBase, flex: 1, minWidth: 0 }}>
          <input ref={cvcRef} value={cvc} onChange={(e) => handleCvc(e.target.value)}
          inputMode="numeric" autoComplete="cc-csc" maxLength={4}
          placeholder="CVC" aria-label="CVC"
          style={{ ...inputBase, flex: 1, minWidth: 0, width: 0 }} />
        </div>
      </div>
      {error && <div style={{ fontFamily: 'Inter', fontWeight: 500, fontSize: 13, color: '#d6553e', paddingLeft: 4 }}>{error}</div>}
    </div>);

};


// Matches the template-Free H2 product-title scale on smallMobile (18).
const SMobSectionHeading = ({ children }) =>
<div style={{
  fontFamily: 'Inter', fontWeight: 600, fontSize: 18,
  color: '#101010', letterSpacing: '-0.04em', marginBottom: 4
}}>{children}</div>;


const SMobCheckbox = ({ checked, onChange, children }) =>
<label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', userSelect: 'none' }}>
    <span style={{
    width: 18, height: 18, borderRadius: 4,
    border: '1.5px solid #91837a',
    background: checked ? '#101010' : '#fff',
    borderColor: checked ? '#101010' : '#91837a',
    display: 'grid', placeItems: 'center', flexShrink: 0,
    transition: 'all 140ms ease'
  }}>
      {checked &&
    <svg width="11" height="11" viewBox="0 0 14 14" fill="none">
          <path d="M3 7.5 6 10.5 11.5 4" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
    }
    </span>
    <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)}
  style={{ position: 'absolute', opacity: 0, pointerEvents: 'none', width: 0, height: 0 }} />
    <span style={{ fontFamily: 'Inter', fontSize: 15, color: '#101010', letterSpacing: '-0.01em' }}>{children}</span>
  </label>;


const SMobBuyButton = ({ onClick, label = 'Buy' }) =>
<button onClick={onClick} style={{
  width: '100%', height: 60, borderRadius: 52,
  background: '#101010', color: '#fff', border: 'none', cursor: 'pointer',
  fontFamily: 'Inter', fontWeight: 700, fontSize: 18, letterSpacing: '-0.01em',
  boxShadow: '0 6px 19.9px rgba(0,0,0,0.2)',
  display: 'flex', alignItems: 'center', justifyContent: 'center'
}}>{label}</button>;


const SMobOrderSummary = ({ product, subtotal, tax, total, taxInfo }) =>
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
      <div style={{
      width: 96, height: 96, flexShrink: 0,
      overflow: 'hidden', borderRadius: 8,
      background: `url(${product.image}) center/cover no-repeat`,
      boxShadow: '-8px 6px 36px rgba(0,0,0,0.08)'
    }} />
      <div style={{
      fontFamily: 'Inter', fontWeight: 500, fontSize: 18,
      color: '#101010', letterSpacing: '-0.04em', lineHeight: 1.1
    }}>{product.title}</div>
    </div>

    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span style={{ fontFamily: 'Inter', fontWeight: 500, fontSize: 16, color: '#101010', letterSpacing: '-0.04em' }}>Subtotal</span>
        <span style={{ fontFamily: 'Inter', fontWeight: 500, fontSize: 16, color: '#101010', letterSpacing: '-0.04em' }}>${subtotal.toFixed(0)}</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span style={{ fontFamily: 'Inter', fontWeight: 500, fontSize: 16, color: '#101010', letterSpacing: '-0.04em' }}>Tax</span>
          <span style={{ fontFamily: 'Inter', fontWeight: 500, fontSize: 16, color: '#101010', letterSpacing: '-0.04em' }}>${tax.toFixed(2)}</span>
        </div>
        <div style={{ fontFamily: 'Inter', fontSize: 13, color: '#696a6d', letterSpacing: '-0.02em' }}>
          {taxInfo ? taxInfo.label : 'HST may apply depending on your location.'}
        </div>
      </div>
      <div style={{ height: 1, background: '#ece4dd', marginTop: 8, marginBottom: 4 }} />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span style={{ fontFamily: 'Inter', fontWeight: 700, fontSize: 16, color: '#101010', letterSpacing: '-0.04em' }}>Total</span>
        <span style={{ fontFamily: 'Inter', fontWeight: 700, fontSize: 16, color: '#101010', letterSpacing: '-0.04em' }}>
          <span style={{ fontSize: 12, marginRight: 4, fontWeight: 400 }}>CAD</span>${total.toFixed(2)}
        </span>
      </div>
    </div>
  </div>;


const SMobPaymentSuccess = ({ onBack, product, total, email, paymentIntentId }) =>
<div style={{
  display: 'flex', flexDirection: 'column', gap: 20,
  alignItems: 'center', textAlign: 'center', maxWidth: 640, margin: '0 auto'
}}>
    <h2 className="serif" style={{ margin: 0, fontSize: 40, lineHeight: '44px', letterSpacing: '-0.01em', color: '#101010' }}>
      Thank you !
    </h2>
    {product.id === 'newsletter' ?
    <React.Fragment>
    <div style={{ fontFamily: 'Inter', fontSize: 15, color: '#696a6d', lineHeight: 1.55, letterSpacing: '-0.01em', textAlign: 'center', width: '100%' }}>
      We're going to do our best to send you high-quality insight and content on the 1st of every month. Thank you so much for subscribing and choosing to start this journey with us.
    </div>
    <div style={{ fontFamily: 'Inter', fontSize: 13, color: '#91837a', letterSpacing: '-0.01em' }}>
      For any inquiries, please contact us at <a href="mailto:yogawithtara@gmail.com" style={{ color: '#101010', fontWeight: 600, textDecoration: 'underline' }}>yogawithtara@gmail.com</a>
    </div>
    </React.Fragment> :
    <React.Fragment>
    <div style={{ fontFamily: 'Inter', fontSize: 15, color: '#696a6d', lineHeight: 1.55, letterSpacing: '-0.01em', textAlign: 'center', width: '100%' }}>
      Your payment of <strong style={{ color: '#101010' }}>CAD ${total.toFixed(2)}</strong> went through - your <em>{product.title}</em> is ready right here. We've also sent the link to your email so you can download it anytime within 24 hours.
    </div>
    <DownloadDelivery product={product} email={email} paymentIntentId={paymentIntentId} variant="smob" />
    <div style={{ fontFamily: 'Inter', fontSize: 13, color: '#91837a', letterSpacing: '-0.01em' }}>
      Need any help? Email me at <a href="mailto:yogawithtara@gmail.com" style={{ color: '#101010', fontWeight: 600, textDecoration: 'underline' }}>yogawithtara@gmail.com</a>
    </div>
    </React.Fragment>
    }
  </div>;


// ─── MOBILE page ──────────────────────────────────────────────────────────────
const PaymentPageSmallMobile = ({ product, subtotal, tax, total, taxInfo, fields, errors, set, submit, done, onBack, stripeConfirmRef, submitting, email, paymentIntentId }) => {
  if (done) {
    return (
      <main style={{ position: 'relative', background: '#fff', minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
        <HeroBackdrop fraction={1 / 3} />
        <NavBar brand="Yoga with Tara" />
        <section style={{
          position: 'relative', display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center', flex: 1, padding: '128px 16px 64px'
        }}>
          <SMobPaymentSuccess onBack={onBack} product={product} total={total} email={email} paymentIntentId={paymentIntentId} />
        </section>
        <Footer tagline="A space where you can be fully you" sub="Check my channel Yoga with Tara" />
      </main>);
  }

  return (
    <main style={{ position: 'relative', background: '#fff' }}>
      <HeroBackdrop fraction={1 / 3} />
      <NavBar brand="Yoga with Tara" />
      <section style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 28, margin: "0px", padding: "128px 16px 48px" }}>
        <button onClick={onBack} style={{
          display: 'flex', alignItems: 'center', alignSelf: 'flex-start',
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontFamily: 'Inter', fontWeight: 500, color: '#101010', padding: 0, gap: 2, fontSize: 16
        }}>
          <svg width="16" height="16" viewBox="0 0 20 20" fill="none">
            <path d="M13 4l-6 6 6 6" stroke="#101010" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          Back
        </button>

        <div style={{ padding: 16, background: '#fffbf9', borderRadius: 16, border: '1px solid #f0e6dc' }}>
          <SMobOrderSummary product={product} subtotal={subtotal} tax={tax} total={total} taxInfo={taxInfo} />
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, margin: '16px 0 0' }}>
          <SMobSectionHeading>Contact</SMobSectionHeading>
          <SMobField label="First Name" value={fields.firstName} onChange={set('firstName')} error={errors.firstName} />
          <SMobField label="Last Name" value={fields.lastName} onChange={set('lastName')} error={errors.lastName} />
          <SMobField label="Email Address" value={fields.email} onChange={set('email')} error={errors.email} type="email" />
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <SMobSectionHeading>Payment</SMobSectionHeading>
          {typeof window.isStripeConfigured === 'function' && window.isStripeConfigured() ?
          <StripeCardField
            fontSize={14} total={total} error={errors.card}
            billing={{ name: `${fields.firstName} ${fields.lastName}`, email: fields.email, country: fields.country, zip: fields.zip }}
                productId={product.id}
            registerConfirm={(fn) => {stripeConfirmRef.current = fn;}} /> :
          <React.Fragment>
              <SMobCombinedCardField
              card={fields.card} exp={fields.exp} cvc={fields.cvc}
              onCardChange={set('card')} onExpChange={set('exp')} onCvcChange={set('cvc')}
              error={errors.card} />
              <StripeDemoNote fontSize={12} />
            </React.Fragment>}
          <SMobSelect label="Country" value={fields.country} onChange={set('country')} error={errors.country}
          options={window.COUNTRIES} />
          <SMobField label="Postal/ZIP code" value={fields.zip} onChange={set('zip')} error={errors.zip} />
        </div>

        <SMobCheckbox checked={fields.optIn} onChange={(v) => set('optIn')(v)}>
          Get updates about new products
        </SMobCheckbox>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <SMobBuyButton onClick={submit} label={submitting ? 'Processing…' : 'Buy'} />
          <SecurePaymentLine fontSize={13} />
        </div>
      </section>
      <Footer tagline="A space where you can be fully you" sub="Check my channel Yoga with Tara" />
    </main>);
};

Object.assign(window, { PaymentPageSmallMobile });