/* HERO v2 — palette-aware, syncs with PageSections via window.OW_PALETTE_KEY */

const HERO_PALETTES = {
  midnight:      { dark: '#0c1118', ink: '#0f1620', cream: '#f7f9fb', accent: '#d98a5c', glowRgb: '217,138,92' },
  midnightWarm:  { dark: '#0c1118', ink: '#0f1620', cream: '#faf5eb', accent: '#d98a5c', glowRgb: '217,138,92' },
  midnightLinen: { dark: '#0c1118', ink: '#0f1620', cream: '#f5efe2', accent: '#d98a5c', glowRgb: '217,138,92' },
  midnightSmoky: { dark: '#0c1118', ink: '#0f1620', cream: '#f1ebdd', accent: '#d98a5c', glowRgb: '217,138,92' },
  originalCream: { dark: '#1a120c', ink: '#2b1f17', cream: '#faf5e9', accent: '#e08a4a', glowRgb: '224,138,74' },
  olive:    { dark: '#1c2419', ink: '#1f2a1c', cream: '#f7f4ea', accent: '#c46b3f', glowRgb: '196,107,63' },
  plum:     { dark: '#241828', ink: '#2a1c2c', cream: '#faf6ee', accent: '#b8895a', glowRgb: '184,137,90' },
  forest:   { dark: '#0f1d18', ink: '#1a2a23', cream: '#f4eedd', accent: '#c8694a', glowRgb: '200,105,74' },
  slate:    { dark: '#1a1410', ink: '#1d1612', cream: '#f5ede1', accent: '#8b4a2b', glowRgb: '139,74,43' },
};

const FONT_FIXED = { display: '"Instrument Serif", serif', body: '"Inter", system-ui, sans-serif', h1Weight: 400, italic: true };

