// Hero — cycling equation: product + original scene + model = output
// Auto-advances every 5s, pauses on hover/focus, with dot pagination + arrows.
// Mobile (≤780px): headline + promise + CTA come FIRST (above the fold), the
// equation visual follows underneath. See the HeroStyles mobile block.

const EQUATION_EXAMPLES = [
  { og: 'assets/eq-og-1.jpg', output: 'assets/eq-output-1.jpg', model: 'assets/eq-model-head.jpg' },
  { og: 'assets/eq-og-9.jpg', output: 'assets/eq-output-9.jpg', model: 'assets/eq-model-9.jpg' },
  { og: 'assets/eq-og-10.jpg', output: 'assets/eq-output-10.jpg', model: 'assets/eq-model-10.jpg' },
  { og: 'assets/eq-og-2.jpg', output: 'assets/eq-output-2.jpg', model: 'assets/eq-model-2.jpg' },
  { og: 'assets/eq-og-4.jpg', output: 'assets/eq-output-4.jpg', model: 'assets/eq-model-4.jpg' },
  { og: 'assets/eq-og-5.jpg', output: 'assets/eq-output-5.jpg', model: 'assets/eq-model-5.jpg' },
  { og: 'assets/eq-og-6.jpg', output: 'assets/eq-output-6.jpg', model: 'assets/eq-model-6.jpg' },
  { og: 'assets/eq-og-7.jpg', output: 'assets/eq-output-7.jpg', model: 'assets/eq-model-7.jpg' },
  { og: 'assets/eq-og-8.jpg', output: 'assets/eq-output-8.jpg', model: 'assets/eq-model-8.jpg' },
  { og: 'assets/eq-og-3.jpg', output: 'assets/eq-output-3.jpg', model: 'assets/eq-model-3.jpg' },
];

const EQUATION_PRODUCT = 'assets/eq-product.jpg';

