// screens-drops.jsx — Limited-edition game-specific merch drops.
//
// Exposes:
//   DropToast        — slide-down notification announcing an active drop
//   DropHeroCard     — large product hero card for Watch tab + Home
//   DropDetailScreen — full-screen drop detail (image, story, size, buy)
//   DropPlaceholder  — CSS placeholder when imagePath fails to load
//
// Drops come from the tenant's `DROPS` array (set by applyTenantToData).

// ─────────────────────────────────────────────────────────────────────
// DropPlaceholder — used when imagePath is missing or fails. Shows a
// branded gradient tile with the product emoji centered. Intentional so
// missing images don't look broken before user provides the assets.
// ─────────────────────────────────────────────────────────────────────
function DropPlaceholder({ drop, size = 'lg' }) {
  const accent = drop.accent || WVU.gold;
  const px = size === 'sm' ? 40 : (size === 'md' ? 64 : 112);
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: `
        radial-gradient(ellipse 70% 60% at 50% 30%, ${hexA(accent, 0.45)}, transparent 65%),
        linear-gradient(160deg, ${WVU.ink2}, #000)
      `,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div style={{
        fontSize: px, lineHeight: 1,
        filter: 'drop-shadow(0 8px 24px rgba(0,0,0,0.6))',
      }}>{drop.emoji || '\u{1F455}'}</div>
    </div>
  );
}