function HeroVideo({ videoSrc = 'assets/hero-1.mp4', altSrc = 'assets/hero-2.mp4' }) {
  const [activeIdx, setActiveIdx] = React.useState(0);
  const [blobs, setBlobs] = React.useState({});
  const [paletteKey, setPaletteKey] = React.useState(window.OW_PALETTE_KEY || 'slate');
  const videoRef = React.useRef(null);
  const sources = [videoSrc, altSrc];
  const currentRaw = sources[activeIdx];
  const src = blobs[currentRaw] || currentRaw;
  const f = FONT_FIXED;
  const p = HERO_PALETTES[paletteKey] || HERO_PALETTES.slate;
  const { dark, cream, accent } = p;

  // hex → rgb tuple for overlay rgba()
  const hexToRgb = (h) => {
    const x = h.replace('#','');
    const n = parseInt(x.length === 3 ? x.split('').map(c=>c+c).join('') : x, 16);
    return [(n>>16)&255, (n>>8)&255, n&255].join(',');
  };
  const darkRgb = hexToRgb(dark);

  React.useEffect(() => {
    const handler = (e) => { if (e?.detail?.key && HERO_PALETTES[e.detail.key]) setPaletteKey(e.detail.key); };
    window.addEventListener('ow-palette-change', handler);
    return () => window.removeEventListener('ow-palette-change', handler);
  }, []);

  React.useEffect(() => {
    let cancelled = false;
    sources.forEach(async (url) => {
      if (blobs[url]) return;
      try {
        const r = await fetch(url);
        const b = await r.blob();
        if (cancelled) return;
        setBlobs(prev => ({ ...prev, [url]: URL.createObjectURL(b) }));
      } catch (e) { console.warn('video load failed', url, e); }
    });
    return () => { cancelled = true; };
  }, []);

  React.useEffect(() => {
    const v = videoRef.current;
    if (v) { v.muted = true; v.volume = 0; v.play().catch(() => {}); }
  }, [src]);

  return (
    <div style={{
      position: 'relative', width: '100%', minHeight: '100vh',
      overflow: 'hidden', background: dark,
      fontFamily: f.body, color: cream,
      transition: 'background .4s, color .4s',
    }}>
      <video
        ref={videoRef}
        key={src}
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', zIndex: 0 }}
        src={src} autoPlay muted defaultMuted loop playsInline
      />

      {/* OVERLAYS — driven by palette dark color */}
      <div style={{ position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none', background: `radial-gradient(ellipse at center, transparent 35%, rgba(${darkRgb},0.55) 100%)` }} />
      <div style={{ position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none', background: `linear-gradient(90deg, rgba(${darkRgb},0.85) 0%, rgba(${darkRgb},0.55) 35%, rgba(${darkRgb},0.05) 60%, transparent 100%)` }} />
      <div style={{ position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none', background: `linear-gradient(180deg, transparent 50%, rgba(${darkRgb},0.4) 80%, rgba(${darkRgb},0.85) 100%)` }} />
      <div style={{ position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none', background: `linear-gradient(180deg, rgba(${darkRgb},0.5) 0%, transparent 18%)` }} />

      {/* NAV */}
      <div style={{ position: 'relative', zIndex: 5, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '24px 56px' }}>
        <div style={{ fontFamily: f.display, fontSize: 22, fontWeight: f.h1Weight, letterSpacing: -0.3, color: cream, display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: accent }} />
          Ożywione Wspomnienia
        </div>
        <div style={{ display: 'flex', gap: 28, alignItems: 'center' }}>
          {[['Jak to działa','#jak-to-dziala'],['Pakiety','#pakiety'],['Opinie','#opinie'],['FAQ','#faq']].map(([l,id]) => (
            <a key={l} href={id} style={{ fontSize: 14, color: `rgba(255,255,255,0.75)`, fontWeight: 500, cursor: 'pointer', textDecoration: 'none' }}>{l}</a>
          ))}
          <span onClick={() => window.OW_ORDER && window.OW_ORDER()} style={{ fontSize: 13, fontWeight: 600, background: cream, color: dark, padding: '11px 22px', borderRadius: 6, cursor: 'pointer' }}>Zamów film</span>
        </div>
      </div>

      {/* CONTENT */}
      <div style={{ position: 'relative', zIndex: 5, padding: '0 56px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, alignItems: 'flex-start', minHeight: 'calc(100vh - 240px)', paddingTop: 60 }}>
        <div style={{ maxWidth: 580 }}>
          <h1 style={{
            fontFamily: f.display,
            fontSize: 'clamp(54px, 6.2vw, 92px)',
            lineHeight: 1.04, fontWeight: f.h1Weight,
            letterSpacing: f.italic ? -1.5 : -2.5,
            marginBottom: 36, color: cream,
            textShadow: '0 2px 6px rgba(0,0,0,0.55), 0 8px 28px rgba(0,0,0,0.45), 0 18px 60px rgba(0,0,0,0.35)',
          }}>
            Stare zdjęcia.<br />
            <span style={{ fontStyle: f.italic ? 'italic' : 'normal', color: accent, fontWeight: f.italic ? f.h1Weight : 600, textShadow: `0 2px 6px rgba(0,0,0,0.6), 0 10px 30px rgba(${hexToRgb(accent)},0.45), 0 0 60px rgba(${hexToRgb(accent)},0.35)` }}>
              Nowe wzruszenie.
            </span>
          </h1>
          <p style={{ fontSize: 18, color: 'rgba(255,255,255,0.85)', lineHeight: 1.6, maxWidth: 480, marginBottom: 32, textShadow: '0 1px 12px rgba(0,0,0,0.4)' }}>
            Są historie, których nie da się powtórzyć. My zamieniamy je w film, który zostaje na lata.
          </p>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 32, flexWrap: 'wrap' }}>
            <button onClick={() => window.OW_ORDER && window.OW_ORDER()} style={{ background: cream, color: dark, border: 'none', padding: '17px 32px', borderRadius: 8, fontSize: 15, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', boxShadow: '0 12px 32px rgba(0,0,0,0.3)' }}>
              Zamów film →
            </button>
            <button style={{ background: 'rgba(255,255,255,0.1)', color: cream, border: '1px solid rgba(255,255,255,0.3)', backdropFilter: 'blur(12px)', padding: '17px 26px', borderRadius: 8, fontSize: 15, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 10 }}>
              ▷ Zobacz przykłady
            </button>
          </div>
          <div style={{ display: 'flex', gap: 22, alignItems: 'center', fontSize: 13, color: 'rgba(255,255,255,0.7)', flexWrap: 'wrap' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ color: accent, fontWeight: 700 }}>✓</span> 72h realizacji</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ color: accent, fontWeight: 700 }}>✓</span> Muzyka w cenie</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ color: accent, fontWeight: 700 }}>✓</span> Od 179 zł</span>
          </div>
        </div>
        <div />
      </div>

      {/* TRUST */}
      <div style={{ position: 'relative', zIndex: 5, padding: '24px 56px 28px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16, fontSize: 13, color: 'rgba(255,255,255,0.85)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ color: accent, fontSize: 16 }}>★★★★★</span>
          <span><strong style={{ color: cream }}>4.9/5</strong> · 100% zadowolonych</span>
        </div>
        <div>🔒 Zdjęcia chronione · RODO</div>
        <div>BLIK · Karta · Przelewy24</div>
        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          {sources.map((s, i) => (
            <button key={s} onClick={() => setActiveIdx(i)} style={{
              width: activeIdx === i ? 28 : 8, height: 8, borderRadius: 999,
              border: 'none', cursor: 'pointer',
              background: activeIdx === i ? accent : 'rgba(255,255,255,0.35)',
              transition: 'width .25s', padding: 0,
            }} aria-label={`Film ${i + 1}`} />
          ))}
        </div>
      </div>

    </div>
  );
}

window.HeroVideo = HeroVideo;
