// "Fresh every week" — auto-pulls the most recent Vault Stock collections
// from the public Playbook browse endpoint and shows their covers. Hidden
// collections are filtered server-side via vault_collection_visibility, so
// only admin-toggled-live ones appear here. Never needs manual updating.

function PSDrops() {
  const [drops, setDrops] = React.useState(null);
  const [errored, setErrored] = React.useState(false);

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await fetch('/api/playbook/browse?mode=recent-collections&limit=6');
        if (!res.ok) throw new Error(`status ${res.status}`);
        const json = await res.json();
        if (cancelled) return;
        const list = Array.isArray(json?.collections) ? json.collections : [];
        setDrops(list);
      } catch {
        if (!cancelled) setErrored(true);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  return (
    <section
      id="drops"
      className="ps-section"
      data-mobile-pad="true"
      data-mobile-y="lg"
      style={{ background: 'var(--cream)', padding: '128px 48px' }}
    >
      <div
        className="ps-stack-mobile"
        style={{
          maxWidth: 1320,
          margin: '0 auto 64px',
          display: 'grid',
          gridTemplateColumns: '1fr 1fr',
          gap: 64,
          alignItems: 'end',
        }}
      >
        <div>
          <div className="eyebrow" style={{ marginBottom: 14 }}>
            <span
              style={{
                display: 'inline-block',
                width: 24,
                height: 1,
                background: 'var(--cocoa)',
                verticalAlign: 'middle',
                marginRight: 12,
              }}
            ></span>
            Fresh every week
          </div>
          <h2
            className="celestial"
            style={{
              fontSize: 'clamp(48px,6vw,96px)',
              color: 'var(--cocoa)',
              margin: 0,
            }}
          >
            New collections,<br />every&nbsp;week.
          </h2>
        </div>
        <p
          style={{
            fontFamily: '"La Villa", sans-serif',
            fontSize: 17,
            lineHeight: 1.6,
            color: 'var(--fg-2)',
            maxWidth: 460,
            margin: 0,
            justifySelf: 'end',
          }}
        >
          New photography lands in The Vault Stock library every week. The moment a collection goes live, every image inside it is available in Product Studio. Nothing to upgrade, nothing to download.
        </p>
      </div>

      {drops === null && !errored && (
        <div
          className="ps-drops-grid-skeleton"
          style={{
            maxWidth: 1320,
            margin: '0 auto',
            display: 'grid',
            gridTemplateColumns: 'repeat(6, 1fr)',
            gap: 12,
          }}
        >
          {Array.from({ length: 6 }).map((_, i) => (
            <div
              key={i}
              style={{
                aspectRatio: '3 / 4',
                background: 'var(--cream-deep)',
                opacity: 0.6,
              }}
            />
          ))}
        </div>
      )}

      {drops && drops.length > 0 && (
        <div
          className="ps-drops-grid"
          style={{
            maxWidth: 1320,
            margin: '0 auto',
            display: 'grid',
            gridTemplateColumns: `repeat(${Math.min(drops.length, 6)}, 1fr)`,
            gap: 12,
          }}
        >
          {drops.slice(0, 6).map((d) => (
            <div key={d.name} style={{ position: 'relative' }}>
              <div
                style={{
                  position: 'relative',
                  width: '100%',
                  aspectRatio: '3 / 4',
                  overflow: 'hidden',
                  background: d.dominant_color || 'var(--cream-deep)',
                  boxShadow: '0 12px 30px -12px rgba(42,36,32,0.30)',
                }}
              >
                {d.thumbnail && (
                  <img
                    src={d.thumbnail}
                    alt={d.name}
                    loading="lazy"
                    className="no-save"
                    draggable={false}
                    onContextMenu={(e) => e.preventDefault()}
                    style={{
                      position: 'absolute',
                      inset: 0,
                      width: '100%',
                      height: '100%',
                      objectFit: 'cover',
                      objectPosition: 'center',
                    }}
                  />
                )}
                {/* Bottom gradient for legibility */}
                <div
                  style={{
                    position: 'absolute',
                    inset: 0,
                    background:
                      'linear-gradient(0deg, rgba(42,36,32,0.65) 0%, rgba(42,36,32,0) 45%)',
                  }}
                />
                <div
                  style={{
                    position: 'absolute',
                    left: 12,
                    right: 12,
                    bottom: 12,
                    color: 'var(--cream)',
                  }}
                >
                  <div
                    style={{
                      fontFamily: '"La Villa", sans-serif',
                      fontSize: 9,
                      letterSpacing: '0.22em',
                      textTransform: 'uppercase',
                      opacity: 0.7,
                      marginBottom: 4,
                    }}
                  >
                    {d.parent === 'ai_generated' ? 'AI generated' : 'Photos'}
                  </div>
                  <div
                    style={{
                      fontFamily: '"La Villa", sans-serif',
                      fontSize: 14,
                      fontWeight: 500,
                      lineHeight: 1.2,
                    }}
                  >
                    {d.name}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {(errored || (drops && drops.length === 0)) && (
        <div
          style={{
            maxWidth: 1320,
            margin: '0 auto',
            padding: '32px 0',
            textAlign: 'center',
            fontFamily: '"La Villa", sans-serif',
            fontSize: 14,
            color: 'var(--fg-2)',
          }}
        >
          Latest collections refresh on every page load. Reload to see them.
        </div>
      )}

      <style>{`
        @media (max-width: 1100px) {
          .ps-drops-grid, .ps-drops-grid-skeleton {
            grid-template-columns: repeat(3, 1fr) !important;
          }
        }
        @media (max-width: 780px) {
          .ps-drops-grid, .ps-drops-grid-skeleton {
            grid-template-columns: repeat(2, 1fr) !important;
            gap: 8px !important;
          }
        }
      `}</style>
    </section>
  );
}

Object.assign(window, { PSDrops });
