/* global React */

// ========== CAROUSEL ==========
const { useState: useStateC, useEffect: useEffectC } = React;

const CAROUSEL_SLIDES = [
  {
    tag: 'THE PRIVACY SERIES',
    title: "Nobody's",
    italic: 'watching',
    rest: 'your screen.',
    desc: '160° blackout. 9H tempered. Zero clarity loss head-on.',
    cta: 'Shop Privacy — ₹2,098',
    href: '/category/screens',
    img: 'assets/privacy-iphone-transparent.png',
    transparent: true,
    bg: 'var(--ink)',
    accent: 'var(--gold)',
    fg: 'var(--cream)'
  },
  {
    tag: 'DROP-TESTED',
    title: 'Built to',
    italic: 'outlast',
    rest: 'your phone.',
    desc: 'Certified 3m drops on tile. Glass takes the hit. You keep scrolling.',
    cta: 'Explore Arc Edge — ₹1,049',
    href: '/category/screens',
    img: 'assets/ar-screen-transparent.png',
    transparent: true,
    bg: 'var(--violet)',
    accent: 'var(--gold)',
    fg: 'var(--cream)'
  },
];

function Carousel() {
  const [i, setI] = useStateC(0);
  useEffectC(() => {
    const t = setInterval(() => setI(x => (x + 1) % CAROUSEL_SLIDES.length), 6000);
    return () => clearInterval(t);
  }, []);
  const s = CAROUSEL_SLIDES[i];
  // Contrast helpers — light accents take ink text; dark backdrops get a cream disc behind product photo
  const LIGHT_ACCENTS = ['var(--gold)', 'var(--cream)', 'var(--cream-2)'];
  const DARK_BGS = ['var(--ink)', 'var(--ink-2)', 'var(--violet)', 'var(--violet-2)'];
  const onAccent = LIGHT_ACCENTS.includes(s.accent) ? 'var(--ink)' : 'var(--cream)';
  const isDarkBg = DARK_BGS.includes(s.bg);
  return (
    <section style={{ padding: '40px 24px' }}>
      <div style={{
        position: 'relative',
        borderRadius: 4,
        background: s.bg,
        color: s.fg,
        overflow: 'hidden',
        minHeight: 560,
        transition: 'background 0.6s ease, color 0.6s ease'
      }}>
        <img src="assets/lion-mark.png" style={{
          position: 'absolute', right: -60, top: -60,
          width: 360, height: 360, opacity: 0.08,
          filter: s.fg === 'var(--cream)' ? 'brightness(3)' : 'none'
        }}/>
        <div style={{ maxWidth: 1400, margin: '0 auto', padding: '60px 40px', position: 'relative', display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 40, alignItems: 'center' }}>
          <div key={i} style={{ animation: 'fadeSlide 0.6s ease both' }}>
            <span className="mono" style={{ color: s.accent }}>◆ {s.tag}</span>
            <h2 className="display" style={{ fontSize: 'clamp(56px, 8vw, 120px)', margin: '16px 0 24px', lineHeight: 0.95, textWrap: 'balance' }}>
              {s.title}<br/>
              <span className="italic-accent" style={{ color: s.accent }}>{s.italic}</span><br/>
              {s.rest}
            </h2>
            <p style={{ fontSize: 18, maxWidth: 440, opacity: 0.8, lineHeight: 1.5 }}>{s.desc}</p>
            <div style={{ display: 'flex', gap: 12, marginTop: 32 }}>
              <a href={s.href || '/category/all'} className="btn lg" style={{ background: s.accent, color: onAccent, borderColor: s.accent, textDecoration: 'none' }}>
                {s.cta}
              </a>
            </div>
          </div>
          <div style={{ position: 'relative', height: 460, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div key={'img'+i} style={{
              animation: 'fadeSlide 0.7s ease both',
              width: 'min(420px, 90%)', aspectRatio: '1/1',
              borderRadius: '50%',
              background: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 30px 60px rgba(0,0,0,0.35)'
            }}>
              <img src={s.img} style={{
                maxWidth: s.transparent ? '96%' : '84%',
                maxHeight: s.transparent ? '96%' : '84%',
                objectFit: 'contain',
                mixBlendMode: s.transparent ? 'normal' : 'multiply'
              }}/>
            </div>
          </div>
        </div>
        {/* Controls */}
        <div style={{ position: 'absolute', bottom: 28, left: 40, right: 40, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', gap: 10 }}>
            {CAROUSEL_SLIDES.map((_, k) => (
              <button key={k} onClick={() => setI(k)} style={{
                width: k === i ? 40 : 12, height: 4, borderRadius: 2,
                background: k === i ? s.accent : (isDarkBg ? 'rgba(255,255,255,0.3)' : 'rgba(26,58,107,0.25)'),
                border: 'none', cursor: 'pointer', transition: 'width 0.3s ease'
              }}/>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={() => setI((i - 1 + CAROUSEL_SLIDES.length) % CAROUSEL_SLIDES.length)} style={{
              width: 44, height: 44, borderRadius: 2, border: `1px solid ${s.fg === 'var(--cream)' ? 'rgba(255,255,255,0.3)' : 'var(--line)'}`,
              background: 'transparent', color: s.fg, cursor: 'pointer', fontFamily: 'Space Grotesk'
            }}>←</button>
            <button onClick={() => setI((i + 1) % CAROUSEL_SLIDES.length)} style={{
              width: 44, height: 44, borderRadius: 2, border: `1px solid ${s.fg === 'var(--cream)' ? 'rgba(255,255,255,0.3)' : 'var(--line)'}`,
              background: s.accent, color: onAccent, cursor: 'pointer', fontFamily: 'Space Grotesk'
            }}>→</button>
          </div>
        </div>
        <style>{`@keyframes fadeSlide { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }`}</style>
      </div>
    </section>
  );
}

// ========== MID BANNER (purple strip between sections) ==========
function PurpleStrip() {
  return (
    <section style={{ padding: '0 24px', marginTop: 48 }}>
      <div style={{
        background: 'var(--violet)',
        color: 'var(--cream)',
        padding: '80px 60px',
        borderRadius: 4,
        position: 'relative',
        overflow: 'hidden',
        display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 40, alignItems: 'center'
      }}>
        <div style={{ position: 'relative', zIndex: 2 }}>
          <span className="mono" style={{ color: 'var(--gold)' }}>◆ FROM ₹799 · FREE SHIPPING</span>
          <h2 className="display" style={{ fontSize: 'clamp(48px, 6vw, 88px)', margin: '16px 0 24px', lineHeight: 1 }}>
            Power that <span className="italic-accent" style={{ color: 'var(--gold)' }}>keeps up</span> with you.
          </h2>
          <p style={{ fontSize: 17, maxWidth: 460, opacity: 0.8, lineHeight: 1.5 }}>
            Braided cables, GaN chargers, MagSafe powerbanks. Engineered for daily life, made in India.
          </p>
          <a href="/category/power" className="btn lg" style={{ background: 'var(--gold)', color: 'var(--ink)', borderColor: 'var(--gold)', marginTop: 28, textDecoration: 'none' }}>Shop Power →</a>
        </div>
        <div style={{ position: 'relative', height: 320, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{
            width: 'min(320px, 90%)', aspectRatio: '1/1',
            borderRadius: '50%', background: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 20px 40px rgba(0,0,0,0.25)'
          }}>
            <img src="assets/charger-transparent.png" style={{ maxHeight: '95%', maxWidth: '95%', objectFit: 'contain' }}/>
          </div>
        </div>
        <img src="assets/lion-mark.png" style={{
          position: 'absolute', left: -80, bottom: -80,
          width: 300, height: 300, opacity: 0.08, filter: 'brightness(3)'
        }}/>
      </div>
    </section>
  );
}

// ========== SECTION 04 — FULLSCREEN IMAGE SLIDER ==========
// To add more images: just append { src: 'assets/yourfile.jpg', caption: '...' }
// Works with ANY number of slides.
// NO static fallback — banners are 100% admin-driven via /super-admin/banners.
// If the API returns nothing, the carousel section just doesn't render at all.
const IMAGE_SLIDES_FALLBACK = [];

function ImageCarousel() {
  const [i, setI] = useStateC(0);
  const [IMAGE_SLIDES, setSlides] = useStateC(IMAGE_SLIDES_FALLBACK);
  const [loaded, setLoaded] = useStateC(false);
  // Auto-discover whatever's in /public/assets/banners/. No renaming needed —
  // any .webp/.jpg/.png/.avif files in the folder show up here.
  useEffectC(() => {
    fetch('/api/home-banners')
      .then(r => r.ok ? r.json() : null)
      .then(d => { if (Array.isArray(d) && d.length) setSlides(d); setLoaded(true); })
      .catch(() => { setLoaded(true); });
  }, []);
  const n = IMAGE_SLIDES.length;
  // ALL hooks must run on every render (React Rules of Hooks). The actual
  // "should we render" decision happens AFTER all useEffect calls below.
  useEffectC(() => {
    if (n <= 1) return;
    const t = setInterval(() => setI(x => (x + 1) % n), 7000);
    return () => clearInterval(t);
  }, [n]);
  // Now safe to early-return: hooks have all been called.
  if (!loaded) return null;
  if (!n) return null;
  const pad = (x) => String(x).padStart(2, '0');
  return (
    <section style={{ margin: 0, padding: 0 }}>
      <div className="hero-carousel-stage" style={{
        position: 'relative',
        width: '100%',
        // 24:10 cinematic ratio — kept on every viewport so the banner fills
        // by width and shrinks proportionally on phones (no portrait crop).
        aspectRatio: '24 / 10',
        maxHeight: '78vh',
        overflow: 'hidden',
        background: 'var(--ink)'
      }}>
        {/* Section tag — top-left */}
        {/* Slides */}
        {IMAGE_SLIDES.map((s, k) => {
          const bgs = ['var(--ink)', 'var(--violet)', 'var(--cream-2)', 'var(--steel)', 'var(--gold)'];
          const fgs = ['var(--cream)', 'var(--cream)', 'var(--ink)', 'var(--cream)', 'var(--ink)'];
          return (
            <div key={k} style={{
              position: 'absolute', inset: 0,
              opacity: k === i ? 1 : 0,
              transition: 'opacity 0.8s ease',
              background: s.src ? 'transparent' : bgs[k % bgs.length],
              color: fgs[k % fgs.length],
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              pointerEvents: k === i ? 'auto' : 'none'
            }}>
              {s.src ? (
                <img src={s.src} alt={s.caption || `Slide ${k+1}`} loading={k === 0 ? 'eager' : 'lazy'}
                     onError={(e) => { e.currentTarget.style.display = 'none'; }}
                     style={{
                  // cover = fill the banner edge-to-edge, no letterboxing.
                  // onError hides the broken-image icon if the banner file
                  // isn't uploaded yet — the dark background shows instead.
                  width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center'
                }}/>
              ) : (
                <div style={{ textAlign: 'center' }}>
                  <div style={{
                    width: 100, height: 100, border: `1.5px dashed currentColor`,
                    borderRadius: 2, margin: '0 auto 32px',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 44, opacity: 0.5
                  }}>+</div>
                  <div className="mono" style={{ opacity: 0.7, marginBottom: 16 }}>
                    ◆ PLACEHOLDER {pad(k + 1)}
                  </div>
                  <div className="display" style={{ fontSize: 'clamp(56px, 7vw, 96px)' }}>
                    {s.caption || `Image ${pad(k + 1)}`}
                  </div>
                  <div className="mono" style={{ opacity: 0.5, marginTop: 16 }}>
                    DROP YOUR IMAGE IN assets/
                  </div>
                </div>
              )}
            </div>
          );
        })}

        {/* Bottom chrome overlay */}
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0,
          padding: '0 48px 36px',
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
          color: 'var(--cream)',
          pointerEvents: 'none'
        }}>
          <div />
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', pointerEvents: 'auto', flexWrap: 'wrap' }}>
            {IMAGE_SLIDES.map((_, k) => (
              <button key={k} onClick={() => setI(k)} aria-label={`Slide ${k+1}`} style={{
                width: k === i ? 56 : 20, height: 3, borderRadius: 0,
                background: k === i ? 'var(--gold)' : 'rgba(255,255,255,0.35)',
                border: 'none', cursor: 'pointer', transition: 'width 0.4s ease',
                padding: 0
              }}/>
            ))}
            <button onClick={() => setI((i - 1 + n) % n)} style={{
              marginLeft: 20, width: 48, height: 48, borderRadius: 2,
              border: '1px solid rgba(255,255,255,0.4)', background: 'transparent',
              color: 'var(--cream)', cursor: 'pointer', fontFamily: 'Space Grotesk'
            }}>←</button>
            <button onClick={() => setI((i + 1) % n)} style={{
              width: 48, height: 48, borderRadius: 2,
              border: '1px solid var(--gold)', background: 'var(--gold)',
              color: 'var(--ink)', cursor: 'pointer', fontFamily: 'Space Grotesk'
            }}>→</button>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Carousel, PurpleStrip, ImageCarousel });
