// Payment / checkout page — DESKTOP layout (>1024px scaled canvas).
// Self-contained: owns its own Field / Button / OrderSummary / Success
// so direct-edits here do NOT propagate to tablet or mobile.

const DESK_PAY_BG = '#fffbf9';

// Sticky order-summary wrapper for the DESKTOP layout.
//
// The desktop page lives inside #scale-root, which is `position:absolute` and
// `transform: scale(...)`. That transform defeats native `position: sticky`
// (the sticky box scrolls away with the canvas), so we emulate sticky in JS:
// on every scroll we translate the card in *design-space* px so it stays
// `top` design-px below the viewport top, clamped to the form column's bounds.
const DeskStickySummary = ({ children, top = 64 }) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const root = document.getElementById('scale-root');
    let raf = null;

    // Layout offset (in design px) of `node` relative to `anc`. Unaffected by
    // any transform we apply, so it stays a stable measurement.
    const offTopTo = (node, anc) => {
      let t = 0,c = node;
      while (c && c !== anc) {t += c.offsetTop;c = c.offsetParent;}
      return t;
    };

    const update = () => {
      raf = null;
      const scale = root ? root.getBoundingClientRect().width / 1920 : 1;
      if (!scale) return;
      const B = offTopTo(el, root); // card's natural top
      const H = el.offsetHeight; // card height
      const parent = el.parentElement; // the 2-col grid
      const gridTop = offTopTo(parent, root);
      const gridBottom = gridTop + parent.offsetHeight;
      const maxDelta = Math.max(0, gridBottom - (B + H));
      const desired = window.scrollY / scale + top;
      const delta = Math.max(0, Math.min(desired - B, maxDelta));
      el.style.transform = 'translateY(' + delta + 'px)';
    };
    const onScroll = () => {if (raf == null) raf = requestAnimationFrame(update);};

    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    window.addEventListener('forcedBpChange', onScroll);
    const ro = new ResizeObserver(onScroll);
    ro.observe(el);
    if (el.parentElement) ro.observe(el.parentElement);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      window.removeEventListener('forcedBpChange', onScroll);
      ro.disconnect();
      if (raf != null) cancelAnimationFrame(raf);
    };
  }, [top]);
  return (
    <div ref={ref} style={{
      willChange: 'transform',
      padding: 32, background: '#fffbf9', borderRadius: 24,
      border: '1px solid #f0e6dc', margin: "32px 0px 0px"
    }}>{children}</div>);

};

const DeskField = ({ 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: "22px" }}>{label}</label>
    <div style={{
    background: DESK_PAY_BG, display: 'flex', alignItems: 'center',
    border: error ? '1px solid #d6553e' : '1px solid #f0e6dc',
    transition: 'border-color 160ms', padding: '0 16px', height: "64px", borderRadius: "8px", fontSize: "22px"
  }}>
      <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: 22,
      color: '#101010', letterSpacing: '-0.01em'
    }} />
    </div>
    {error && <div style={{ fontFamily: 'Inter', fontWeight: 500, fontSize: 13, color: '#d6553e', paddingLeft: 4 }}>{error}</div>}
  </div>;