function PSHero() {
  return (
    <section className="ps-section ps-hero" data-mobile-pad="true" data-mobile-y="md" style={{
      position: 'relative', minHeight: '100vh', background: 'var(--cream)',
      paddingTop: 120, overflow: 'hidden'
    }}>
      <div className="ps-stack-mobile ps-hero-stack-mobile" style={{
        display: 'grid',
        gridTemplateColumns: '1fr 1.15fr',
        gap: 0,
        minHeight: 'calc(100vh - 120px)',
        alignItems: 'stretch'
      }}>
        {/* LEFT, typographic slab */}
        <div className="ps-hero-slab" data-mobile-pad="true" style={{ padding: '40px 64px 64px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 24 }}>
              <span style={{ display: 'inline-block', width: 24, height: 1, background: 'var(--cocoa)', verticalAlign: 'middle', marginRight: 12 }}></span>
              By The Vault Stock · Authentic × AI Hybrid
            </div>
            <h1 className="celestial ps-hero-display" style={{
              fontSize: 'clamp(64px, 8.4vw, 132px)',
              color: 'var(--cocoa)', margin: 0, letterSpacing: "0.669px", lineHeight: 0.95
            }}>
              VAULT CREATIVE STUDIO.
              <span className="ps-hero-display-sub" style={{ display: 'block', marginTop: 20, fontStyle: 'normal', letterSpacing: '-0.01em', fontWeight: 400, fontFamily: "\"La Villa\"", fontSize: 'clamp(28px, 3.4vw, 46px)', lineHeight: 1.1 }}>Create with 10,000 real images, or BYO.</span>
            </h1>
            <p className="ps-hero-body" style={{
              fontFamily: '"La Villa", sans-serif', fontSize: 17, lineHeight: 1.55,
              color: 'var(--fg-2)', maxWidth: 460, marginTop: 36
            }}>
              Bring your product, or just create. Play with the whole Vault Stock library, <em style={{ fontFamily: '"La Villa", sans-serif', fontStyle: 'normal' }}>real photographs</em>, not AI slop, or upload your own. Our engine places your product like it was shot there. No shoot. No studio.
            </p>
            <div className="ps-hero-cta-row" style={{ display: 'flex', gap: 16, marginTop: 40, flexWrap: 'wrap', alignItems: 'center' }}>
              <PSPrimary href={window.PORTAL_URL || '/dashboard/product-studio'}>Open the Studio</PSPrimary>
              <PSSecondary href="/examples">See examples</PSSecondary>
              {/* Mobile only — on desktop the nav already carries Pricing, and a
                  third pill here crowds the hero. */}
              <PSSecondary href="/pricing" className="ps-hero-pricing-cta">View pricing</PSSecondary>
            </div>
            <div style={{
              marginTop: 18,
              fontFamily: '"La Villa", sans-serif',
              fontStyle: 'italic',
              fontSize: 13,
              color: 'var(--fg-2)',
              opacity: 0.85,
              letterSpacing: '0.01em'
            }}>
              Free to explore. Credits to generate.
            </div>
            <div style={{
              marginTop: 14,
              fontFamily: '"La Villa", sans-serif',
              fontSize: 12.5,
              color: 'var(--fg-2)',
              opacity: 0.9,
              letterSpacing: '0.03em'
            }}>
              Trusted by 10,000+ creatives · hundreds of thousands of downloads
            </div>
          </div>

          {/* Stat row — on DESKTOP it sits at the bottom of the slab. On mobile
              this copy is hidden and the stats reappear below the image (see the
              ps-hero-stats-mobile block) so the page reads words → image → words. */}
          <HeroStats className="ps-hide-mobile" />
        </div>

        {/* RIGHT, cycling equation */}
        <div className="ps-hero-visual" style={{ position: 'relative', overflow: 'hidden', minHeight: 'min(70vh, 600px)' }}>
          <HeroEquation />
        </div>

        {/* Mobile-only: the stats land UNDER the image, completing the
            words → image → words rhythm. Hidden on desktop. */}
        <div className="ps-hero-stats-mobile" data-mobile-pad="true">
          <HeroStats mobile />
        </div>
      </div>
    </section>);

}

/* The four trust stats. Shared between the desktop slab and the mobile block
   so the copy stays in one place. `mobile` drops the top margin since on
   mobile it sits under the image rather than at the bottom of the slab. */
function HeroStats({ className = '', mobile = false }) {
  const items = [
    ['10,000+', 'image library or BYO'],
    ['130+', 'models in the library'],
    ['all categories', 'skincare to homewares'],
    ['2K · 4K', 'commercial-ready output'],
  ];
  return (
    <div className={`ps-hero-stat-row ${className}`} style={{
      display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 24,
      marginTop: mobile ? 0 : 56, paddingTop: 24, borderTop: '1px solid var(--border-1)'
    }}>
      {items.map(([n, l]) =>
        <div key={l}>
          <div style={{ fontFamily: '"La Villa", sans-serif', fontWeight: 500, fontSize: 22, color: 'var(--cocoa)', lineHeight: 1, letterSpacing: '-0.01em' }}>{n}</div>
          <div className="eyebrow" style={{ marginTop: 6, fontSize: 10 }}>{l}</div>
        </div>
      )}
    </div>
  );
}

/* ============================================================
   HERO EQUATION
   product + original + model = output, cycling through 8 examples.
   Auto-advances every 5s, pauses on hover. Dots + arrows.
   ============================================================ */
function HeroEquation() {
  const [idx, setIdx] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const total = EQUATION_EXAMPLES.length;

  // Smart preload — only the first example is loaded eagerly so first paint
  // is fast. Remaining examples are deferred 2.5s after mount so they don't
  // compete with critical above-the-fold assets, then loaded in the
  // background. Combined with the JIT preload below, the user always has
  // the next example ready by the time the cycle advances.
  React.useEffect(() => {
    const eager = [EQUATION_PRODUCT, EQUATION_EXAMPLES[0].og, EQUATION_EXAMPLES[0].output, EQUATION_EXAMPLES[0].model];
    eager.forEach(u => { const i = new Image(); i.src = u; });
    const t = setTimeout(() => {
      EQUATION_EXAMPLES.slice(1).forEach(e => {
        [e.og, e.output, e.model].forEach(u => { const i = new Image(); i.src = u; });
      });
    }, 2500);
    return () => clearTimeout(t);
  }, []);

  // JIT preload the next example whenever idx changes — covers the case
  // where the deferred preload above hasn't finished yet (slow connection)
  // or the user clicks ahead manually.
  React.useEffect(() => {
    const nextIdx = (idx + 1) % total;
    const e = EQUATION_EXAMPLES[nextIdx];
    [e.og, e.output, e.model].forEach(u => { const i = new Image(); i.src = u; });
  }, [idx, total]);

  React.useEffect(() => {
    if (paused) return;
    const t = setInterval(() => setIdx(i => (i + 1) % total), 5200);
    return () => clearInterval(t);
  }, [paused, total]);

  const current = EQUATION_EXAMPLES[idx];
  const next = () => setIdx((idx + 1) % total);
  const prev = () => setIdx((idx - 1 + total) % total);

  return (
    <div
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      onFocus={() => setPaused(true)}
      onBlur={() => setPaused(false)}
      style={{
        position: 'absolute', inset: 0,
        display: 'flex', flexDirection: 'column',
        alignItems: 'stretch', justifyContent: 'center',
        padding: '24px 32px 24px 12px',
        gap: 14,
      }}>

      {/* Recipe strip on top: the three ingredients. */}
      <div className="ps-hero-equation-row" style={{
        display: 'grid',
        gridTemplateColumns: '1fr auto 1fr auto 1fr',
        alignItems: 'center',
        gap: 10,
        flex: '0 0 auto',
        maxWidth: 480,
        width: '100%',
        margin: '0 auto',
      }}>
        <StripCell src={EQUATION_PRODUCT} label="Upload product" tone="cream" mode="cover" />
        <EquationOperator>+</EquationOperator>
        <StripCell src={current.model} label="Pick model" tone="dark" mode="cover" animateKey={`model-${idx}`} />
        <EquationOperator>+</EquationOperator>
        <StripCell src={current.og} label="Add Vault scene" tone="dark" mode="cover" animateKey={`og-${idx}`} />
      </div>

      {/* Equals sign bridging the ingredients to the result */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        gap: 10, flex: '0 0 auto',
      }}>
        <span style={{ display: 'inline-block', width: 28, height: 1, background: 'var(--cocoa)', opacity: 0.35 }} />
        <span style={{
          fontFamily: '"La Villa", sans-serif', fontSize: 22, lineHeight: 1,
          color: 'var(--cocoa)', opacity: 0.6, fontWeight: 300, userSelect: 'none',
        }}>=</span>
        <span style={{ display: 'inline-block', width: 28, height: 1, background: 'var(--cocoa)', opacity: 0.35 }} />
      </div>

      {/* BIG OUTPUT (the hero visual) — now sits under the recipe + equals. */}
      <div className="ps-hero-output" style={{
        position: 'relative', flex: '1 1 auto', minHeight: 0,
        display: 'flex', alignItems: 'stretch', justifyContent: 'center',
      }}>
        <div style={{
          position: 'relative', height: '100%', aspectRatio: '4 / 5',
          maxWidth: '100%', overflow: 'hidden', borderRadius: 4,
          boxShadow: '0 30px 70px -20px rgba(42,36,32,0.45), 0 8px 22px rgba(42,36,32,0.16)',
        }}>
          <img
            key={`hero-out-${idx}`}
            src={current.output} alt={`Output, example ${idx + 1}`}
            loading="eager" decoding="async"
            style={{
              position: 'absolute', inset: 0, width: '100%', height: '100%',
              objectFit: 'cover', objectPosition: 'center',
              animation: 'eqFade 600ms cubic-bezier(.22,.61,.36,1)',
            }}
          />
          <div style={{
            position: 'absolute', top: 12, left: 12,
            fontFamily: '"La Villa", sans-serif', fontSize: 9.5,
            letterSpacing: '0.22em', textTransform: 'uppercase',
            color: 'var(--cream)', background: 'rgba(42,36,32,0.55)',
            backdropFilter: 'blur(6px)', padding: '6px 10px', borderRadius: 999,
          }}>Result</div>
          <div style={{
            position: 'absolute', bottom: 12, right: 12,
            fontFamily: '"La Villa", sans-serif', fontSize: 9.5,
            letterSpacing: '0.22em', textTransform: 'uppercase',
            color: 'var(--cream)', background: 'rgba(42,36,32,0.55)',
            backdropFilter: 'blur(6px)', padding: '6px 10px', borderRadius: 999,
            fontVariantNumeric: 'tabular-nums',
          }}>{String(idx + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}</div>
          <button className="ps-hero-arrow ps-hero-arrow-prev" onClick={(e) => { e.preventDefault(); e.stopPropagation(); prev(); }} aria-label="Previous example" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', width: 40, height: 40, borderRadius: 999, border: 0, cursor: 'pointer', background: 'rgba(42,36,32,0.5)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', color: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: '"La Villa", sans-serif', fontSize: 20, lineHeight: 1 }}>‹</button>
          <button className="ps-hero-arrow ps-hero-arrow-next" onClick={(e) => { e.preventDefault(); e.stopPropagation(); next(); }} aria-label="Next example" style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', width: 40, height: 40, borderRadius: 999, border: 0, cursor: 'pointer', background: 'rgba(42,36,32,0.5)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', color: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: '"La Villa", sans-serif', fontSize: 20, lineHeight: 1 }}>›</button>
        </div>
      </div>

      {/* Dots (arrows now overlay the image left/right) */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
        {EQUATION_EXAMPLES.map((_, i) => (
          <button key={i} onClick={() => setIdx(i)} aria-label={`Show example ${i + 1}`} style={{
            width: i === idx ? 22 : 7, height: 7, borderRadius: 999,
            background: i === idx ? 'var(--cocoa)' : 'rgba(42,36,32,0.25)',
            border: 0, padding: 0, cursor: 'pointer',
            transition: 'width 240ms cubic-bezier(.22,.61,.36,1), background 200ms',
          }} />
        ))}
      </div>
    </div>
  );
}

/* Small thumbnail cell used in the equation strip below the big output hero. */
function StripCell({ src, label, tone, mode, animateKey, highlight }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6, minWidth: 0 }}>
      <div style={{
        position: 'relative', width: '100%', aspectRatio: '3 / 4',
        overflow: 'hidden', borderRadius: 3,
        background: tone === 'cream' ? 'var(--cream-deep, #EFE7DC)' : 'var(--cocoa-deep, #1d1814)',
        outline: highlight ? '1px solid var(--cocoa)' : 'none',
        outlineOffset: highlight ? 2 : 0,
        boxShadow: '0 6px 14px -8px rgba(42,36,32,0.28)',
      }}>
        <img
          key={animateKey || src}
          src={src} alt={label}
          loading="eager" decoding="async"
          style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%',
            objectFit: mode === 'contain' ? 'contain' : 'cover',
            objectPosition: 'center',
            animation: animateKey ? 'eqFade 600ms cubic-bezier(.22,.61,.36,1)' : undefined,
          }}
        />
      </div>
      <div style={{
        fontFamily: '"La Villa", sans-serif', fontSize: 9,
        letterSpacing: '0.22em', textTransform: 'uppercase',
        color: 'var(--cocoa)', opacity: highlight ? 1 : 0.85,
        textAlign: 'center',
        fontWeight: highlight ? 500 : 400,
      }}>{label}</div>
    </div>
  );
}

