// Sections component — all content blocks

const sectionsStyles = {
  hero: {
    minHeight: '100vh',
    display: 'flex',
    alignItems: 'center',
    position: 'relative',
    overflow: 'hidden',
  },
  heroContent: {
    position: 'relative',
    zIndex: 2,
  },
  heroImage: {
    position: 'absolute',
    top: 0,
    right: 0,
    width: '50%',
    height: '100%',
    objectFit: 'cover',
    opacity: 0,
  },
  heroImageFull: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%',
    objectFit: 'cover',
    opacity: 0.2,
  },
  heroOverlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%',
    background: 'linear-gradient(to right, var(--primary) 40%, transparent 100%)',
    zIndex: 1,
  },
  heroTagline: {
    marginTop: '24px',
    maxWidth: '600px',
    opacity: 0.8,
  },
  heroCTA: {
    marginTop: '40px',
    display: 'flex',
    gap: '16px',
    flexWrap: 'wrap',
  },
  
  sectionHeader: {
    textAlign: 'center',
    marginBottom: 'calc(var(--s6) * var(--density))',
  },
  sectionLabel: {
    color: 'var(--accent)',
    marginBottom: '12px',
  },
  
  reviewCard: {
    display: 'flex',
    flexDirection: 'column',
    gap: '20px',
  },
  reviewImage: {
    width: '100%',
    aspectRatio: '3/4',
    borderRadius: '2px',
    overflow: 'hidden',
  },
  reviewContent: {
    display: 'flex',
    flexDirection: 'column',
    gap: '12px',
  },
  
  
  lookbookGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
    gap: 'calc(var(--s3) * var(--density))',
  },
  lookbookImage: {
    width: '100%',
    aspectRatio: '3/4',
    borderRadius: '2px',
  },
  
  essentialCard: {
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
    padding: 'calc(var(--s4) * var(--density))',
    border: '1px solid',
    borderColor: 'currentColor',
    borderRadius: '2px',
    transition: 'all 0.3s ease',
  },
  
  pressItem: {
    display: 'flex',
    gap: '24px',
    padding: 'calc(var(--s3) * var(--density)) 0',
    borderBottom: '1px solid',
    borderColor: 'currentColor',
    opacity: 1,
  },
  pressLogo: {
    width: '80px',
    height: '80px',
    flexShrink: 0,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    border: '1px solid',
    borderColor: 'currentColor',
    borderRadius: '2px',
    opacity: 0.4,
  },
  pressContent: {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
    gap: '8px',
  },
  
  shopCard: {
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
  },
  shopImage: {
    width: '100%',
    aspectRatio: '1/1',
    borderRadius: '2px',
  },
  shopInfo: {
    display: 'flex',
    flexDirection: 'column',
    gap: '8px',
  },
  
  bookingForm: {
    display: 'flex',
    flexDirection: 'column',
    gap: 'calc(var(--s3) * var(--density))',
    maxWidth: '600px',
    margin: '0 auto',
  },
  input: {
    padding: 'calc(var(--s2) * var(--density))',
    border: '1px solid',
    borderColor: 'color-mix(in srgb, var(--fg) 30%, transparent)',
    borderRadius: '2px',
    background: 'rgba(255, 255, 255, 0.05)',
    color: 'var(--fg)',
    fontFamily: 'inherit',
    fontSize: '16px',
  },
  textarea: {
    padding: 'calc(var(--s2) * var(--density))',
    border: '1px solid',
    borderColor: 'color-mix(in srgb, var(--fg) 30%, transparent)',
    borderRadius: '2px',
    background: 'rgba(255, 255, 255, 0.05)',
    color: 'var(--fg)',
    fontFamily: 'inherit',
    fontSize: '16px',
    minHeight: '120px',
    resize: 'vertical',
  },
  
  newsletterBox: {
    maxWidth: '600px',
    margin: '0 auto',
    padding: 'calc(var(--s6) * var(--density))',
    border: '2px solid var(--accent)',
    borderRadius: '2px',
    textAlign: 'center',
  },
  newsletterForm: {
    display: 'flex',
    gap: '12px',
    marginTop: '24px',
    flexWrap: 'wrap',
  },
  
  footer: {
    padding: 'calc(var(--s6) * var(--density)) 0 calc(var(--s4) * var(--density))',
    borderTop: '1px solid',
    borderColor: 'currentColor',
    opacity: 1,
  },
  footerGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
    gap: 'calc(var(--s5) * var(--density))',
    marginBottom: 'calc(var(--s5) * var(--density))',
  },
  footerCol: {
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
  },
  footerLinks: {
    display: 'flex',
    flexDirection: 'column',
    gap: '12px',
  },
  footerLink: {
    color: 'inherit',
    textDecoration: 'none',
    opacity: 0.7,
    transition: 'opacity 0.2s ease',
  },
  footerBottom: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: 'calc(var(--s4) * var(--density))',
    flexWrap: 'wrap',
    gap: '16px',
  },
  socialLinks: {
    display: 'flex',
    gap: '16px',
  },
};

