// Paywall — vial selection. Checkout applies the current product price:
// $299 membership base plus any compound difference above $299.
// AI-reviewed framing, never "clinician-led".

const PLAN_OPTIONS = [
  { id: 'solo', slots: 1, price: 299, name: '1 peptide plan', desc: 'One monthly vial.' },
  { id: 'paired', slots: 2, price: 578, name: '2 peptide plan', desc: 'Two monthly vials. Save $20.', recommended: true },
  { id: 'full', slots: 3, price: 877, name: '3 peptide plan', desc: 'Three monthly vials. Save $20.' },
];

const SUPPORT_OPTIONS = [
  { id: 'none', tier: 'none', price: 0, name: 'Not now', desc: 'Peptide membership only.' },
  { id: 'monthly-care', tier: 'group_monthly', price: 129, name: 'Provider care rooms', desc: 'One provider-led care room monthly.' },
  { id: 'twice-care', tier: 'group_twice_monthly', price: 199, name: 'Provider care rooms plus', desc: 'Two provider-led care rooms monthly.', recommended: true },
  { id: 'direct-support', tier: 'private_access', price: 299, name: 'Provider care rooms + 1:1', desc: 'Care rooms plus direct 1:1 access.' },
];

const Paywall = ({ track, contact, onPay, onBack, verified }) => {
  const trackInfo = CATEGORIES.find(t => t.id === track) || CATEGORIES[0];
  const planHint = React.useMemo(() => ({
    tier: window.sessionStorage?.getItem('axo_peptide_plan_tier') || 'paired',
    slots: Number(window.sessionStorage?.getItem('axo_peptide_plan_slots') || 0),
    price: Number(window.sessionStorage?.getItem('axo_peptide_plan_price') || 0),
    label: window.sessionStorage?.getItem('axo_peptide_plan_label') || '',
    anchorName: window.sessionStorage?.getItem('axo_peptide_anchor_name') || '',
  }), []);

  const [selectedPlan, setSelectedPlan] = React.useState(() => {
    const hinted = PLAN_OPTIONS.find(p => p.id === planHint.tier || p.slots === planHint.slots);
    return hinted || PLAN_OPTIONS[1];
  });
  const [selectedSupport, setSelectedSupport] = React.useState(SUPPORT_OPTIONS[0]);
  const [checkoutContact, setCheckoutContact] = React.useState(() => ({
    legalName: contact?.legalName || '',
    email: contact?.email || '',
    phone: contact?.phone || '',
    address1: contact?.address1 || '',
    address2: contact?.address2 || '',
    city: contact?.city || '',
    state: contact?.state || '',
    zip: contact?.zip || '',
  }));
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');
  const [paymentProvider, setPaymentProvider] = React.useState('stripe');

  React.useEffect(() => {
    let alive = true;
    fetch('/api/checkout-config')
      .then((res) => res.ok ? res.json() : null)
      .then((data) => {
        if (!alive || !data) return;
        if (data.provider === 'stripe' || data.provider === 'whop') {
          setPaymentProvider(data.provider);
        }
      })
      .catch(() => {});
    return () => { alive = false; };
  }, []);

  const total = selectedPlan.price + selectedSupport.price;
  const anchorName = planHint.anchorName || `Primary peptide · ${trackInfo.name.toLowerCase()}`;
  const plannedVials = Array.from({ length: selectedPlan.slots }, (_, index) => ({
    id: index === 0 ? 'primary' : `slot-${index + 1}`,
    name: index === 0 ? anchorName : `Peptide ${index + 1}`,
    planId: selectedPlan.id,
    planSlots: selectedPlan.slots,
    planPrice: selectedPlan.price,
  }));

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    const email = checkoutContact.email.trim();
    const legalName = checkoutContact.legalName.trim();
    const phone = checkoutContact.phone.trim();
    const shipping = {
      address1: checkoutContact.address1.trim(),
      address2: checkoutContact.address2.trim(),
      city: checkoutContact.city.trim(),
      state: checkoutContact.state.trim().toUpperCase(),
      zip: checkoutContact.zip.trim(),
    };
    if (!legalName) {
      setError('Full name is required before checkout.');
      return;
    }
    if (!email || !email.includes('@')) {
      setError('Email is required before checkout.');
      return;
    }
    if (!phone || !shipping.address1 || !shipping.city || !shipping.state || !shipping.zip) {
      setError('Shipping address and phone are required before checkout.');
      return;
    }
    setSubmitting(true);

    const checkoutState = {
      vials: plannedVials,
      plan: selectedPlan,
      support: selectedSupport,
      total,
      track,
      contact: { ...contact, legalName, email, phone, ...shipping },
      shipping,
      savedAt: new Date().toISOString(),
    };
    window.sessionStorage?.setItem('axo_site_checkout_state', JSON.stringify(checkoutState));

    try {
      const siteRoot = window.location.origin;
      const items = [{
        name: selectedPlan.name,
        supply: `${selectedPlan.slots} monthly vial${selectedPlan.slots === 1 ? '' : 's'}`,
        price: selectedPlan.price * 100,
        quantity: 1,
        billingKind: 'peptide_plan',
        metadata: {
          planId: selectedPlan.id,
          slots: selectedPlan.slots,
          track,
          anchorName,
        },
      }];

      if (selectedSupport.id !== 'none') {
        items.push({
          name: selectedSupport.name,
          supply: selectedSupport.desc,
          price: selectedSupport.price * 100,
          quantity: 1,
          billingKind: 'provider_support',
          metadata: {
            supportId: selectedSupport.id,
            careTier: selectedSupport.tier,
          },
        });
      }

      const res = await fetch('/api/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          items,
          customerEmail: email,
          customerName: legalName,
          careTier: selectedSupport.tier,
          peptidePlan: selectedPlan,
          providerSupport: selectedSupport,
          paymentProvider,
          visitorId: window.localStorage?.getItem('axo_site_visitor_id') || null,
          customerRef: contact?.userId || null,
          shipping: {
            name: legalName,
            phone,
            ...shipping,
          },
          successUrl: `${siteRoot}/dashboard?checkout_session_id={CHECKOUT_SESSION_ID}`,
          cancelUrl: `${siteRoot}/checkout`,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.url) throw new Error(data.error || 'Checkout failed');

      onPay?.({
        vials: plannedVials,
        plan: selectedPlan,
        support: selectedSupport,
        contact: checkoutState.contact,
        checkoutStatus: 'started',
      });
      window.top.location.href = data.url;
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Checkout failed');
      setSubmitting(false);
    }
  };

  const fname = (checkoutContact.legalName || contact?.legalName || '').split(' ')[0];

  return (
    <div className="shell" style={{ background: 'var(--bg)' }}>
      <nav className="nav">
        <div className="nav-inner">
          <Logo size={20} asLink />
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', color: 'var(--ink-mute)', textTransform: 'uppercase' }}>
            {verified ? 'IDENTITY VERIFIED · ASSESSMENT REVIEWED · READY TO ACTIVATE' : 'ASSESSMENT REVIEWED · YOU CAN ACTIVATE'}
          </div>
          <button className="btn btn-soft btn-sm" onClick={onBack}>← Back</button>
        </div>
      </nav>

      <div className="section pay-section">
        {verified && (
          <div className="pay-status-pill">
            <span>✓</span>
            IDENTITY VERIFIED
          </div>
        )}
        <div className="pay-intro">
          <h2 className="serif">
            {fname ? `${fname}, choose ` : 'Choose '}<em>your monthly plan.</em>
          </h2>
        </div>

        <div className="paywall-grid">
          <form className="pay-form" onSubmit={submit} noValidate>
            <div>
              <div className="section-eyebrow">— YOUR INFORMATION</div>
              <div className="pay-contact-grid">
                <label className="pay-field">
                  <span>Full name</span>
                  <input
                    type="text"
                    required
                    value={checkoutContact.legalName}
                    onChange={(e) => setCheckoutContact(prev => ({ ...prev, legalName: e.target.value }))}
                    placeholder="First and last name"
                    autoComplete="name"
                  />
                </label>
                <label className="pay-field">
                  <span>Email address</span>
                  <input
                    type="email"
                    required
                    value={checkoutContact.email}
                    onChange={(e) => setCheckoutContact(prev => ({ ...prev, email: e.target.value }))}
                    placeholder="you@example.com"
                    autoComplete="email"
                  />
                </label>
                <label className="pay-field">
                  <span>Phone</span>
                  <input
                    type="tel"
                    required
                    value={checkoutContact.phone}
                    onChange={(e) => setCheckoutContact(prev => ({ ...prev, phone: e.target.value }))}
                    placeholder="Mobile number"
                    autoComplete="tel"
                  />
                </label>
                <label className="pay-field pay-field-wide">
                  <span>Shipping address</span>
                  <input
                    type="text"
                    required
                    value={checkoutContact.address1}
                    onChange={(e) => setCheckoutContact(prev => ({ ...prev, address1: e.target.value }))}
                    placeholder="Street address"
                    autoComplete="shipping address-line1"
                  />
                </label>
                <label className="pay-field pay-field-wide">
                  <span>Apt, suite, unit</span>
                  <input
                    type="text"
                    value={checkoutContact.address2}
                    onChange={(e) => setCheckoutContact(prev => ({ ...prev, address2: e.target.value }))}
                    placeholder="Optional"
                    autoComplete="shipping address-line2"
                  />
                </label>
                <label className="pay-field">
                  <span>City</span>
                  <input
                    type="text"
                    required
                    value={checkoutContact.city}
                    onChange={(e) => setCheckoutContact(prev => ({ ...prev, city: e.target.value }))}
                    placeholder="City"
                    autoComplete="shipping address-level2"
                  />
                </label>
                <label className="pay-field">
                  <span>State</span>
                  <input
                    type="text"
                    required
                    maxLength="2"
                    value={checkoutContact.state}
                    onChange={(e) => setCheckoutContact(prev => ({ ...prev, state: e.target.value.toUpperCase() }))}
                    placeholder="ST"
                    autoComplete="shipping address-level1"
                  />
                </label>
                <label className="pay-field">
                  <span>ZIP</span>
                  <input
                    type="text"
                    required
                    inputMode="numeric"
                    value={checkoutContact.zip}
                    onChange={(e) => setCheckoutContact(prev => ({ ...prev, zip: e.target.value }))}
                    placeholder="ZIP code"
                    autoComplete="shipping postal-code"
                  />
                </label>
              </div>
            </div>

            <div>
              <div className="section-eyebrow">— SELECT YOUR PLAN SIZE</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 16 }}>
                {PLAN_OPTIONS.map((plan) => (
                  <button
                    type="button"
                    key={plan.id}
                    onClick={() => setSelectedPlan(plan)}
                    className={`pay-plan-choice ${selectedPlan.id === plan.id ? 'is-active' : ''}`}
                    style={{
                      textAlign: 'left',
                      background: selectedPlan.id === plan.id ? 'var(--ink)' : 'var(--bg-card)',
                      color: selectedPlan.id === plan.id ? 'var(--bg)' : 'var(--ink)',
                      border: `1px solid ${selectedPlan.id === plan.id ? 'var(--ink)' : 'var(--rule)'}`,
                      borderRadius: 6,
                      padding: '20px 22px',
                      cursor: 'pointer',
                      display: 'grid',
                      gridTemplateColumns: '24px 1fr auto',
                      gap: 16,
                      alignItems: 'flex-start',
                      transition: 'all 0.15s',
                    }}
                  >
                    <span style={{
                      width: 22, height: 22, borderRadius: 4,
                      border: `1.5px solid ${selectedPlan.id === plan.id ? 'var(--bg)' : 'var(--rule)'}`,
                      background: selectedPlan.id === plan.id ? 'var(--bg)' : 'transparent',
                      color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontSize: 14, marginTop: 2,
                    }}>{selectedPlan.id === plan.id ? '✓' : ''}</span>
                    <div>
                      <div style={{ fontWeight: 500, fontSize: 17, display: 'flex', alignItems: 'center', gap: 10 }}>
                        {plan.name}
                        {plan.recommended && (
                          <span style={{
                            fontFamily: 'JetBrains Mono', fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase',
                            background: selectedPlan.id === plan.id ? 'var(--accent-soft)' : 'var(--accent)',
                            color: 'var(--bg)', padding: '3px 8px', borderRadius: 999,
                          }}>RECOMMENDED</span>
                        )}
                      </div>
                      <div style={{ fontSize: 14, marginTop: 4, opacity: 0.85, lineHeight: 1.5 }}>{plan.desc}</div>
                    </div>
                    <div style={{ fontFamily: 'Fraunces', fontSize: 24, letterSpacing: '-0.02em', whiteSpace: 'nowrap' }}>
                      ${plan.price}<span style={{ fontFamily: 'JetBrains Mono', fontSize: 11, opacity: 0.7, marginLeft: 4 }}>/mo</span>
                    </div>
                  </button>
                ))}
              </div>
            </div>

            <div style={{ marginTop: 24 }}>
              <div className="section-eyebrow">— PROVIDER SUPPORT</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 16 }}>
                {SUPPORT_OPTIONS.map((support) => (
                  <button
                    type="button"
                    key={support.id}
                    onClick={() => setSelectedSupport(support)}
                    className={`pay-choice ${selectedSupport.id === support.id ? 'is-active' : ''}`}
                  >
                    <span className="pay-choice-mark">{selectedSupport.id === support.id ? '✓' : ''}</span>
                    <span>
                      <span className="pay-choice-title">
                        {support.name}
                        {support.recommended && <span className="pay-badge">RECOMMENDED</span>}
                      </span>
                      <span className="pay-choice-desc">{support.desc}</span>
                    </span>
                    <span className="pay-choice-price">{support.price ? `$${support.price}/mo` : '$0'}</span>
                  </button>
                ))}
              </div>
            </div>

            <button type="submit" className="btn btn-primary btn-lg" style={{ marginTop: 12, justifyContent: 'center' }} disabled={submitting}>
              {submitting ? 'Opening checkout…' : `Continue to checkout · $${total}/month`}
            </button>
            {error && (
              <div style={{ color: 'var(--accent)', fontSize: 13, lineHeight: 1.4, textAlign: 'center' }}>{error}</div>
            )}
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', color: 'var(--ink-mute)', textTransform: 'uppercase', textAlign: 'center' }}>
              Secure checkout · cancellable any time · COA on every shipment
            </div>
          </form>

          <aside className="paywall-summary">
            <div className="section-eyebrow" style={{ marginBottom: 16 }}>— ORDER SUMMARY</div>
            <div style={{ marginBottom: 20 }}>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-mute)', marginBottom: 6 }}>{trackInfo.name} category</div>
              <div className="serif" style={{ fontSize: 24, lineHeight: 1.1, letterSpacing: '-0.02em' }}>{selectedPlan.slots} peptide plan</div>
            </div>
            {plannedVials.map(v => (
              <div key={v.id} className="summary-row">
                <span style={{ paddingRight: 12 }}>{v.name}</span>
                <span>{v.id === 'primary' ? 'Starting peptide' : 'Choose after review'}</span>
              </div>
            ))}
            <div className="summary-row">
              <span>Cold-chain shipping</span>
              <span>Included</span>
            </div>
            <div className="summary-row">
              <span>{selectedSupport.name}</span>
              <span>{selectedSupport.price ? `$${selectedSupport.price}/mo` : 'Not added'}</span>
            </div>
            <div className="summary-total serif">
              <span>Starting today</span>
              <span>${total}.00 <span className="unit">/ MO</span></span>
            </div>
            <p style={{ fontSize: 13, color: 'var(--ink-soft)', lineHeight: 1.5, margin: '8px 0 0' }}>
              Your profile lets you request switches before the next refill.
            </p>
          </aside>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Paywall, PLAN_OPTIONS, SUPPORT_OPTIONS });
