// ZION Hero — full-bleed fireball-content style with inferno glow
// `media` controls what fills the strip beneath the headline:
//   'photos' (default) — 3 image-slot photos that bleed into each other
//   'video'            — a single muted, looping background clip
function Hero({ onShop, media = 'photos', videoSrc = '', poster = '' }) {
  return (
    <section style={{
      color: '#fff', position: 'relative', overflow: 'hidden',
      padding: '32px 0 0', background: '#0A0A0A',
    }}>
      {/* Top ember glow — mirrors the StayLit footer wash, anchored at the top edge */}
      <div aria-hidden style={{
        position: 'absolute', top: 0, left: 0, right: 0,
        height: 'clamp(280px, 32vw, 460px)',
        pointerEvents: 'none', zIndex: 0,
        background:
          'radial-gradient(ellipse 90% 70% at 50% 0%, #3A0F08 0%, rgba(58,15,8,0.55) 35%, rgba(26,5,6,0.25) 65%, rgba(10,10,10,0) 100%)',
      }} />

      {/* Film grain */}
      <div aria-hidden style={{
        position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 1,
        backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='300' height='300'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='1.4' numOctaves='2' seed='5'/><feColorMatrix values='0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.10 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>")`,
        mixBlendMode: 'overlay',
      }} />

      {/* Top LEFT social rail */}
      <div style={{
        position: 'absolute', top: 22, left: 32, zIndex: 5,
        display: 'flex', gap: 10, alignItems: 'center',
      }}>
        <SocialDot label="IG" href="https://www.instagram.com/thefireballguyy/" />
        <SocialDot label="TT" href="https://www.tiktok.com/@thefireballguy" />
        <SocialDot label="YT" href="https://www.youtube.com/@thefireballguyy" />
      </div>

      {/* Top right STAY LIT lockup */}
      <div style={{
        position: 'absolute', top: 18, right: 32, zIndex: 5,
        display: 'flex', alignItems: 'center', gap: 4,
      }}>
        <img src="../../assets/logo-z-staylit.png" alt="ZION Stay Lit" style={{ height: 56 }} />
      </div>

      {/* Full-width media strip with the headline + CTA grouped low on the video */}
      <div style={{ position: 'relative', marginTop: 8, width: '100%' }}>
        <div style={{
          position: 'relative', width: '100%',
          height: 'clamp(440px, 56vw, 720px)',
          WebkitMaskImage: 'linear-gradient(180deg, transparent 0%, rgba(0,0,0,0.2) 12%, #000 34%, #000 90%, transparent 100%)',
          maskImage: 'linear-gradient(180deg, transparent 0%, rgba(0,0,0,0.2) 12%, #000 34%, #000 90%, transparent 100%)',
          overflow: 'hidden',
        }}>
          {media === 'video' ? (
            <HeroVideo videoSrc={videoSrc} poster={poster} />
          ) : (
            <div style={{
              display: 'flex', width: '100%', height: '100%',
              alignItems: 'flex-end', gap: 0,
            }}>
              <HeroPhoto src="assets/hero-guy.png"  alt="Levi" />
              <HeroPhoto src="assets/hero-ball.png" alt="Flaming ball" overlapLeft />
              <HeroPhoto src="assets/hero-girl.png" alt="Performer" overlapLeft />
            </div>
          )}
          {/* legibility scrim — darkens behind the centered text */}
          <div aria-hidden style={{
            position: 'absolute', inset: 0, pointerEvents: 'none',
            background: 'radial-gradient(ellipse 95% 70% at 50% 50%, rgba(10,10,10,0.6) 0%, rgba(10,10,10,0.25) 45%, rgba(10,10,10,0) 75%)',
          }} />
        </div>

        {/* Headline + CTA — grouped tightly, centered on the video */}
        <div style={{
          position: 'absolute', left: 0, right: 0, top: '50%', transform: 'translateY(-50%)',
          zIndex: 4, padding: '0 24px',
          display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
        }}>
          <div style={{
            fontFamily: 'Poppins, sans-serif', fontWeight: 500,
            fontSize: 'clamp(16px, 2vw, 30px)', color: '#fff',
            letterSpacing: '-0.005em', marginBottom: 6,
            textShadow: '0 2px 20px rgba(0,0,0,0.65)',
          }}>
            The world's first <span style={{ color: '#F7591F', textTransform: 'uppercase', fontWeight: 700 }}>FIRE</span>
          </div>
          <h1 style={{
            fontFamily: 'Poppins, sans-serif', fontWeight: 900, textTransform: 'uppercase',
            fontSize: 'clamp(38px, 6.6vw, 100px)',
            lineHeight: 0.92, letterSpacing: '-0.025em',
            margin: '0 0 22px', color: '#fff',
            textShadow: '0 12px 48px rgba(0,0,0,0.6)',
          }}>
            FOOTBALL BRAND<span style={{ color: '#F7591F' }}>.</span>
          </h1>
          <PillButton onClick={onShop}>PLACE YOUR ORDER TODAY!</PillButton>
        </div>
      </div>
    </section>
  );
}