// Ethiopian cross motif SVG
const CrossMotif = () => (
  <svg viewBox="0 0 24 24" fill="currentColor">
    <path d="M12 2L14 10H22L16 14L18 22L12 18L6 22L8 14L2 10H10L12 2Z" />
  </svg>
);

const SoundOffIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M11 5L6 9H3v6h3l5 4V5z" />
    <path d="M15.54 8.46a5 5 0 0 1 0 7.07" />
    <path d="M19.07 4.93a10 10 0 0 1 0 14.14" />
    <path d="M2 2l20 20" />
  </svg>
);

const SoundOnIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M11 5L6 9H3v6h3l5 4V5z" />
    <path d="M15.54 8.46a5 5 0 0 1 0 7.07" />
    <path d="M19.07 4.93a10 10 0 0 1 0 14.14" />
  </svg>
);

const HERO_VIDEO_SRC = 'assets/007_1.mp4';
const HERO_POSTER_SRC = 'assets/hafiz-portrait.jpg';

function isPoorNetwork() {
  if (typeof navigator === 'undefined') return false;
  const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
  if (!conn) return false;
  if (conn.saveData) return true;
  const slow = ['slow-2g', '2g'];
  return conn.effectiveType ? slow.includes(conn.effectiveType) : false;
}

const HeroVideo = React.forwardRef(function HeroVideo(
  { className = '', style = {}, muted = true, onHasVideo },
  ref
) {
  const posterOnly = React.useMemo(() => isPoorNetwork(), []);

  React.useEffect(() => {
    onHasVideo?.(!posterOnly);
    return () => onHasVideo?.(false);
  }, [posterOnly, onHasVideo]);

  React.useEffect(() => {
    if (posterOnly) return undefined;
    const el = ref && 'current' in ref ? ref.current : null;
    if (!el) return undefined;

    let cancelled = false;

    const loadVideo = () => {
      if (cancelled || el.dataset.loaded === 'true') return;
      el.dataset.loaded = 'true';
      const source = el.querySelector('source');
      if (!source || source.src) return;
      source.src = source.dataset.src || HERO_VIDEO_SRC;
      el.load();
      const play = () => { el.play().catch(() => {}); };
      if (el.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) play();
      else el.addEventListener('canplay', play, { once: true });
    };

    const scheduleLoad = () => {
      if (typeof requestIdleCallback === 'function') {
        requestIdleCallback(loadVideo, { timeout: 2500 });
      } else {
        setTimeout(loadVideo, 150);
      }
    };

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries.some((entry) => entry.isIntersecting)) {
          observer.disconnect();
          scheduleLoad();
        }
      },
      { rootMargin: '80px 0px', threshold: 0.01 }
    );

    observer.observe(el);
    return () => {
      cancelled = true;
      observer.disconnect();
    };
  }, [posterOnly, ref]);

  if (posterOnly) {
    return (
      <img
        src={HERO_POSTER_SRC}
        alt=""
        role="presentation"
        className={`hero-img hero-video-poster ${className}`.trim()}
        style={style}
        loading="lazy"
        decoding="async"
        fetchPriority="low"
      />
    );
  }

  return (
    <video
      ref={ref}
      className={`hero-img hero-video-lazy ${className}`.trim()}
      style={style}
      muted={muted}
      loop
      playsInline
      autoPlay
      preload="none"
      poster={HERO_POSTER_SRC}
      aria-hidden="true"
    >
      <source data-src={HERO_VIDEO_SRC} type="video/mp4" />
    </video>
  );
});