function EquationOperator({ children }) {
  return (
    <div style={{
      fontFamily: '"La Villa", sans-serif', fontWeight: 300,
      fontSize: 22, lineHeight: 1, color: 'var(--cocoa)',
      opacity: 0.6, padding: '0 2px', userSelect: 'none',
      alignSelf: 'center', marginBottom: 14, // visual-balance with cell labels
    }}>{children}</div>
  );
}

function ArrowBtn({ children, onClick, ...rest }) {
  return (
    <button onClick={onClick} {...rest} style={{
      width: 36, height: 36, borderRadius: 999,
      background: 'transparent', border: '1px solid var(--border-2)',
      color: 'var(--cocoa)', fontFamily: '"La Villa", sans-serif',
      fontSize: 18, cursor: 'pointer', lineHeight: 1,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      transition: 'background 180ms, border-color 180ms',
    }}
    onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--cocoa)'; e.currentTarget.style.color = 'var(--cream)'; }}
    onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--cocoa)'; }}
    >{children}</button>
  );
}

/* Inline keyframes + responsive equation layout, scoped via a one-off <style>. */
function HeroStyles() {
  return (
    <style>{`
      @keyframes eqFade {
        from { opacity: 0; transform: scale(1.015); }
        to   { opacity: 1; transform: scale(1); }
      }
      /* Stats below the image are mobile-only; desktop keeps them in the slab. */
      .ps-hero-stats-mobile { display: none; }
      /* "View pricing" pill is mobile-only (desktop nav already has Pricing). */
      .ps-hero-pricing-cta { display: none !important; }
      /* Strip stays as 4 thumbnails on every breakpoint — it's already small,
         the operators just tighten on narrower screens. */
      @media (max-width: 780px) {
        /* Keep the recipe strip compact so the RESULT image below it can be big. */
        .ps-hero-equation-row { gap: 6px !important; max-width: 300px !important; }
        /* Bigger result image; smaller, edge-hugging arrows so they don't cover it. */
        .ps-hero-arrow { width: 34px !important; height: 34px !important; font-size: 16px !important; background: rgba(42,36,32,0.4) !important; }
        .ps-hero-arrow-prev { left: 5px !important; }
        .ps-hero-arrow-next { right: 5px !important; }
        /* Mobile reading order: words → image → words. Explicit per-child orders
           (the slab, the visual, then the stats) override the global :last-child
           rules now that the hero has a third child, the mobile stat block. */
        .ps-hero-stack-mobile { gap: 18px !important; }
        /* Let the hero be exactly as tall as its content on mobile. The forced
           100vh height (great on desktop) was leaving a big empty gap under the
           stats before the next section. */
        .ps-hero { min-height: 0 !important; }
        .ps-hero-stack-mobile { min-height: 0 !important; }
        .ps-hero-stack-mobile > .ps-hero-slab { order: 0 !important; padding-top: 4px !important; padding-bottom: 24px !important; }
        .ps-hero-stack-mobile > .ps-hero-visual { order: 1 !important; min-height: 64vh !important; }
        /* Extra ancestor (.ps-hero) raises specificity above the global
           ".ps-stack-mobile > div:last-child { min-height: 60vh }" rule, which
           was otherwise inflating the stats block (now the last child) to 60vh
           and leaving a huge empty stretch under it. */
        .ps-hero .ps-hero-stack-mobile > .ps-hero-stats-mobile { order: 2 !important; min-height: 0 !important; display: block !important; padding-top: 6px !important; padding-bottom: 4px !important; }
        .ps-hero-output > div { aspect-ratio: 5 / 6 !important; }
        /* Clear the tall fixed mobile nav (~118px: hamburger stacked over the logo)
           and give the eyebrow real breathing room below it. */
        .ps-hero[data-mobile-y="md"] { padding-top: 138px !important; }
        /* Compact type hierarchy that fits the first screen on a phone. */
        .ps-hero-display { font-size: 38px !important; line-height: 0.98 !important; letter-spacing: 0 !important; }
        .ps-hero-display-sub { font-size: 20px !important; margin-top: 12px !important; line-height: 1.12 !important; }
        .ps-hero-body { font-size: 15.5px !important; margin-top: 18px !important; }
        .ps-hero-cta-row { margin-top: 24px !important; gap: 12px !important; flex-wrap: wrap !important; }
        .ps-hero-cta-row > a { justify-content: center !important; }
        /* Show the pricing pill on mobile. */
        .ps-hero-pricing-cta { display: inline-flex !important; }
        /* Primary fills its own row; "See examples" + "View pricing" split the next. */
        .ps-hero-cta-row > a:first-child { flex: 1 1 100% !important; }
        .ps-hero-cta-row > a:not(:first-child) { flex: 1 1 0 !important; }
      }
    `}</style>
  );
}

Object.assign(window, { PSHero, HeroStyles, EQUATION_EXAMPLES, EQUATION_PRODUCT });