// Native <select> styled to match DeskField. Used for country picker.
const DeskSelect = ({ 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: "22px" }}>{label}</label>
    <div style={{
    background: DESK_PAY_BG, display: 'flex', alignItems: 'center',
    border: error ? '1px solid #d6553e' : '1px solid #f0e6dc',
    transition: 'border-color 160ms', padding: '0 16px', height: "64px", borderRadius: "8px",
    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: 22,
      color: '#101010', letterSpacing: '-0.01em', appearance: 'none',
      WebkitAppearance: 'none', MozAppearance: 'none', cursor: 'pointer',
      paddingRight: 32
    }}>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
      <svg width="16" height="16" viewBox="0 0 20 20" style={{ position: 'absolute', right: 18, 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>;


// Small card-brand glyph shown inside the combined Card field.
const DeskCardGlyph = ({ brand }) => {
  const bg = brand === 'visa' ? '#1a1f71' :
  brand === 'mastercard' ? '#1a1a1a' :
  brand === 'amex' ? '#2e77bb' :
  brand === 'discover' ? '#ff6000' :
  '#3a3a3a';
  return (
    <div style={{
      width: 36, height: 24, borderRadius: 4, background: bg, flexShrink: 0,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'Inter', fontWeight: 700, fontSize: 9, color: '#fff', letterSpacing: '0.05em',
      position: 'relative'
    }}>
      <div style={{ position: 'absolute', left: 4, top: 4, width: 8, height: 6, background: '#f0c674', borderRadius: 1 }} />
      <span style={{ position: 'absolute', right: 4, bottom: 3 }}>
        {brand === 'visa' ? 'VISA' : brand === 'amex' ? 'AMEX' : brand === 'discover' ? 'DISC' : '•••'}
      </span>
    </div>);

};


// Combined Card field — card number + expiry + CVC in a single bordered row.
// Auto-advances focus: 16 card digits → expiry; 4 expiry digits → CVC.
const DeskCombinedCardField = ({ 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: 22,
    color: '#101010', letterSpacing: '-0.01em'
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <label style={{ fontFamily: 'Inter', fontWeight: 500, color: '#101010', letterSpacing: '-0.02em', fontSize: "22px" }}>
        Card
      </label>
      <div style={{
        background: DESK_PAY_BG, display: 'flex', alignItems: 'center', gap: 16,
        border: error ? '1px solid #d6553e' : '1px solid #f0e6dc',
        transition: 'border-color 160ms', padding: '0 20px', height: 64, borderRadius: 8
      }}>
        <DeskCardGlyph 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 }} />
        <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, width: 100, textAlign: 'right' }} />
        <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, width: 64, textAlign: 'right' }} />
      </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 desktop (32).
const DeskSectionHeading = ({ children }) =>
<div style={{
  fontFamily: 'Inter', fontWeight: 600, fontSize: 32,
  color: '#101010', letterSpacing: '-0.05em', marginBottom: 4
}}>{children}</div>;


const DeskCheckbox = ({ 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', color: '#101010', letterSpacing: '-0.01em', fontSize: "20px" }}>{children}</span>
  </label>;


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


const DeskOrderSummary = ({ product, subtotal, tax, total, taxInfo }) =>
<div style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
    <div style={{ display: 'flex', gap: 24, alignItems: 'center' }}>
      <div style={{
      width: 184, height: 184, flexShrink: 0,
      borderRadius: 20, overflow: 'hidden',
      background: `url(${product.image}) center/cover no-repeat`,
      boxShadow: '-8px 6px 36px rgba(0,0,0,0.08)'
    }} />
      <div style={{
      fontFamily: 'Inter', fontWeight: 500,
      color: '#101010', letterSpacing: '-0.05em', lineHeight: 1.1, fontSize: "24px"
    }}>{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, color: '#101010', letterSpacing: '-0.04em', fontSize: "22px" }}>Subtotal</span>
        <span style={{ fontFamily: 'Inter', fontWeight: 500, color: '#101010', letterSpacing: '-0.04em', fontSize: "22px" }}>${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, color: '#101010', letterSpacing: '-0.04em', fontSize: "22px" }}>Tax</span>
          <span style={{ fontFamily: 'Inter', fontWeight: 500, color: '#101010', letterSpacing: '-0.04em', fontSize: "22px" }}>${tax.toFixed(2)}</span>
        </div>
        <div style={{ fontFamily: 'Inter', color: '#696a6d', letterSpacing: '-0.02em', fontSize: "16px" }}>
          {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, color: '#101010', letterSpacing: '-0.04em', fontSize: "22px" }}>Total</span>
        <span style={{ fontFamily: 'Inter', fontWeight: 700, color: '#101010', letterSpacing: '-0.04em', fontSize: "22px" }}>
          <span style={{ marginRight: 4, fontWeight: 400, fontSize: "20px" }}>CAD</span>${total.toFixed(2)}
        </span>
      </div>
    </div>
  </div>;