// Helper: smart drop image with onError → placeholder fallback
function DropImage({ drop, size = 'lg', objectPosition = 'center' }) {
  const [ok, setOk] = React.useState(true);
  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      {ok && drop.imagePath ? (
        <img
          src={drop.imagePath}
          alt={drop.title}
          onError={() => setOk(false)}
          style={{
            position: 'absolute', inset: 0,
            width: '100%', height: '100%',
            objectFit: 'cover',
            objectPosition,
          }}
        />
      ) : (
        <DropPlaceholder drop={drop} size={size} />
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// DROP TOAST — slide-down notification when a drop unlocks
// Props:
//   drop:     drop config to feature
//   onTap:    () => void   — opens the drop detail
//   onClose:  () => void
//   visible:  bool (controls render)
// Auto-dismisses after 7 seconds.
// ─────────────────────────────────────────────────────────────────────
function DropToast({ drop, onTap, onClose, visible }) {
  React.useEffect(() => {
    if (!visible) return;
    const t = setTimeout(() => onClose && onClose(), 7000);
    return () => clearTimeout(t);
  }, [visible, onClose]);

  if (!visible || !drop) return null;
  const accent = drop.accent || WVU.gold;
  const pctLeft = Math.round((drop.stockLeft / drop.stockTotal) * 100);

  return (
    <div style={{
      position: 'absolute', top: 0, left: 0, right: 0, zIndex: 230,
      padding: '44px 12px 8px',
      pointerEvents: 'none',
      animation: 'mtnDropToastIn 480ms cubic-bezier(0.22,1,0.36,1)',
    }}>
      <style>{`
        @keyframes mtnDropToastIn {
          from { transform: translateY(-130%); opacity: 0; }
          to   { transform: translateY(0); opacity: 1; }
        }
      `}</style>
      <div
        onClick={(e) => { e.stopPropagation(); onTap && onTap(); }}
        style={{
          position: 'relative', overflow: 'hidden',
          pointerEvents: 'auto', cursor: 'pointer',
          background: `linear-gradient(135deg, ${accent} 0%, ${_darkenColor(accent, 0.35)} 100%)`,
          borderRadius: 16,
          border: '0.5px solid rgba(255,255,255,0.18)',
          boxShadow: `0 18px 42px rgba(0,0,0,0.55)`,
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '12px 14px',
        }}
      >
        {/* Live-drop pulse */}
        <div style={{
          width: 44, height: 44, borderRadius: 10, flexShrink: 0,
          position: 'relative', overflow: 'hidden',
          background: '#000',
        }}>
          <DropImage drop={drop} size="sm" objectPosition="center" />
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 5,
            fontFamily: DS.mono, fontSize: 10.5, fontWeight: 800,
            color: '#fff', letterSpacing: '0.16em', textTransform: 'uppercase',
            padding: '2px 6px', borderRadius: 3,
            background: 'rgba(0,0,0,0.32)',
          }}>
            <span style={{
              width: 6, height: 6, borderRadius: 3, background: '#fff',
              animation: 'mtnPulse 1.4s ease-in-out infinite',
            }} />
            🔥 Limited Drop Unlocked
          </div>
          <div style={{
            fontFamily: DS.sans, fontSize: 13.5, fontWeight: 800,
            color: '#fff', letterSpacing: '-0.005em', marginTop: 4,
            lineHeight: 1.2,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>{drop.title}</div>
          <div style={{
            fontFamily: DS.sans, fontSize: 12, color: 'rgba(255,255,255,0.85)',
            marginTop: 1,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>Only {drop.stockLeft}/{drop.stockTotal} left · ends at final whistle</div>
        </div>

        <button onClick={(e) => { e.stopPropagation(); onClose && onClose(); }} style={{
          width: 26, height: 26, borderRadius: 13, flexShrink: 0,
          background: 'rgba(0,0,0,0.32)',
          border: '0.5px solid rgba(255,255,255,0.18)',
          color: '#fff', cursor: 'pointer', padding: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="10" height="10" viewBox="0 0 10 10"><path d="M1 1l8 8M9 1l-8 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// DROP HERO CARD — featured card used in:
//   * Game Day Watch tab (above multi-angle grid)
//   * Home (after Live Now)
//   * Game Day Rewards tab (in the section)
// Variants: 'full' (big bleed image), 'compact' (smaller for Home)
// ─────────────────────────────────────────────────────────────────────
function DropHeroCard({ drop, onTap, variant = 'full' }) {
  if (!drop) return null;
  const accent = drop.accent || WVU.gold;
  const pctLeft = drop.stockLeft / drop.stockTotal;
  // Heights: full = 220 (Home), compact = 168, small = 132 (Game Day — ~25% smaller)
  const h = variant === 'small' ? 132 : (variant === 'compact' ? 168 : 220);

  return (
    <div data-pulse="true" onClick={onTap} style={{
      position: 'relative', borderRadius: DS.r.lg, overflow: 'hidden',
      cursor: 'pointer',
      border: `0.5px solid ${hexA(accent, 0.45)}`,
      boxShadow: `0 12px 36px rgba(0,0,0,0.45)`,
      '--hint-color': hexA(accent, 0.55),
      '--hint-color-soft': hexA(accent, 0.22),
    }}>
      {/* Product image (full bleed) */}
      <div style={{
        position: 'relative', width: '100%', height: h,
        background: '#000',
      }}>
        <DropImage drop={drop} size="lg" />
        {/* Gradient overlay so text reads */}
        <div style={{
          position: 'absolute', inset: 0,
          background: `
            linear-gradient(180deg, rgba(0,0,0,0.0) 0%, rgba(0,0,0,0.0) 30%, rgba(0,0,0,0.85) 100%),
            linear-gradient(90deg, rgba(0,0,0,0.45) 0%, rgba(0,0,0,0) 50%)
          `,
        }} />

        {/* Top kicker: 🔥 Limited Drop badge */}
        <div style={{
          position: 'absolute', top: 12, left: 12,
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '5px 9px', borderRadius: 6,
          background: `linear-gradient(135deg, ${accent}, ${_darkenColor(accent, 0.35)})`,
          border: '0.5px solid rgba(255,255,255,0.22)',
          fontFamily: DS.mono, fontSize: 10.5, fontWeight: 800,
          color: '#fff', letterSpacing: '0.14em', textTransform: 'uppercase',
          boxShadow: `0 4px 14px ${hexA(accent, 0.5)}`,
        }}>
          <span style={{
            width: 6, height: 6, borderRadius: 3, background: '#fff',
            animation: 'mtnPulse 1.4s ease-in-out infinite',
          }} />
          🔥 Limited Drop
        </div>

        {/* Scarcity counter top-right */}
        <div style={{
          position: 'absolute', top: 12, right: 12,
          padding: '5px 9px', borderRadius: 6,
          background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(10px)',
          border: '0.5px solid rgba(255,255,255,0.14)',
          fontFamily: DS.mono, fontSize: 12, fontWeight: 800,
          color: '#fff', letterSpacing: '0.04em',
          fontVariantNumeric: 'tabular-nums',
        }}>{drop.stockLeft} <span style={{ color: 'rgba(255,255,255,0.6)' }}>/ {drop.stockTotal}</span></div>

        {/* Title + moment + price */}
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0,
          padding: '14px 14px 14px',
        }}>
          <div style={{
            fontFamily: DS.display,
            fontSize: variant === 'small' ? 15 : (variant === 'compact' ? 18 : 22),
            fontWeight: 900,
            color: '#fff', letterSpacing: '-0.02em', lineHeight: 1.1,
            textShadow: '0 2px 8px rgba(0,0,0,0.7)',
          }}>{drop.title}</div>
          {variant !== 'small' && (
            <div style={{
              fontFamily: DS.sans, fontSize: 12.5, fontWeight: 600,
              color: 'rgba(255,255,255,0.92)', marginTop: 4,
              lineHeight: 1.3,
              overflow: 'hidden', display: '-webkit-box',
              WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
              textShadow: '0 1px 4px rgba(0,0,0,0.7)',
            }}>{drop.moment}</div>
          )}

          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: variant === 'small' ? 6 : 10 }}>
            <div style={{
              padding: '6px 11px', borderRadius: 999,
              background: `linear-gradient(135deg, ${accent}, ${_darkenColor(accent, 0.25)})`,
              fontFamily: DS.sans, fontSize: 12, fontWeight: 800,
              color: '#fff', letterSpacing: '0.04em', textTransform: 'uppercase',
              boxShadow: `0 2px 8px ${hexA(accent, 0.5)}`,
            }}>Drop · ${drop.price}</div>
            <div style={{ flex: 1 }} />
            <div style={{
              fontFamily: DS.mono, fontSize: 11, fontWeight: 700,
              color: pctLeft < 0.3 ? '#FFB85C' : 'rgba(255,255,255,0.85)',
              letterSpacing: '0.04em',
            }}>{pctLeft < 0.3 ? 'SELLING FAST ·' : ''} {Math.round(pctLeft * 100)}% left</div>
          </div>
        </div>
      </div>

      {/* Bottom scarcity bar */}
      <div style={{
        height: 4, background: 'rgba(0,0,0,0.5)',
        position: 'relative',
      }}>
        <div style={{
          width: `${pctLeft * 100}%`, height: '100%',
          background: `linear-gradient(90deg, ${accent}, ${_lighten(accent, 0.18)})`,
          boxShadow: 'none',
        }} />
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// DROP DETAIL SCREEN — full-screen drop page
// Props:
//   drop:    drop config
//   onClose: () => void
//   onBuy:   (size) => void  — fires when user taps Add to cart
// ─────────────────────────────────────────────────────────────────────
function DropDetailScreen({ drop, onClose, onBuy }) {
  if (!drop) return null;
  const accent = drop.accent || WVU.gold;
  const pctLeft = drop.stockLeft / drop.stockTotal;
  const [selectedSize, setSelectedSize] = React.useState(drop.defaultSize || (drop.sizes && drop.sizes[0]));
  const [buyState, setBuyState] = React.useState('idle'); // 'idle' | 'adding' | 'added'

  const handleBuy = () => {
    if (buyState !== 'idle') return;
    setBuyState('adding');
    setTimeout(() => {
      setBuyState('added');
      if (onBuy) onBuy(selectedSize);
    }, 600);
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 260,
      background: WVU.ink, color: WVU.cream,
      overflow: 'auto',
      animation: 'mtnDropPageIn 320ms cubic-bezier(0.22, 1, 0.36, 1)',
    }} className="mtn-scrollbar">
      <style>{`
        @keyframes mtnDropPageIn {
          from { transform: translateY(40px); opacity: 0; }
          to   { transform: translateY(0); opacity: 1; }
        }
      `}</style>

      {/* ─── Hero (product image) ─── */}
      <div style={{
        position: 'relative', width: '100%', aspectRatio: '1 / 1',
        background: '#000',
      }}>
        <DropImage drop={drop} size="lg" />
        {/* Top fade so close + chip read */}
        <div style={{
          position: 'absolute', top: 0, left: 0, right: 0, height: 120,
          background: 'linear-gradient(180deg, rgba(0,0,0,0.55), transparent)',
          pointerEvents: 'none',
        }} />

        {/* Close button */}
        <button onClick={onClose} style={{
          position: 'absolute', top: 54, left: 14,
          width: 38, height: 38, borderRadius: 19,
          background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(10px)',
          border: '0.5px solid rgba(255,255,255,0.18)',
          color: '#fff', cursor: 'pointer', padding: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
          </svg>
        </button>

        {/* 🔥 Drop chip */}
        <div style={{
          position: 'absolute', top: 60, right: 14,
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '6px 11px', borderRadius: 8,
          background: `linear-gradient(135deg, ${accent}, ${_darkenColor(accent, 0.35)})`,
          border: '0.5px solid rgba(255,255,255,0.22)',
          fontFamily: DS.mono, fontSize: 11, fontWeight: 800,
          color: '#fff', letterSpacing: '0.14em', textTransform: 'uppercase',
          boxShadow: `0 4px 14px ${hexA(accent, 0.5)}`,
        }}>
          <span style={{
            width: 6, height: 6, borderRadius: 3, background: '#fff',
            animation: 'mtnPulse 1.4s ease-in-out infinite',
          }} />
          🔥 Limited Drop
        </div>
      </div>

      {/* ─── Sticky scarcity strip ─── */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 4,
        padding: '10px 16px',
        background: 'rgba(11,11,15,0.92)',
        backdropFilter: 'blur(14px)',
        borderBottom: `0.5px solid ${WVU.line}`,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{
          fontFamily: DS.mono, fontSize: 11.5, fontWeight: 700,
          color: pctLeft < 0.3 ? '#FFB85C' : WVU.creamDim,
          letterSpacing: '0.14em', textTransform: 'uppercase',
        }}>
          {pctLeft < 0.3 ? 'Selling fast' : 'In stock'}
        </div>
        <div style={{ flex: 1, height: 5, borderRadius: 2.5, background: 'rgba(255,255,255,0.1)', overflow: 'hidden' }}>
          <div style={{
            width: `${pctLeft * 100}%`, height: '100%',
            background: `linear-gradient(90deg, ${accent}, ${_lighten(accent, 0.2)})`,
            boxShadow: 'none',
            transition: 'width 400ms ease',
          }} />
        </div>
        <div style={{
          fontFamily: DS.mono, fontSize: 12, fontWeight: 800,
          color: WVU.cream, letterSpacing: '0.04em',
          fontVariantNumeric: 'tabular-nums',
        }}>{drop.stockLeft}<span style={{ color: WVU.creamDim }}>/{drop.stockTotal}</span></div>
      </div>

      {/* ─── Title + price ─── */}
      <div style={{ padding: '20px 18px 10px' }}>
        <div style={{
          fontFamily: DS.sans, fontSize: 11.5, fontWeight: 700,
          color: accent, letterSpacing: '0.16em', textTransform: 'uppercase',
          marginBottom: 6,
        }}>{drop.sub || 'Limited Edition'}</div>
        <div style={{
          fontFamily: DS.display, fontSize: 28, fontWeight: 900,
          color: WVU.cream, letterSpacing: '-0.025em', lineHeight: 1.05,
        }}>{drop.title}</div>
        <div style={{
          fontFamily: DS.display, fontSize: 22, fontWeight: 800,
          color: WVU.gold, letterSpacing: '-0.015em',
          fontVariantNumeric: 'tabular-nums',
          marginTop: 12,
        }}>${drop.price}</div>
      </div>

      {/* ─── The Moment ─── */}
      <div style={{ padding: '8px 18px 18px' }}>
        <div style={{
          padding: 14, borderRadius: DS.r.md,
          background: `linear-gradient(135deg, ${hexA(accent, 0.14)}, ${WVU.ink2})`,
          border: `0.5px solid ${hexA(accent, 0.35)}`,
        }}>
          <div style={{
            fontFamily: DS.mono, fontSize: 11, fontWeight: 700,
            color: accent, letterSpacing: '0.16em', textTransform: 'uppercase',
            marginBottom: 6,
          }}>The Moment</div>
          <div style={{
            fontFamily: DS.sans, fontSize: 14, fontWeight: 700,
            color: WVU.cream, letterSpacing: '-0.005em', lineHeight: 1.35,
          }}>{drop.moment}</div>
          <div style={{
            fontFamily: DS.sans, fontSize: 12.5, color: WVU.creamDim,
            marginTop: 8, lineHeight: 1.45,
          }}>{drop.story}</div>
        </div>
      </div>

      {/* ─── Size selector ─── */}
      <div style={{ padding: '8px 18px 16px' }}>
        <div style={{
          fontFamily: DS.sans, fontSize: 12, fontWeight: 700,
          color: WVU.gold, letterSpacing: '0.11em', textTransform: 'uppercase',
          marginBottom: 10,
        }}>Size · {drop.sizes && drop.sizes.length > 1 ? 'pick yours' : 'one size'}</div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {(drop.sizes || ['L']).map(sz => {
            const on = sz === selectedSize;
            return (
              <button key={sz} onClick={() => setSelectedSize(sz)} style={{
                minWidth: 56, padding: '10px 14px',
                borderRadius: 10,
                background: on ? `linear-gradient(135deg, ${WVU.gold}, ${WVU.goldDim})` : 'rgba(245,236,217,0.06)',
                color: on ? WVU.blueDim : WVU.cream,
                border: on ? 'none' : `0.5px solid ${WVU.lineBold}`,
                fontFamily: DS.sans, fontSize: 13, fontWeight: 800,
                letterSpacing: '-0.005em',
                cursor: 'pointer',
                boxShadow: on ? `0 4px 12px ${hexA(WVU.gold, 0.45)}` : 'none',
                transition: 'all 140ms ease',
              }}>{sz}</button>
            );
          })}
        </div>
      </div>

      {/* ─── Shipping + reward note ─── */}
      <div style={{ padding: '0 18px 16px' }}>
        <div style={{
          padding: '12px 14px', borderRadius: DS.r.md,
          background: 'rgba(245,236,217,0.04)',
          border: `0.5px solid ${WVU.line}`,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <div style={{
            width: 30, height: 30, borderRadius: 15,
            background: `linear-gradient(135deg, ${WVU.gold}, ${WVU.goldDim})`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0, color: WVU.blueDim,
          }}>
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d="M8 1.5l2 4 4.5.4-3.4 3 1 4.3L8 11l-4.1 2.2 1-4.3-3.4-3 4.5-.4z" fill="currentColor"/>
            </svg>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: DS.sans, fontSize: 12.5, fontWeight: 700,
              color: WVU.cream, letterSpacing: '-0.005em',
            }}>Earn 50 pts on this drop</div>
            <div style={{
              fontFamily: DS.sans, fontSize: 12, color: WVU.creamDim,
              marginTop: 2,
            }}>Ships in 7 days · free for season-ticket members</div>
          </div>
        </div>
      </div>

      {/* ─── Sticky buy CTA ─── */}
      <div style={{
        position: 'sticky', bottom: 0,
        padding: '14px 16px 28px',
        background: `linear-gradient(180deg, transparent, ${WVU.ink} 22%)`,
      }}>
        <button onClick={handleBuy} disabled={buyState !== 'idle'} style={{
          width: '100%', padding: '16px 20px',
          background: buyState === 'added'
            ? `linear-gradient(135deg, ${hexA(accent, 0.3)}, ${hexA(accent, 0.15)})`
            : `linear-gradient(135deg, ${accent}, ${_darkenColor(accent, 0.25)})`,
          color: '#fff', border: 'none',
          borderRadius: 14,
          fontFamily: DS.sans, fontSize: 16, fontWeight: 800,
          letterSpacing: '0.01em',
          cursor: buyState === 'idle' ? 'pointer' : 'default',
          boxShadow: `0 8px 28px ${hexA(accent, 0.5)}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          transition: 'all 200ms ease',
        }}>
          {buyState === 'idle' && (
            <>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M3 5h10l-1 8H4L3 5z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" fill="none"/>
                <path d="M6 5V4a2 2 0 014 0v1" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" fill="none"/>
              </svg>
              Add to cart · ${drop.price}
            </>
          )}
          {buyState === 'adding' && 'Adding…'}
          {buyState === 'added' && (
            <>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M3 8.5l3.5 3.5L13 4" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              Added · checking out
            </>
          )}
        </button>
      </div>
    </div>
  );
}

// hex helpers
function _darkenColor(hex, t) {
  const h = (hex || '#000').replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16);
  const r = ((n >> 16) & 255) * (1 - t);
  const g = ((n >>  8) & 255) * (1 - t);
  const b = ((n)       & 255) * (1 - t);
  return '#' + [r, g, b].map(v => Math.round(v).toString(16).padStart(2, '0')).join('');
}
function _lighten(hex, t) {
  const h = (hex || '#000').replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16);
  const r = ((n >> 16) & 255) + (255 - ((n >> 16) & 255)) * t;
  const g = ((n >>  8) & 255) + (255 - ((n >>  8) & 255)) * t;
  const b = ((n)       & 255) + (255 - ((n)       & 255)) * t;
  return '#' + [r, g, b].map(v => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('');
}

Object.assign(window, { DropToast, DropHeroCard, DropDetailScreen, DropPlaceholder, DropImage });