function Hero({ layout = 'split' }) {
  const heroVideoRef = React.useRef(null);
  const [isMuted, setIsMuted] = React.useState(true);
  const [hasVideo, setHasVideo] = React.useState(false);

  const handleSoundToggle = () => {
    const el = heroVideoRef.current;
    if (!el) return;
    const nextMuted = !isMuted;
    setIsMuted(nextMuted);
    el.muted = nextMuted;
    if (!nextMuted) {
      el.volume = 1;
      el.play().catch(() => {});
    }
  };

  React.useEffect(() => {
    setIsMuted(true);
  }, [layout]);
  const styles = layout === 'full' 
    ? { ...sectionsStyles.hero, background: 'var(--primary)', color: 'var(--bg)' }
    : layout === 'centered'
    ? { ...sectionsStyles.hero, textAlign: 'center', justifyContent: 'center', background: 'var(--primary)', color: 'var(--bg)' }
    : { ...sectionsStyles.hero, background: 'var(--primary)', color: 'var(--bg)' };

  return (
    <section className={`reveal-fade hero-section hero-section--${layout}`} style={styles}>
      {layout === 'split' && (
        <>
          <div className="hero-overlay" aria-hidden="true" />
          <HeroVideo
            ref={heroVideoRef}
            muted={isMuted}
            onHasVideo={setHasVideo}
            className="hero-video-split"
          />
        </>
      )}
      {layout === 'full' && (
        <HeroVideo
          ref={heroVideoRef}
          muted={isMuted}
          onHasVideo={setHasVideo}
          className="hero-video-full"
          style={{ ...sectionsStyles.heroImageFull, opacity: 0.3 }}
        />
      )}
      <div className="container hero-content" style={sectionsStyles.heroContent}>
        <div style={{ maxWidth: layout === 'centered' ? '800px' : '600px', margin: layout === 'centered' ? '0 auto' : '0' }}>
          <div className="label reveal-up" style={{ color: 'var(--accent)' }}>Ethiopia's Premier Style Authority</div>
          <h1 className="display-1 reveal-up" style={{ marginTop: '16px' }}>
            Hafiz Time
          </h1>
          <p className="body-large reveal-up" style={sectionsStyles.heroTagline}>
            The gold standard of Ethiopian menswear. Timeless style, sartorial precision, and the definitive voice on formal elegance.
          </p>
          <div style={sectionsStyles.heroCTA} className="reveal-up hero-cta">
            <a href="#booking" className="btn btn-primary">Book a Collaboration</a>
            <div className="hero-cta-actions">
              <a href="#reviews" className="btn btn-secondary">View Reviews</a>
              {hasVideo && (
                <button
                  type="button"
                  className="btn btn-secondary hero-sound-toggle"
                  onClick={handleSoundToggle}
                  aria-label={isMuted ? 'Unmute hero video' : 'Mute hero video'}
                  aria-pressed={!isMuted}
                >
                  {isMuted ? <SoundOffIcon /> : <SoundOnIcon />}
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
      <div className="motif" style={{ top: '40%', right: '10%' }}>
        <CrossMotif />
      </div>
    </section>
  );
}

function Reviews() {
  const reviews = [
    { title: 'The Perfect Double-Breasted Blazer', category: 'Tailoring', date: 'May 2026', image: 'assets/hafiz1.jpg' },
    { title: 'Italian Leather Oxfords Review', category: 'Footwear', date: 'Apr 2026', image: 'assets/hafiz2.jpg' },
    { title: 'Summer Linen: A Style Guide', category: 'Seasonal', date: 'Mar 2026', image: 'assets/hafiz3.jpg' },
  ];

  return (
    <section id="reviews" className="section">
      <div className="container">
        <div style={sectionsStyles.sectionHeader} className="reveal-fade">
          <div className="label" style={sectionsStyles.sectionLabel}>Featured</div>
          <h2 className="heading-1">Garment Reviews</h2>
        </div>
        <div className="grid-3">
          {reviews.map((review, i) => (
            <div key={i} style={sectionsStyles.reviewCard} className="reveal-up">
              <div style={sectionsStyles.reviewImage} className="img-container">
                <img src={review.image} alt={review.title} />
              </div>
              <div style={sectionsStyles.reviewContent}>
                <div className="caption">{review.category}</div>
                <h3 className="heading-3">{review.title}</h3>
                <div className="body" style={{ opacity: 0.7 }}>{review.date}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Brands() {
  const brands = [
    { name: 'Tecno Mobile', src: 'assets/brand1.jpg' },
    { name: 'Ethiopian Airlines', src: 'assets/brand2.png' },
    { name: 'Sheraton Addis', src: 'assets/brand3.gif' },
    { name: 'Zemen Bank', src: 'assets/brand4.jpeg' },
  ];

  return (
    <section id="brands" className="section-tight" style={{ background: 'var(--surface)' }}>
      <div className="container">
        <div style={sectionsStyles.sectionHeader} className="reveal-fade">
          <div className="label" style={sectionsStyles.sectionLabel}>Partnerships</div>
          <h2 className="heading-1">Brand Collaborations</h2>
        </div>
        <div className="brands-marquee reveal-fade" aria-label="Partner brand logos">
          <div className="brands-marquee-track">
            {[...brands, ...brands].map((brand, i) => (
              <div key={`${brand.src}-${i}`} className="brands-marquee-item">
                <img
                  src={brand.src}
                  alt={brand.name}
                  loading="lazy"
                  decoding="async"
                />
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function Lookbook() {
  const looks = [
    'assets/hafiz4.jpg',
    'assets/hafiz5.jpg',
    'assets/hafiz6.jpg',
    'assets/hafiz7.jpg',
    'assets/hafiz8.jpg',
    'assets/hafiz9.jpg',
  ];

  return (
    <section id="lookbook" className="section">
      <div className="container">
        <div style={sectionsStyles.sectionHeader} className="reveal-fade">
          <div className="label" style={sectionsStyles.sectionLabel}>Gallery</div>
          <h2 className="heading-1">Editorial Lookbook</h2>
        </div>
        <div style={sectionsStyles.lookbookGrid}>
          {looks.map((src, i) => (
            <div key={i} className="img-container reveal-up" style={sectionsStyles.lookbookImage}>
              <img src={src} alt={`Look ${i + 1}`} />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Essentials() {
  const essentials = [
    { title: 'The Navy Blazer', desc: 'Every gentleman\'s foundation' },
    { title: 'Oxford Shoes', desc: 'Timeless leather craftsmanship' },
    { title: 'White Dress Shirt', desc: 'Crisp, impeccable, essential' },
    { title: 'Wool Trousers', desc: 'Tailored to perfection' },
  ];

  return (
    <section id="essentials" className="section-tight">
      <div className="container">
        <div style={sectionsStyles.sectionHeader} className="reveal-fade">
          <div className="label" style={sectionsStyles.sectionLabel}>Fundamentals</div>
          <h2 className="heading-1">Wardrobe Essentials</h2>
        </div>
        <div className="grid-2">
          {essentials.map((item, i) => (
            <div key={i} style={sectionsStyles.essentialCard} className="reveal-up">
              <h3 className="heading-2">{item.title}</h3>
              <p className="body">{item.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Press() {
  const mentions = [
    { outlet: 'Vogue Italia', title: 'Africa\'s Rising Style Icons', date: 'May 2026' },
    { outlet: 'GQ Middle East', title: 'The New Tailors', date: 'Apr 2026' },
    { outlet: 'Financial Times', title: 'Ethiopian Fashion\'s Global Reach', date: 'Mar 2026' },
  ];

  return (
    <section id="press" className="section" style={{ background: 'var(--surface)' }}>
      <div className="container-narrow">
        <div style={sectionsStyles.sectionHeader} className="reveal-fade">
          <div className="label" style={sectionsStyles.sectionLabel}>Recognition</div>
          <h2 className="heading-1">Press & Features</h2>
        </div>
        <div>
          {mentions.map((item, i) => (
            <div key={i} style={sectionsStyles.pressItem} className="reveal-left">
              <div style={sectionsStyles.pressLogo}>
                <span className="caption">{item.outlet}</span>
              </div>
              <div style={sectionsStyles.pressContent}>
                <h3 className="heading-3">{item.title}</h3>
                <div className="body" style={{ opacity: 0.7 }}>{item.outlet} — {item.date}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Shop() {
  const products = [
    { name: 'Signature Tie Bar', price: '$120', image: 'assets/hafiz10.jpg' },
    { name: 'Leather Card Holder', price: '$85', image: 'assets/hafiz11.jpg' },
    { name: 'Pocket Square Set', price: '$60', image: 'assets/hafiz12.jpg' },
    { name: 'Style Guide Book', price: '$45', image: 'assets/hafiz13.jpg' },
  ];

  return (
    <section id="shop" className="section-tight">
      <div className="container">
        <div style={sectionsStyles.sectionHeader} className="reveal-fade">
          <div className="label" style={sectionsStyles.sectionLabel}>Shop</div>
          <h2 className="heading-1">Recommended Pieces</h2>
        </div>
        <div className="grid-4">
          {products.map((item, i) => (
            <div key={i} style={sectionsStyles.shopCard} className="reveal-up">
              <div style={sectionsStyles.shopImage} className="img-container">
                <img src={item.image} alt={item.name} />
              </div>
              <div style={sectionsStyles.shopInfo}>
                <h3 className="heading-3">{item.name}</h3>
                <div className="body" style={{ color: 'var(--accent)', fontWeight: 600 }}>{item.price}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Booking() {
  return (
    <section id="booking" className="section" style={{ background: 'var(--primary)', color: 'var(--bg)' }}>
      <div className="container-narrow">
        <div style={sectionsStyles.sectionHeader} className="reveal-fade">
          <div className="label" style={sectionsStyles.sectionLabel}>Get in Touch</div>
          <h2 className="heading-1">Book a Collaboration</h2>
          <p className="body-large" style={{ marginTop: '16px', opacity: 0.8 }}>
            Partner with Ethiopia's premier style authority for campaigns, content, and brand excellence.
          </p>
        </div>
        <form style={sectionsStyles.bookingForm} className="reveal-up" onSubmit={(e) => e.preventDefault()}>
          <input type="text" placeholder="Your Name" style={sectionsStyles.input} />
          <input type="email" placeholder="Email Address" style={sectionsStyles.input} />
          <input type="text" placeholder="Company / Brand" style={sectionsStyles.input} />
          <textarea placeholder="Tell us about your project" style={sectionsStyles.textarea}></textarea>
          <button type="submit" className="btn btn-primary">Submit Inquiry</button>
        </form>
      </div>
    </section>
  );
}

function Newsletter() {
  return (
    <section id="newsletter" className="section-tight">
      <div className="container">
        <div style={sectionsStyles.newsletterBox} className="reveal-scale">
          <h2 className="heading-2">Join the Movement</h2>
          <p className="body" style={{ marginTop: '12px', opacity: 0.7 }}>
            Weekly style insights, reviews, and exclusive content delivered to your inbox.
          </p>
          <form style={sectionsStyles.newsletterForm} onSubmit={(e) => e.preventDefault()}>
            <input 
              type="email" 
              placeholder="Your email" 
              style={{ ...sectionsStyles.input, flex: 1 }} 
            />
            <button type="submit" className="btn btn-primary">Subscribe</button>
          </form>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer style={sectionsStyles.footer}>
      <div className="container">
        <div style={sectionsStyles.footerGrid}>
          <div style={sectionsStyles.footerCol}>
            <h3 className="heading-3">Hafiz Time</h3>
            <p className="body" style={{ opacity: 0.7 }}>
              The gold standard of Ethiopian menswear.
            </p>
          </div>
          <div style={sectionsStyles.footerCol}>
            <div className="label">Quick Links</div>
            <div style={sectionsStyles.footerLinks}>
              <a href="#reviews" style={sectionsStyles.footerLink} className="body">Reviews</a>
              <a href="#lookbook" style={sectionsStyles.footerLink} className="body">Lookbook</a>
              <a href="#shop" style={sectionsStyles.footerLink} className="body">Shop</a>
            </div>
          </div>
          <div style={sectionsStyles.footerCol}>
            <div className="label">Connect</div>
            <div style={sectionsStyles.footerLinks}>
              <a href="#" style={sectionsStyles.footerLink} className="body">Instagram</a>
              <a href="#" style={sectionsStyles.footerLink} className="body">YouTube</a>
              <a href="#" style={sectionsStyles.footerLink} className="body">TikTok</a>
            </div>
          </div>
          <div style={sectionsStyles.footerCol}>
            <div className="label">Legal</div>
            <div style={sectionsStyles.footerLinks}>
              <a href="#" style={sectionsStyles.footerLink} className="body">Privacy</a>
              <a href="#" style={sectionsStyles.footerLink} className="body">Terms</a>
            </div>
          </div>
        </div>
        <div style={sectionsStyles.footerBottom}>
          <div className="body" style={{ opacity: 0.5 }}>© 2026 Hafiz Time. All rights reserved.</div>
          <div style={sectionsStyles.socialLinks}>
            <a href="#" style={{ ...sectionsStyles.footerLink, opacity: 0.5 }}>IG</a>
            <a href="#" style={{ ...sectionsStyles.footerLink, opacity: 0.5 }}>YT</a>
            <a href="#" style={{ ...sectionsStyles.footerLink, opacity: 0.5 }}>TT</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// Export to window
Object.assign(window, {
  Hero,
  Reviews,
  Brands,
  Lookbook,
  Essentials,
  Press,
  Shop,
  Booking,
  Newsletter,
  Footer,
});
