// Pricing — credit packs vs monthly subscriptions, with mode toggle.
// Cards are selectable (radio-style). One central "Get started →" CTA below
// the grid routes to the portal with ?tier=<id> for the picked tier.
//
// =============================================================================
// DEV NOTE — "Get started" button behaviour
// =============================================================================
// When the user clicks "Get started" they should land in Product Studio with the
// purchase popup already open AND the tier they picked here pre-selected, so all
// they have to do is hit checkout.
//
// Current href contract (see `checkoutHref` below):
//
//     https://productstudio.thevaultstock.com/?tier=<tier-id>
//
// Where <tier-id> is one of:
//   Credit packs : starter | creator | studio | scale | business
//   Monthly      : creator-mo | studio-mo | scale-mo
//
// Implementation on the studio side should be roughly:
//   1. Read `?tier=` from window.location.search on load.
//   2. If present and valid → open the credit-pack / sign-up popup automatically.
//   3. Pre-select that tier inside the popup so the user is one click from
//      checkout.
//   4. After successful payment, the studio is the natural landing surface,
//      so no redirect is needed (they're already there).
//
// If `?tier=` is absent or unknown, just open the studio normally — no popup.
// =============================================================================
function PSPricing({ defaultMode = 'packs' }) {
  const [mode, setMode] = React.useState(defaultMode);
  React.useEffect(() => {setMode(defaultMode);}, [defaultMode]);

  const packs = [
  { id: 'starter', name: 'Starter', price: '$6', credits: '1,000', per: '$0.60 / 100 credits', sub: 'Try a few generations', gens: '10 × 2K · or 5 × 4K', vids: '6 standard · or 2 premium' },
  { id: 'creator', name: 'Creator', price: '$15', credits: '3,000', per: '$0.50 / 100 credits', sub: 'A small launch shoot', gens: '30 × 2K · or 15 × 4K', vids: '20 standard · or 6 premium' },
  { id: 'studio', name: 'Studio', price: '$36', credits: '8,000', per: '$0.45 / 100 credits', sub: 'A full season of imagery', gens: '80 × 2K · or 40 × 4K', vids: '53 standard · or 16 premium', popular: true },
  { id: 'scale', name: 'Scale', price: '$80', credits: '20,000', per: '$0.40 / 100 credits', sub: 'A full brand campaign', gens: '200 × 2K · or 100 × 4K', vids: '133 standard · or 40 premium' },
  { id: 'business', name: 'Business', price: '$180', credits: '50,000', per: '$0.36 / 100 credits', sub: 'Year-round content engine', gens: '500 × 2K · or 250 × 4K', vids: '333 standard · or 100 premium' }];


  const subs = [
  { id: 'creator-mo', name: 'Creator', price: '$13', credits: '3,000', per: '$0.43 / 100 credits', sub: 'Monthly content, lightly', gens: '30 × 2K · or 15 × 4K', vids: '20 standard · or 6 premium' },
  { id: 'studio-mo', name: 'Studio', price: '$30', credits: '8,000', per: '$0.38 / 100 credits', sub: 'A working brand cadence', gens: '80 × 2K · or 40 × 4K', vids: '53 standard · or 16 premium', popular: true },
  { id: 'scale-mo', name: 'Scale', price: '$68', credits: '20,000', per: '$0.34 / 100 credits', sub: 'Full team, full pipeline', gens: '200 × 2K · or 100 × 4K', vids: '133 standard · or 40 premium' }];


  const tiers = mode === 'packs' ? packs : subs;
  const isPacks = mode === 'packs';

  // Selection: default to popular. Reset whenever mode flips.
  const popularId = (tiers.find((t) => t.popular) || tiers[0]).id;
  const [selectedId, setSelectedId] = React.useState(popularId);
  React.useEffect(() => {setSelectedId(popularId);}, [mode]);

  // Shared disclosure: one toggle controls every card's "What's included" panel.
  const [detailsOpen, setDetailsOpen] = React.useState(false);

  const portalBase = typeof window !== 'undefined' && window.PORTAL_URL || 'https://productstudio.thevaultstock.com/';
  const checkoutHref = `${portalBase}?tier=${encodeURIComponent(selectedId)}`;
  const selectedTier = tiers.find((t) => t.id === selectedId) || tiers[0];

  return (
    <section id="pricing" className="ps-section" data-mobile-pad="true" data-mobile-y="lg" style={{ background: 'var(--cream)', padding: '128px 48px 96px' }}>
      {/* Header */}
      <div style={{ maxWidth: 1320, margin: '0 auto 56px', textAlign: 'center' }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>Pricing</div>
        <h2 className="celestial" style={{ fontSize: 'clamp(56px,7vw,120px)', color: 'var(--cocoa)', margin: 0, lineHeight: 1 }}>
          Buy credits,<br />
          <span style={{ fontStyle: 'normal', letterSpacing: '-0.02em', fontFamily: "\"La Villa\"", textTransform: 'none', fontSize: "clamp(28px, 5.5vw, 80px)", display: 'block', marginTop: 8 }}>
            OR SAVE WITH A MONTHLY PLAN.
          </span>
        </h2>
        <p style={{ fontFamily: '"La Villa", sans-serif', fontSize: 16, lineHeight: 1.6, color: 'var(--fg-2)', maxWidth: 540, margin: '24px auto 0' }}>
          Each image uses 100 credits at 2K, or 200 at 4K. Each video uses 500 credits per 5s clip, 1,000 per 10s clip.
          <br />
          <span style={{ fontStyle: 'italic', opacity: 0.75 }}>Purchase some credits, then jump straight into the Product Studio.</span>
        </p>
      </div>

      {/* Mode toggle */}
      <div style={{ maxWidth: 1320, margin: '0 auto 56px', display: 'flex', justifyContent: 'center' }}>
        <div style={{
          display: 'inline-flex', padding: 4, background: 'var(--bg-2)',
          borderRadius: 999, border: '1px solid var(--border-1)'
        }}>
          {[
          { v: 'packs', l: 'Credit Packs', s: 'PAY AS YOU GO' },
          { v: 'subs', l: 'Monthly Plans', s: 'SAVE 15%' }].
          map((o) => {
            const active = mode === o.v;
            return (
              <button key={o.v} onClick={() => setMode(o.v)}
              style={{
                padding: '12px 28px', borderRadius: 999, border: 0,
                background: active ? 'var(--cocoa)' : 'transparent',
                color: active ? 'var(--cream)' : 'var(--cocoa)',
                cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
                transition: 'all 240ms cubic-bezier(.22,.61,.36,1)'
              }}>
                <span style={{ fontFamily: '"La Villa", sans-serif', fontSize: 12, letterSpacing: '0.22em', textTransform: 'uppercase', fontWeight: 500 }}>{o.l}</span>
                <span style={{ fontStyle: 'italic', opacity: active ? 0.85 : 0.55, letterSpacing: 0, textTransform: 'none', fontFamily: "\"La Villa\"", fontSize: "13px" }}>{o.s}</span>
              </button>);

          })}
        </div>
      </div>

      {/* Tier grid */}
      <div className="ps-pricing-grid" style={{
        maxWidth: 1320, margin: '0 auto',
        display: 'grid',
        gridTemplateColumns: isPacks ? 'repeat(5, 1fr)' : 'repeat(3, minmax(0, 1fr))',
        gap: isPacks ? 12 : 20
      }}>
        {tiers.map((t) =>
        <PriceCard
          key={t.id}
          t={t}
          mode={mode}
          selected={selectedId === t.id}
          onSelect={() => setSelectedId(t.id)}
          open={detailsOpen}
          onToggleOpen={() => setDetailsOpen((o) => !o)} />

        )}
      </div>

      {/* Single central CTA */}
      <div style={{
        maxWidth: 1320, margin: '40px auto 0',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14
      }}>
        <a
          href={checkoutHref}
          target="_blank"
          rel="noopener noreferrer"
          data-dev-note="Routes to the studio with ?tier=<id>. The studio should auto-open the purchase popup with this tier pre-selected. See ps_pricing.jsx header for full contract."
          style={{
            padding: '18px 44px',
            background: 'var(--cocoa)', color: 'var(--cream)',
            borderRadius: 999, border: 0, cursor: 'pointer', textDecoration: 'none',
            fontFamily: '"La Villa", sans-serif', fontSize: 12, letterSpacing: '0.22em',
            textTransform: 'uppercase', fontWeight: 500,
            display: 'inline-flex', alignItems: 'center', gap: 12,
            transition: 'transform 240ms cubic-bezier(.22,.61,.36,1)'
          }}
          onMouseEnter={(e) => {e.currentTarget.style.transform = 'translateY(-2px)';}}
          onMouseLeave={(e) => {e.currentTarget.style.transform = 'none';}}>
          Get started
          <span style={{ fontFamily: '"La Villa", sans-serif', fontSize: 14, letterSpacing: 0 }}>→</span>
        </a>
        <div style={{
          fontFamily: '"La Villa", sans-serif', fontStyle: 'italic',
          fontSize: 13, color: 'var(--fg-2)', opacity: 0.85, textAlign: 'center'
        }}>
          You picked <strong style={{ fontStyle: 'normal', fontWeight: 500, color: 'var(--cocoa)' }}>{selectedTier.name}</strong>
          {' · '}
          <span style={{ fontVariantNumeric: 'tabular-nums' }}>{selectedTier.price}</span>
          {' · '}
          <span style={{ fontVariantNumeric: 'tabular-nums' }}>{selectedTier.credits} credits</span>
          {!isPacks && ' / month'}
        </div>
      </div>
    </section>);

}

function PriceCard({ t, mode, selected, onSelect, open, onToggleOpen }) {
  const [h, setH] = React.useState(false);
  const featured = !!t.popular;
  const isPacks = mode === 'packs';
  const accent = selected || featured ? 'var(--sand)' : 'var(--fg-2)';

  // Visual states:
  //  - selected: dark cocoa fill, cream text (highest emphasis)
  //  - featured (but not selected): cream fill, cocoa text, with a "Most picked" tag
  //  - default: light bg-2, cocoa text
  const bg = selected ? 'var(--cocoa)' : 'var(--bg-2)';
  const fg = selected ? 'var(--cream)' : 'var(--cocoa)';
  const border = selected ?
  '1px solid var(--cocoa)' :
  featured ? '1px solid var(--cocoa)' : '1px solid var(--border-1)';

  const handleCardActivate = (e) => {
    // Don't toggle selection when clicking the inner disclosure button
    if (e.target.closest('[data-pricing-disclose]')) return;
    onSelect();
  };
  const handleKey = (e) => {
    if (e.key === 'Enter' || e.key === ' ') {
      if (e.target.closest('[data-pricing-disclose]')) return;
      e.preventDefault();
      onSelect();
    }
  };

  return (
    <div
      role="button"
      tabIndex={0}
      onClick={handleCardActivate}
      onKeyDown={handleKey}
      onMouseEnter={() => setH(true)}
      onMouseLeave={() => setH(false)}
      aria-pressed={selected}
      style={{
        textAlign: 'left',
        background: bg,
        color: fg,
        padding: isPacks ? '28px 22px 22px' : '34px 30px 28px',
        display: 'flex', flexDirection: 'column',
        border,
        borderRadius: 3,
        position: 'relative',
        cursor: 'pointer',
        font: 'inherit',
        outline: 'none',
        transition: 'transform 240ms cubic-bezier(.22,.61,.36,1), background 200ms, color 200ms, border-color 200ms, box-shadow 240ms',
        transform: h || selected ? 'translateY(-3px)' : 'none',
        boxShadow: selected ? '0 18px 36px rgba(42,36,32,0.22)' : 'none'
      }}>
      {featured && !selected &&
      <div style={{
        position: 'absolute', top: -10, left: '50%', transform: 'translateX(-50%)',
        background: 'var(--cocoa)', color: 'var(--cream)',
        padding: '4px 10px', fontSize: 9, letterSpacing: '0.22em',
        textTransform: 'uppercase', borderRadius: 999, fontWeight: 500, whiteSpace: 'nowrap'
      }}>Most picked</div>
      }

      {/* Tier name */}
      <div className="eyebrow" style={{ color: accent, marginBottom: 14 }}>{t.name}</div>

      {/* Price */}
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
        <span style={{
          fontFamily: '"La Villa", sans-serif', fontWeight: 500,
          fontSize: isPacks ? 56 : 64, lineHeight: 1, letterSpacing: '-0.02em',
          fontVariantNumeric: 'tabular-nums'
        }}>{t.price}</span>
        {!isPacks && <span style={{ fontFamily: '"La Villa", sans-serif', fontSize: 13, color: accent }}>/mo</span>}
      </div>

      {/* Credits */}
      <div style={{ marginTop: 18, display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span style={{
          fontFamily: '"La Villa", sans-serif', fontWeight: 500,
          fontSize: isPacks ? 22 : 26, letterSpacing: '-0.01em',
          fontVariantNumeric: 'tabular-nums'
        }}>{t.credits}</span>
        <span style={{
          fontFamily: '"La Villa", sans-serif', fontSize: 10, letterSpacing: '0.22em',
          textTransform: 'uppercase', color: accent
        }}>credits</span>
      </div>

      {/* Tagline */}
      <div style={{ fontFamily: '"La Villa", sans-serif', fontStyle: 'normal', fontSize: 14, color: accent, marginTop: 10, lineHeight: 1.35 }}>
        {t.sub}
      </div>

      <div style={{ flex: 1, minHeight: 16 }} />

      {/* Selection indicator (acts as the visual confirm of click-to-select) */}
      <div style={{
        marginTop: 18, paddingTop: 14,
        borderTop: `1px solid ${selected ? 'rgba(242,236,228,0.18)' : 'var(--border-1)'}`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontFamily: '"La Villa", sans-serif', fontSize: 10, letterSpacing: '0.22em',
        textTransform: 'uppercase', fontWeight: 500, color: accent
      }}>
        <span>{selected ? 'Selected' : 'Select'}</span>
        <span aria-hidden="true" style={{
          width: 16, height: 16, borderRadius: '50%',
          border: `1.5px solid ${selected ? 'var(--cream)' : 'var(--cocoa)'}`,
          background: selected ? 'var(--cream)' : 'transparent',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          transition: 'background 200ms, border-color 200ms'
        }}>
          {selected &&
          <span style={{
            width: 6, height: 6, borderRadius: '50%', background: 'var(--cocoa)'
          }} />
          }
        </span>
      </div>

      {/* "What's included" disclosure */}
      <button
        data-pricing-disclose
        type="button"
        onClick={(e) => {e.stopPropagation();onToggleOpen();}}
        aria-expanded={open}
        style={{
          marginTop: 12, padding: '6px 0',
          background: 'transparent', border: 0,
          color: fg, opacity: 0.75, cursor: 'pointer',
          fontFamily: '"La Villa", sans-serif', fontSize: 10, letterSpacing: '0.22em',
          textTransform: 'uppercase', fontWeight: 500,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          transition: 'opacity 200ms'
        }}
        onMouseEnter={(e) => {e.currentTarget.style.opacity = 1;}}
        onMouseLeave={(e) => {e.currentTarget.style.opacity = 0.75;}}>
        <span>{open ? 'Hide details' : 'What\u2019s included'}</span>
        <span style={{
          fontFamily: '"La Villa", sans-serif', fontSize: 13, letterSpacing: 0,
          transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 220ms'
        }}>↓</span>
      </button>
      <div style={{
        overflow: 'hidden',
        maxHeight: open ? 240 : 0,
        opacity: open ? 1 : 0,
        transition: 'max-height 280ms cubic-bezier(.22,.61,.36,1), opacity 220ms'
      }}>
        <dl style={{
          margin: '12px 0 0', padding: 0,
          display: 'grid', gridTemplateColumns: '1fr auto', rowGap: 8, columnGap: 12,
          fontFamily: '"La Villa", sans-serif', fontSize: 12, color: fg
        }}>
          <dt style={{ color: accent }}>Billing</dt>
          <dd style={{ margin: 0, textAlign: 'right' }}>{isPacks ? 'One-time' : 'Monthly'}</dd>
          <dt style={{ color: accent }}>Per 100 credits</dt>
          <dd style={{ margin: 0, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{(t.per.match(/\$[\d.]+/) || [''])[0]}</dd>
          <dt style={{ color: accent }}>Images</dt>
          <dd style={{ margin: 0, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{t.gens.replace(' · ', ' / ')}</dd>
          <dt style={{ color: accent }}>Videos (5s)</dt>
          <dd style={{ margin: 0, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{t.vids ? t.vids.replace(' · ', ' / ') : '—'}</dd>
          <dt style={{ color: accent }}>{isPacks ? 'Expires' : 'Cancel'}</dt>
          <dd style={{ margin: 0, textAlign: 'right' }}>{isPacks ? 'Never' : 'Anytime'}</dd>
        </dl>
      </div>
    </div>);

}

Object.assign(window, { PSPricing });