const DeskPaymentSuccess = ({ onBack, product, total, email, paymentIntentId }) =>
<div style={{
  display: 'flex', flexDirection: 'column', gap: 32,
  alignItems: 'center', textAlign: 'center', maxWidth: 640, margin: '0 auto'
}}>
    <h2 className="serif" style={{ margin: 0, fontSize: 128, lineHeight: '120px', letterSpacing: '-0.01em', color: '#101010' }}>
      Thank you !
    </h2>
    {product.id === 'newsletter' ?
    <React.Fragment>
    <div style={{ fontFamily: 'Inter', fontSize: 20, 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: 16, 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: 20, 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="desktop" />
    <div style={{ fontFamily: 'Inter', fontSize: 16, 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>;


// ─── DESKTOP page ─────────────────────────────────────────────────────────────
const PaymentPageDesktop = ({ 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 tilt />
        <NavBar brand="Yoga with Tara" />
        <section style={{
          position: 'relative', display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center', flex: 1, padding: '256px 128px 160px'
        }}>
          <DeskPaymentSuccess 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 tilt />
      <NavBar brand="Yoga with Tara" />
      <section style={{
        position: 'relative', display: 'flex', justifyContent: 'center', padding: "256px 264px 96px"

      }}>
        <button onClick={onBack} style={{
          position: 'absolute', left: 128, top: 220,
          display: 'flex', alignItems: 'center',
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontFamily: 'Inter', fontWeight: 500, color: '#101010', padding: 0, gap: "4px", fontSize: "22px"
        }} aria-label="Back to template">
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none" style={{ width: "22px", height: "22px" }}>
            <path d="M13 4l-6 6 6 6" stroke="#101010" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          Back
        </button>

        <div style={{
          width: '100%', display: 'grid', gridTemplateColumns: '1fr 555px', gap: 88,
          alignItems: 'start'
        }}>
          <div style={{ display: 'flex', flexDirection: 'column', margin: "32px 0px 0px", padding: "0px", gap: "64px" }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              <DeskSectionHeading>Contact</DeskSectionHeading>
              <DeskField label="First Name" value={fields.firstName} onChange={set('firstName')} error={errors.firstName} autoComplete="given-name" />
              <DeskField label="Last Name" value={fields.lastName} onChange={set('lastName')} error={errors.lastName} autoComplete="family-name" />
              <DeskField label="Email Address" value={fields.email} onChange={set('email')} error={errors.email} type="email" autoComplete="email" />
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              <DeskSectionHeading>Payment</DeskSectionHeading>
              {typeof window.isStripeConfigured === 'function' && window.isStripeConfigured() ?
              <StripeCardField
                fontSize={22} 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>
                  <DeskCombinedCardField
                  card={fields.card} exp={fields.exp} cvc={fields.cvc}
                  onCardChange={set('card')} onExpChange={set('exp')} onCvcChange={set('cvc')}
                  error={errors.card} />
                  <StripeDemoNote fontSize={16} />
                </React.Fragment>}
              <DeskSelect label="Country" value={fields.country} onChange={set('country')} error={errors.country}
              options={window.COUNTRIES} />
              <DeskField label="Postal/ZIP code" value={fields.zip} onChange={set('zip')} error={errors.zip} autoComplete="postal-code" />
            </div>

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

            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <DeskBuyButton onClick={submit} label={submitting ? 'Processing…' : 'Buy'} />
              <SecurePaymentLine fontSize={18} />
            </div>
          </div>

          <DeskStickySummary>
            <DeskOrderSummary product={product} subtotal={subtotal} tax={tax} total={total} taxInfo={taxInfo} />
          </DeskStickySummary>
        </div>
      </section>
      <Footer tagline="A space where you can be fully you" sub="Check my channel Yoga with Tara" />
    </main>);
};

Object.assign(window, { PaymentPageDesktop });