function SocialDot({ label, href }) {
  const [hover, setHover] = React.useState(false);
  const Tag = href ? 'a' : 'div';
  const linkProps = href ? { href, target: '_blank', rel: 'noopener noreferrer', 'aria-label': label } : {};
  return (
    <Tag
      {...linkProps}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        width: 28, height: 28, borderRadius: '50%',
        background: hover ? 'rgba(247,89,31,0.18)' : 'rgba(255,255,255,0.1)',
        border: `1px solid ${hover ? '#F7591F' : 'rgba(255,255,255,0.25)'}`,
        boxShadow: hover ? '0 0 16px rgba(247,89,31,0.55), 0 0 32px rgba(247,89,31,0.25)' : 'none',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'Poppins', fontSize: 9, fontWeight: 800, letterSpacing: '0.1em',
        color: '#fff', cursor: 'pointer', textDecoration: 'none',
        transition: 'background 160ms, border-color 160ms, box-shadow 200ms',
      }}>{label}</Tag>
  );
}

// Hero photo — pre-filled real image with horizontal edge-fade so neighbors blend.
function HeroPhoto({ src, alt, overlapLeft }) {
  const overlap = overlapLeft ? { marginLeft: '-10%' } : {};
  const m = 'linear-gradient(90deg, transparent 0%, #000 14%, #000 86%, transparent 100%)';
  return (
    <div style={{
      flex: 1, height: '100%', position: 'relative', overflow: 'hidden',
      WebkitMaskImage: m, maskImage: m,
      ...overlap,
    }}>
      <img src={src} alt={alt} style={{
        width: '100%', height: '100%', objectFit: 'cover', display: 'block',
      }} />
    </div>
  );
}

// HeroVideo — drop-zone / file-picker for the hero video.
// You can either:
//   - pass `videoSrc` prop directly (e.g. 'assets/hero.mp4'), OR
//   - drag a .mp4 onto the slot / click to pick a file (persists in localStorage)
function HeroVideo({ videoSrc, poster }) {
  const STORAGE_KEY = 'zion.heroVideo';
  const [localSrc, setLocalSrc]   = React.useState('');
  const [localName, setLocalName] = React.useState('');
  const [dragging, setDragging]   = React.useState(false);
  const [error, setError]         = React.useState('');
  const inputRef = React.useRef(null);

  // Restore previously-picked video from localStorage on mount
  React.useEffect(() => {
    try {
      const cached = localStorage.getItem(STORAGE_KEY);
      if (cached) {
        const { dataUrl, name } = JSON.parse(cached);
        if (dataUrl) { setLocalSrc(dataUrl); setLocalName(name || 'video'); }
      }
    } catch {}
  }, []);

  const handleFile = (file) => {
    setError('');
    if (!file) return;
    if (!file.type.startsWith('video/')) {
      setError('Not a video file. Try .mp4, .webm, or .mov.');
      return;
    }
    // 12MB cap on persistence — bigger files still play, just not persisted
    const cap = 12 * 1024 * 1024;
    const reader = new FileReader();
    reader.onload = e => {
      const dataUrl = e.target.result;
      setLocalSrc(dataUrl);
      setLocalName(file.name);
      if (file.size <= cap) {
        try { localStorage.setItem(STORAGE_KEY, JSON.stringify({ dataUrl, name: file.name })); }
        catch (err) { /* quota exceeded — playback still works this session */ }
      }
    };
    reader.readAsDataURL(file);
  };

  const handleClear = (e) => {
    e.stopPropagation();
    setLocalSrc(''); setLocalName(''); setError('');
    try { localStorage.removeItem(STORAGE_KEY); } catch {}
  };

  const effectiveSrc = videoSrc || localSrc;

  // Enforce mute on the DOM node — React's JSX `muted` attribute is known to
  // sometimes fail to apply, leading to audio leaking on autoplay. Belt + braces.
  const playerRef = React.useRef(null);
  React.useEffect(() => {
    const v = playerRef.current;
    if (!v) return;
    v.muted = true;
    v.defaultMuted = true;
    v.volume = 0;
  }, [effectiveSrc]);

  // === Filled state ============================================
  if (effectiveSrc) {
    return (
      <div style={{ position: 'relative', width: '100%', height: '100%' }}>
        <video
          ref={playerRef}
          src={effectiveSrc}
          poster={poster}
          autoPlay muted={true} loop playsInline
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
        />
        {/* Only show "change/clear" UI when using the user-picked one, not a hard-coded src */}
        {!videoSrc && (
          <div style={{
            position: 'absolute', top: 16, left: 16, zIndex: 5,
            display: 'flex', gap: 8, alignItems: 'center',
            background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(8px)',
            border: '1px solid rgba(255,255,255,0.15)',
            padding: '6px 10px', borderRadius: 999,
          }}>
            <span style={{
              fontFamily: 'JetBrains Mono', fontSize: 11, color: 'rgba(255,255,255,0.85)',
              maxWidth: 220, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{localName}</span>
            <button onClick={() => inputRef.current?.click()} style={miniBtn}>Replace</button>
            <button onClick={handleClear} style={miniBtn}>Remove</button>
            <input
              ref={inputRef} type="file" accept="video/*" hidden
              onChange={e => handleFile(e.target.files?.[0])}
            />
          </div>
        )}
      </div>
    );
  }

  // === Empty / drop-zone state =================================
  return (
    <div
      onClick={() => inputRef.current?.click()}
      onDragOver={e => { e.preventDefault(); setDragging(true); }}
      onDragLeave={() => setDragging(false)}
      onDrop={e => {
        e.preventDefault(); setDragging(false);
        handleFile(e.dataTransfer.files?.[0]);
      }}
      role="button" tabIndex={0}
      style={{
        width: '100%', height: '100%',
        background: dragging ? '#1A1410' : '#141414',
        border: dragging ? '2px dashed #F7591F' : '2px dashed rgba(255,255,255,0.18)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexDirection: 'column', gap: 12, cursor: 'pointer',
        transition: 'background 160ms, border-color 160ms',
        boxSizing: 'border-box',
      }}
    >
      {/* Play-glyph emblem */}
      <div style={{
        width: 72, height: 72, borderRadius: '50%',
        background: dragging ? '#F7591F' : 'rgba(247,89,31,0.18)',
        border: '1.5px solid #F7591F',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: dragging ? '0 0 28px rgba(247,89,31,0.55)' : 'none',
        transition: 'background 160ms, box-shadow 160ms',
      }}>
        <svg width="22" height="26" viewBox="0 0 22 26" fill="#fff" aria-hidden="true">
          <path d="M0 0 L22 13 L0 26 Z" />
        </svg>
      </div>
      <div style={{
        fontFamily: 'Poppins', fontWeight: 800, fontSize: 13, letterSpacing: '0.18em',
        textTransform: 'uppercase', color: dragging ? '#F7591F' : '#fff',
      }}>
        {dragging ? 'Drop to ignite' : 'Add hero video'}
      </div>
      <div style={{
        fontFamily: 'Poppins', fontSize: 12, color: 'rgba(255,255,255,0.55)',
        textAlign: 'center', lineHeight: 1.5, maxWidth: 440,
      }}>
        Drag a .mp4 here, or <span style={{ color: '#F7591F', textDecoration: 'underline' }}>browse</span>.<br />
        Plays muted + looped. Stored in your browser.
      </div>
      {error && (
        <div style={{
          fontFamily: 'JetBrains Mono', fontSize: 11, color: '#FF7A66', marginTop: 4,
        }}>{error}</div>
      )}
      <input
        ref={inputRef} type="file" accept="video/*" hidden
        onChange={e => handleFile(e.target.files?.[0])}
      />
    </div>
  );
}

const miniBtn = {
  background: 'rgba(255,255,255,0.1)', color: '#fff',
  border: '1px solid rgba(255,255,255,0.2)',
  fontFamily: 'Poppins', fontWeight: 700, fontSize: 10,
  letterSpacing: '0.1em', textTransform: 'uppercase',
  padding: '4px 10px', borderRadius: 999, cursor: 'pointer',
};

// FireSlot: dark image-slot placeholder. `fade` controls the mask used.
//   'bottom'        — opaque top → transparent bottom (dissolves into page below)
//   'topAndSides'   — opaque bottom-center, fades at top + left + right (blends into neighbors)
//   'none'          — no mask (use a parent mask for full-strip fades)
function FireSlot({ id, cols, flex, aspect, placeholder, fade = 'bottom', overlapLeft, fullHeight }) {
  const colStyle = cols ? { gridColumn: `span ${cols}` } : {};
  const flexStyle = flex ? { flex } : {};
  const overlap = overlapLeft ? { marginLeft: '-10%' } : {};
  const sizing = fullHeight ? { height: '100%' } : (aspect ? { aspectRatio: aspect } : { aspectRatio: '4/3' });

  let maskStyle = {};
  if (fade === 'bottom') {
    const m = 'linear-gradient(180deg, #000 0%, #000 55%, transparent 100%)';
    maskStyle = { WebkitMaskImage: m, maskImage: m };
  } else if (fade === 'topAndSides') {
    const m = 'radial-gradient(ellipse 110% 130% at 50% 100%, #000 45%, transparent 90%)';
    maskStyle = { WebkitMaskImage: m, maskImage: m };
  } else if (fade === 'sides') {
    // Horizontal soft edges so neighbors bleed into each other
    const m = 'linear-gradient(90deg, transparent 0%, #000 14%, #000 86%, transparent 100%)';
    maskStyle = { WebkitMaskImage: m, maskImage: m };
  }

  return (
    <image-slot
      data-id={id}
      data-placeholder={placeholder}
      data-shape="rect"
      style={{
        ...colStyle, ...flexStyle, ...overlap, ...sizing,
        display: 'block',
        background: '#141414',
        '--is-bg': '#141414',
        '--is-border': 'rgba(255,255,255,0.08)',
        '--is-fg': 'rgba(255,255,255,0.45)',
        ...maskStyle,
      }}
    />
  );
}

function FireButton({ children, onClick, hard }) {
  const [press, setPress] = React.useState(false);
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={onClick}
      onMouseEnter={()=>setHover(true)} onMouseLeave={()=>{setHover(false); setPress(false);}}
      onMouseDown={()=>setPress(true)} onMouseUp={()=>setPress(false)}
      style={{
        fontFamily: 'Poppins', fontWeight: 800, fontSize: 13, letterSpacing: '0.14em',
        textTransform: 'uppercase',
        background: hover ? '#C8420E' : '#F7591F', color: '#fff',
        border: 'none', padding: '16px 26px', cursor: 'pointer',
        boxShadow: hard ? (press ? '0 0 0 0 rgba(0,0,0,0.0)' : '4px 4px 0 0 rgba(0,0,0,0.85)') : 'none',
        transform: press ? 'translate(2px,2px) scale(0.99)' : 'translate(0,0)',
        transition: 'transform 120ms cubic-bezier(0.7,0,0.2,1), background 140ms',
      }}>{children}</button>
  );
}

function GhostButton({ children, onClick, dark }) {
  const [hover, setHover] = React.useState(false);
  const fg = dark ? '#fff' : '#000';
  return (
    <button onClick={onClick}
      onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
      style={{
        fontFamily: 'Poppins', fontWeight: 800, fontSize: 13, letterSpacing: '0.14em',
        textTransform: 'uppercase',
        background: hover ? fg : 'transparent', color: hover ? (dark ? '#000' : '#fff') : fg,
        border: `2px solid ${fg}`, padding: '14px 24px', cursor: 'pointer',
        transition: 'all 140ms',
      }}>{children}</button>
  );
}

window.Hero = Hero;
window.FireSlot = FireSlot;
window.FireButton = FireButton;
window.GhostButton = GhostButton;

// PillButton — long, rounded primary CTA used in the hero
function PillButton({ children, onClick }) {
  const [hover, setHover] = React.useState(false);
  const [press, setPress] = React.useState(false);
  return (
    <button onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setPress(false); }}
      onMouseDown={() => setPress(true)}
      onMouseUp={() => setPress(false)}
      style={{
        fontFamily: 'Poppins, sans-serif', fontWeight: 800,
        fontSize: 15, letterSpacing: '0.04em',
        textTransform: 'uppercase',
        background: hover ? '#C8420E' : '#F7591F', color: '#fff',
        border: 'none', borderRadius: 999,
        padding: '20px 56px', cursor: 'pointer',
        boxShadow: '0 8px 28px rgba(247,89,31,0.35)',
        transform: press ? 'scale(0.985)' : 'scale(1)',
        transition: 'transform 120ms cubic-bezier(0.7,0,0.2,1), background 140ms',
      }}>{children}</button>
  );
}

window.PillButton = PillButton;
