/* global React */
const { useState, useEffect, useRef } = React;

/* ============================================
   Shared mobile hook
   ============================================ */
function useIsMobile(breakpoint = 768) {
  const [mobile, setMobile] = useState(window.innerWidth <= breakpoint);
  useEffect(() => {
    const onResize = () => setMobile(window.innerWidth <= breakpoint);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [breakpoint]);
  return mobile;
}

/* ============================================
   Logo — DOT typografické s tečkou
   ============================================ */
function Logo({ inverted = false, dark = false }) {
  return (
    <a href="index.html" className="dot-logo">
      <img
        src={dark ? 'images/dot_kuchyne_logo_black.png' : 'images/dot_kuchyne_logo.png'}
        alt="DOT kuchyně"
        style={{
          height: '32px',
          display: 'block',
          filter: inverted ? 'brightness(0) invert(1)' : 'none',
        }}
      />
    </a>
  );
}

/* ============================================
   NAV
   ============================================ */
function Nav({ inverted = false, dark = false }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const [ctaHover, setCtaHover] = useState(false);
  const mobile = useIsMobile();
  const navColor = inverted && !menuOpen ? '#FAFAF7' : 'var(--ink)';
  const primaryBg = inverted && !menuOpen ? '#FAFAF7' : 'var(--ink)';
  const primaryColor = inverted && !menuOpen ? '#1A1A1A' : 'var(--bg)';

  // Lock body scroll when menu is open
  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);

  const links = [
    { label: 'Naše kuchyně', anchor: 'nase-kuchyne' },
    { label: 'Jak pracujeme', anchor: 'jak-pracujeme' },
    { label: 'Spotřebiče', anchor: 'spotrebice' },
    { label: 'Cena', anchor: 'ceny' },
    { label: 'Náš tým', anchor: 'nas-tym' },
    { label: 'Recenze', anchor: 'recenze' },
  ];

  const scrollTo = (anchor) => {
    const el = document.getElementById(anchor);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <>
      <nav style={{
        position: menuOpen ? 'fixed' : 'relative',
        top: menuOpen ? 0 : undefined,
        left: menuOpen ? 0 : undefined,
        right: menuOpen ? 0 : undefined,
        zIndex: 100,
        padding: mobile ? '16px 0' : '24px 0',
        background: menuOpen ? '#ffffff' : 'transparent',
        transition: 'all 0.3s ease',
        flexShrink: 0,
      }}>
        <div className="container" style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}>
          <Logo inverted={inverted && !menuOpen} dark={dark} />

          {!mobile && (
            <ul style={{
              display: 'flex',
              listStyle: 'none',
              gap: '40px',
              fontFamily: 'var(--sans)',
              fontSize: '14px',
              fontWeight: 400,
            }}>
              {links.map((item) => (
                <li key={item.label}>
                  <a href={`#${item.anchor}`} onClick={(e) => { e.preventDefault(); scrollTo(item.anchor); }} style={{
                    color: navColor,
                    position: 'relative',
                    paddingBottom: '4px',
                    transition: 'opacity 0.2s ease',
                    cursor: 'pointer',
                  }}
                  onMouseEnter={(e) => e.currentTarget.style.opacity = '0.6'}
                  onMouseLeave={(e) => e.currentTarget.style.opacity = '1'}
                  >
                    {item.label}
                  </a>
                </li>
              ))}
            </ul>
          )}

          {!mobile && (
            <a
              href="#kontakt"
              onClick={scrollToKontakt}
              className="btn btn-primary"
              onMouseEnter={() => setCtaHover(true)}
              onMouseLeave={() => setCtaHover(false)}
              style={{
                background: ctaHover ? '#a6192e' : primaryBg,
                color: ctaHover ? '#ffffff' : primaryColor,
                borderRadius: '999px',
                fontSize: '13px',
                fontWeight: 600,
                letterSpacing: ctaHover ? '0.1em' : '0.06em',
                padding: '11px 20px',
                transform: ctaHover ? 'scale(1.04)' : 'scale(1)',
                transition: 'background 0.3s ease, color 0.3s ease, transform 0.3s ease, letter-spacing 0.3s ease',
                boxShadow: ctaHover ? '0 4px 20px rgba(0,0,0,0.22)' : 'none',
              }}
            >
              3D NÁVRH ZDARMA →
            </a>
          )}

          {mobile && (
            <button
              onClick={() => setMenuOpen(!menuOpen)}
              aria-label="Menu"
              style={{
                width: '44px', height: '44px',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                position: 'relative', zIndex: 101,
              }}
            >
              <div style={{ width: '22px', height: '14px', position: 'relative' }}>
                <span style={{
                  position: 'absolute', left: 0, width: '100%', height: '1.5px',
                  background: navColor,
                  transition: 'all 0.3s ease',
                  top: menuOpen ? '6px' : '0',
                  transform: menuOpen ? 'rotate(45deg)' : 'none',
                }} />
                <span style={{
                  position: 'absolute', left: 0, width: '100%', height: '1.5px',
                  background: navColor,
                  top: '6px',
                  opacity: menuOpen ? 0 : 1,
                  transition: 'opacity 0.2s ease',
                }} />
                <span style={{
                  position: 'absolute', left: 0, width: '100%', height: '1.5px',
                  background: navColor,
                  transition: 'all 0.3s ease',
                  top: menuOpen ? '6px' : '12px',
                  transform: menuOpen ? 'rotate(-45deg)' : 'none',
                }} />
              </div>
            </button>
          )}
        </div>
      </nav>

      {/* Mobile menu overlay */}
      {mobile && (
        <div style={{
          position: 'fixed',
          inset: 0,
          zIndex: 99,
          background: '#ffffff',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'flex-start',
          opacity: menuOpen ? 1 : 0,
          pointerEvents: menuOpen ? 'auto' : 'none',
          transition: 'opacity 0.3s ease',
          overflowY: 'auto',
        }}>
          {/* Spacer for nav bar */}
          <div style={{ height: '64px', flexShrink: 0 }} />

          {/* Navigation links */}
          <div style={{ padding: '4px 28px 0' }}>
            {links.map((item) => (
              <a
                key={item.label}
                href={`#${item.anchor}`}
                onClick={(e) => { e.preventDefault(); setMenuOpen(false); setTimeout(() => scrollTo(item.anchor), 300); }}
                style={{
                  display: 'block',
                  color: 'var(--ink)',
                  fontSize: '20px',
                  fontFamily: 'var(--sans)',
                  fontWeight: 500,
                  padding: '9px 0',
                  textDecoration: 'none',
                }}
              >
                {item.label}
              </a>
            ))}
          </div>

          {/* CTA */}
          <div style={{ padding: '14px 28px 0' }}>
            <a
              href="#kontakt"
              className="btn btn-primary"
              style={{ borderRadius: '999px', width: '100%', justifyContent: 'center', boxSizing: 'border-box' }}
              onClick={(e) => { e.preventDefault(); setMenuOpen(false); setTimeout(scrollToKontakt, 300); }}
            >
              3D NÁVRH ZDARMA →
            </a>
          </div>

          {/* Divider */}
          <div style={{ margin: '35px 28px 0', borderTop: '1px solid rgba(0,0,0,0.1)' }} />

          {/* Studios */}
          <div style={{ padding: '31px 28px 24px' }}>
            <div style={{ fontFamily: 'var(--sans)', fontSize: '11px', fontWeight: 600, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.35)', marginBottom: '10px' }}>Naše studia</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
              {['Praha – Letná', 'Praha – Vinohrady', 'Brno – Centrum', 'Olomouc', 'Jihlava'].map((studio, i) => (
                <div key={i} style={{
                  fontFamily: 'var(--sans)',
                  fontSize: '15px',
                  fontWeight: 400,
                  color: 'var(--ink)',
                  padding: '6px 0',
                }}>
                  {studio}
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

/* ============================================
   HERO — scroll-driven animation (desktop)
   ============================================ */
function Hero() {
  const mobile = useIsMobile();
  const [progress, setProgress] = useState(0);
  const [viewport, setViewport] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });
  const [imgAspectRatio, setImgAspectRatio] = useState(3 / 2);
  const sectionRef = useRef(null);
  const lockedHeightRef = useRef(window.innerHeight);

  useEffect(() => {
    const img = new Image();
    img.onload = () => {
      if (img.naturalWidth && img.naturalHeight) {
        setImgAspectRatio(img.naturalWidth / img.naturalHeight);
      }
    };
    img.src = 'images/newhero_1.webp';
  }, []);

  useEffect(() => {
    const onScroll = () => {
      if (!sectionRef.current) return;
      const rect = sectionRef.current.getBoundingClientRect();
      const scrolled = -rect.top;
      const threshold = sectionRef.current.offsetHeight * 0.42;
      const raw = Math.min(1, Math.max(0, scrolled / threshold));
      // sqrt curve: first scroll triggers disproportionately large visual change
      const p = Math.pow(raw, 0.5);
      setProgress(p);
    };
    const onResizeWidthOnly = () => {
      setViewport({
        width: window.innerWidth,
        height: lockedHeightRef.current,
      });
      onScroll();
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onResizeWidthOnly);
    onScroll();
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onResizeWidthOnly);
    };
  }, []);

  const eased = progress < 0.5
    ? 2 * progress * progress
    : 1 - Math.pow(-2 * progress + 2, 2) / 2;
  const diagonal = 200 - eased * 200;
  const revealClipPath = diagonal >= 100
    ? `polygon(100% ${diagonal - 100}%, 100% 100%, ${diagonal - 100}% 100%)`
    : `polygon(${diagonal}% 0%, 100% 0%, 100% 100%, 0% 100%, 0% ${diagonal}%)`;
  const heroViewportHeight = mobile
    ? Math.round(lockedHeightRef.current * 1.1)
    : Math.round(viewport.height * (viewport.width >= 1600 ? 1.1 : 1.2));
  const heroImageStyle = {
    position: 'absolute',
    inset: 0,
    backgroundSize: 'cover',
    backgroundPosition: mobile ? 'center center' : 'center calc(50% - 20px)',
    backgroundRepeat: 'no-repeat',
  };
  const titleShift = mobile ? 74 : 120;
  const titleStyle = {
    position: 'absolute',
    inset: 0,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    padding: mobile ? '0 12px' : '0 48px',
    fontFamily: 'var(--sans)',
    fontSize: mobile ? '50px' : '78px',
    lineHeight: 1.02,
    fontWeight: 500,
    letterSpacing: 0,
    textAlign: 'center',
    willChange: 'opacity, transform',
  };

  return (
    <section id="uvod" data-hero-section ref={sectionRef} style={{
      position: 'relative',
      height: `${heroViewportHeight * 1.8}px`,
      marginBottom: '-1px',
      background: 'var(--bg)',
    }}>
      <div style={{
        position: 'sticky',
        top: 0,
        height: `${heroViewportHeight}px`,
        overflow: 'hidden',
      }}>
        <div style={{
          ...heroImageStyle,
          backgroundImage: 'url("images/newhero_1.webp")',
        }}>
        </div>
        <div style={{
          ...heroImageStyle,
          backgroundImage: 'url("images/newhero_2b.webp")',
          clipPath: revealClipPath,
          willChange: 'clip-path',
          bottom: '-2px',
        }} />
        <div style={{
          position: 'absolute',
          inset: 0,
          background: 'linear-gradient(180deg, rgba(0,0,0,0.34) 0%, rgba(0,0,0,0.12) 24%, rgba(0,0,0,0) 58%)',
          pointerEvents: 'none',
        }} />
        <div style={{
          position: 'absolute',
          inset: 0,
          zIndex: 1,
          pointerEvents: 'none',
          overflow: 'hidden',
          transform: `translateY(${mobile ? -73 : -125}px)`,
        }}>
          <h1 style={{
            ...titleStyle,
            fontSize: mobile ? '36px' : titleStyle.fontSize,
            opacity: 1 - eased,
            transform: `translateY(${-titleShift * eased}px)`,
            color: '#dfd2bf',
            textShadow: '0 2px 24px rgba(0, 0, 0, 0.42), 0 8px 34px rgba(0, 0, 0, 0.32)',
          }}>
            <span style={{ display: 'block', maxWidth: '1100px' }}>
              {mobile ? (
                <span style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: '4px',
                  marginBottom: '16px',
                  lineHeight: 1,
                  textShadow: 'inherit',
                }}>
                  <span style={{
                    display: 'inline-flex',
                    alignItems: 'baseline',
                    gap: '6px',
                    fontWeight: 300,
                    letterSpacing: '0.14em',
                    textTransform: 'uppercase',
                    fontSize: '18px',
                    lineHeight: 1,
                  }}>
                    STUDIO
                    <img
                      src="images/dot_logo.png"
                      alt="DOT"
                      style={{
                        height: '14px',
                        display: 'inline-block',
                        verticalAlign: 'middle',
                        filter: 'none',
                      }}
                    />
                    &amp;
                  </span>
                  <span style={{
                    fontWeight: 300,
                    letterSpacing: '0.14em',
                    textTransform: 'uppercase',
                    fontSize: '18px',
                    lineHeight: 1,
                  }}>
                    KUCHYNĚ <span style={{ fontWeight: 700 }}>GORENJE</span>
                  </span>
                </span>
              ) : (
                <span style={{
                  display: 'inline-flex',
                  alignItems: 'baseline',
                  justifyContent: 'center',
                  gap: '10px',
                  marginBottom: '22px',
                  lineHeight: 1,
                  textShadow: 'inherit',
                  whiteSpace: 'nowrap',
                }}>
                  <span style={{
                    fontWeight: 300,
                    letterSpacing: '0.22em',
                    textTransform: 'uppercase',
                    fontSize: '22px',
                    lineHeight: 1,
                  }}>
                    STUDIO
                  </span>
                  <img
                    src="images/dot_logo.png"
                    alt="DOT"
                    style={{
                      height: '18px',
                      display: 'inline-block',
                      verticalAlign: 'middle',
                      filter: 'none',
                    }}
                  />
                  <span style={{
                    fontWeight: 300,
                    letterSpacing: '0.22em',
                    textTransform: 'uppercase',
                    fontSize: '22px',
                    lineHeight: 1,
                  }}>
                    & KUCHYNĚ <span style={{ fontWeight: 700 }}>GORENJE</span>
                  </span>
                </span>
              )}
              <span style={{ display: 'block', marginTop: '-10px', color: '#ffffff', fontSize: mobile ? '48px' : undefined }}>Tvoříme krásné kuchyně.</span>
            </span>
          </h1>
          <h1 style={{
            ...titleStyle,
            fontSize: mobile ? '50px' : titleStyle.fontSize,
            lineHeight: mobile ? 1.05 : 1.02,
            opacity: eased,
            transform: `translateY(${titleShift * (1 - eased) - (mobile ? 45 : 35)}px)`,
            color: '#0A0A0A',
            textShadow: '0 2px 10px rgba(255, 255, 255, 0.95), 0 8px 32px rgba(255, 255, 255, 0.78)',
          }}>
            <span style={{ display: 'block', maxWidth: '1100px' }}>
              {mobile ? (
                <>
                  <span style={{ display: 'block' }}>Od návrhu</span>
                  <span style={{ display: 'block' }}>po život.</span>
                </>
              ) : (
                'Od návrhu po život.'
              )}
            </span>
          </h1>
        </div>
        {/* Location badge — bottom right, fades with first headline, desktop only */}
        {!mobile && (
        <div style={{
          position: 'absolute',
          bottom: `${Math.max(16, heroViewportHeight - lockedHeightRef.current + 16)}px`,
          left: 0,
          right: 0,
          zIndex: 3,
          pointerEvents: 'none',
          opacity: Math.max(0, 1 - eased * 2.5),
        }}>
          <div className="container" style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: '7px',
              color: 'rgba(255,255,255,0.72)',
              fontFamily: 'var(--sans)',
              fontSize: '13px',
              fontWeight: 400,
              letterSpacing: '0.12em',
              textTransform: 'uppercase',
              textShadow: '0 1px 8px rgba(0,0,0,0.4)',
            }}>
              <div style={{ textAlign: 'right', lineHeight: '1.7' }}>
                <div>PRAHA – LETNÁ</div>
                <div>PRAHA – VINOHRADY</div>
                <div>BRNO – CENTRUM</div>
                <div>OLOMOUC</div>
                <div>JIHLAVA</div>
              </div>
            </div>
          </div>
        </div>
        )}

        {/* Scroll indicator — mobile only, disappears on scroll */}
        {mobile && (
        <div style={{
          position: 'fixed',
          bottom: '36px',
          left: 0, right: 0,
          zIndex: 3,
          display: 'flex',
          justifyContent: 'center',
          pointerEvents: 'none',
          opacity: Math.max(0, 1 - eased * 4),
        }}>
          <style>{`
            @keyframes scrollChevron {
              0% { opacity: 0; transform: translateY(-6px); }
              50% { opacity: 1; }
              100% { opacity: 0; transform: translateY(4px); }
            }
          `}</style>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '2px' }}>
            {[0, 1, 2].map(i => (
              <svg key={i} width="24" height="14" viewBox="0 0 24 14" fill="none"
                style={{ animation: `scrollChevron 1.6s ease-in-out ${i * 0.22}s infinite` }}>
                <polyline points="2,2 12,12 22,2" stroke="rgba(255,255,255,0.7)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            ))}
          </div>
        </div>
        )}

        <div style={{
          position: 'relative',
          zIndex: 2,
        }}>
          <Nav inverted />
        </div>
      </div>
    </section>
  );
}

/* ============================================
   INFO MARQUEE
   ============================================ */
function InfoMarquee() {
  const items = [
    { icon: 'check', label: '2 000+ realizací' },
    { icon: 'clock', label: '10 let zkušeností' },
    { icon: 'star', label: '4,9 průměrné hodnocení', href: 'https://www.recenze-kuchyne.cz/recenze/kuchyne-gorenje' },
    { icon: 'pin', label: '10 studií po celé ČR' },
    { icon: 'leaf', label: 'Německo-česká výroba' },
  ];

  const Icon = ({ name }) => {
    const props = {
      width: 24, height: 24, viewBox: '0 0 24 24',
      fill: 'none', stroke: 'currentColor', strokeWidth: 1.4,
      strokeLinecap: 'round', strokeLinejoin: 'round',
    };
    switch (name) {
      case 'check': return <svg {...props}><path d="M20 6L9 17l-5-5"/></svg>;
      case 'clock': return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
      case 'star':  return <svg {...props}><path d="M12 3l2.7 5.7 6.3.9-4.5 4.4 1.1 6.3L12 17.3l-5.6 3 1.1-6.3L3 9.6l6.3-.9z"/></svg>;
      case 'pin':   return <svg {...props}><path d="M12 21s7-7.5 7-12a7 7 0 10-14 0c0 4.5 7 12 7 12z"/><circle cx="12" cy="9" r="2.5"/></svg>;
      case 'leaf':  return <svg {...props}><path d="M5 19c8 0 14-6 14-14-8 0-14 6-14 14z"/><path d="M5 19l5-5"/></svg>;
      default: return null;
    }
  };

  const reel = [...items, ...items, ...items, ...items];

  return (
    <section style={{
      borderTop: '1px solid var(--line)',
      borderBottom: '1px solid var(--line)',
      background: 'var(--bg)',
      padding: '36px 0',
      overflow: 'hidden',
    }}>
      <div style={{
        display: 'flex',
        width: 'max-content',
        animation: 'marquee 38s linear infinite',
      }}>
        {reel.map((it, i) => {
          const inner = (
            <>
              <span style={{ color: 'var(--ink)' }}>
                <Icon name={it.icon} />
              </span>
              <span>{it.label}</span>
            </>
          );
          const sharedStyle = {
            display: 'flex',
            alignItems: 'center',
            gap: '14px',
            padding: '0 44px',
            borderRight: '1px solid var(--line)',
            color: 'var(--ink)',
            fontFamily: 'var(--sans)',
            fontSize: '16px',
            fontWeight: 400,
            letterSpacing: '0.01em',
            whiteSpace: 'nowrap',
            textDecoration: 'none',
          };
          return it.href
            ? <a key={i} href={it.href} target="_blank" rel="noopener noreferrer" style={sharedStyle}>{inner}</a>
            : <div key={i} style={sharedStyle}>{inner}</div>;
        })}
      </div>
      <style>{`
        @keyframes marquee {
          from { transform: translateX(0); }
          to   { transform: translateX(-50%); }
        }
      `}</style>
    </section>
  );
}

/* ============================================
   FLOATING CTA — appears after 500px scroll
   ============================================ */
function FloatingCta() {
  const [visible, setVisible] = useState(false);
  const mobile = useIsMobile();

  useEffect(() => {
    const onScroll = () => {
      const kontakt = document.getElementById('kontakt');
      const jakPracujeme = document.getElementById('jak-pracujeme');
      const workSectionInView = jakPracujeme
        ? jakPracujeme.getBoundingClientRect().top < window.innerHeight && jakPracujeme.getBoundingClientRect().bottom > 0
        : false;
      if (kontakt) {
        const rect = kontakt.getBoundingClientRect();
        const inView = rect.top < window.innerHeight && rect.bottom > 0;
        setVisible(window.scrollY > 1000 && !inView && !workSectionInView);
      } else {
        setVisible(window.scrollY > 1000 && !workSectionInView);
      }
    };
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <a href="#kontakt" onClick={scrollToKontakt} style={{
      position: 'fixed',
      bottom: mobile ? '16px' : '24px',
      left: '50%',
      transform: visible ? 'translateX(-50%) translateY(0)' : 'translateX(-50%) translateY(calc(100% + 40px))',
      zIndex: 90,
      display: 'flex',
      alignItems: 'center',
      gap: mobile ? '12px' : '16px',
      padding: mobile ? '10px 14px 10px 20px' : '10px 16px 10px 28px',
      textDecoration: 'none',
      background: '#ffffff',
      border: '1px solid #dddddd',
      boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)',
      borderRadius: '0',
      transition: 'transform 0.5s cubic-bezier(0.4, 0.0, 0.2, 1), opacity 0.5s ease',
      opacity: visible ? 1 : 0,
      pointerEvents: visible ? 'auto' : 'none',
    }}>
      <span style={{
        fontFamily: 'var(--serif)',
        fontSize: mobile ? '16px' : '19px',
        color: 'var(--ink)',
        fontWeight: 400,
        whiteSpace: 'nowrap',
      }}>
        Sjednejte si schůzku na studiu
      </span>
      <button style={{
        background: 'var(--ink)',
        color: 'var(--bg)',
        border: 'none',
        width: mobile ? '36px' : '42px',
        height: mobile ? '36px' : '42px',
        borderRadius: '0',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        cursor: 'pointer',
        flexShrink: 0,
        transition: 'opacity 0.2s ease',
      }}
      onMouseEnter={(e) => e.currentTarget.style.opacity = '0.85'}
      onMouseLeave={(e) => e.currentTarget.style.opacity = '1'}
      >
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M5 12h14M13 5l7 7-7 7"/>
        </svg>
      </button>
    </a>
  );
}

function scrollToKontakt(e) {
  if (e) e.preventDefault();
  const el = document.getElementById('cta-heading');
  if (el) {
    const top = el.getBoundingClientRect().top + window.scrollY - 10;
    window.scrollTo({ top, behavior: 'smooth' });
  }
}

/* ============================================
   PROMO BAR — slides in from top after scrolling
   past the Jak pracujeme controls
   ============================================ */
function PromoBar() {
  const [visible, setVisible] = useState(false);
  const [dismissed, setDismissed] = useState(false);
  const mobile = useIsMobile();

  useEffect(() => {
    const onScroll = () => {
      if (dismissed) return;
      const section = document.getElementById('jak-pracujeme');
      if (!section) return;
      const rect = section.getBoundingClientRect();
      // Show when user has scrolled past the bottom of the section
      setVisible(rect.bottom < window.innerHeight * 0.5);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [dismissed]);

  if (dismissed) return null;

  return (
    <div
      data-promo-bar
      onClick={mobile ? scrollToKontakt : undefined}
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        zIndex: 200,
        transform: visible ? 'translateY(0)' : 'translateY(-110%)',
        transition: 'transform 0.55s cubic-bezier(0.34, 1.56, 0.64, 1)',
        background: '#a6192e',
        display: 'flex',
        alignItems: 'center',
        justifyContent: mobile ? 'space-between' : 'center',
        gap: mobile ? '10px' : '24px',
        padding: mobile ? '8px 12px' : '8px 24px',
        flexWrap: 'nowrap',
        cursor: mobile ? 'pointer' : 'default',
      }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: mobile ? '1 1 0' : 'none' }}>
        <span style={{
          fontFamily: 'var(--sans)',
          fontSize: mobile ? '14px' : '15px',
          fontWeight: 400,
          color: '#ffffff',
          textAlign: 'left',
          lineHeight: mobile ? 1 : 'inherit',
        }}>
          {mobile ? (
            <>Letní akce: <strong>30 % sleva</strong> na kuchyně<br />na míru + 3 spotřebiče zdarma</>
          ) : (
            <>Letní akce: <strong>30 % sleva</strong> na kuchyně na míru + 3 spotřebiče zdarma</>
          )}
        </span>
        {mobile && (
          <svg style={{ flexShrink: 0 }} width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.8)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 12h14M13 5l7 7-7 7"/>
          </svg>
        )}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flexShrink: 0 }}>
        {!mobile && (
          <a
            href="#kontakt"
            onClick={scrollToKontakt}
            style={{
              display: 'inline-block',
              padding: '8px 22px',
              borderRadius: '999px',
              background: '#ffffff',
              color: '#a6192e',
              fontFamily: 'var(--sans)',
              fontSize: '13px',
              fontWeight: 700,
              letterSpacing: '0.06em',
              textTransform: 'uppercase',
              textDecoration: 'none',
              whiteSpace: 'nowrap',
            }}
          >
            Chci slevu →
          </a>
        )}
        <button
          onClick={(e) => { e.stopPropagation(); setDismissed(true); }}
          aria-label="Zavřít"
          style={{
            background: 'none',
            border: 'none',
            color: 'rgba(255,255,255,0.7)',
            cursor: 'pointer',
            padding: '4px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            flexShrink: 0,
          }}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            <path d="M18 6L6 18M6 6l12 12"/>
          </svg>
        </button>
      </div>
    </div>
  );
}

/* ============================================
   STICKY PROMO BUTTON
   - fades in under "Od návrhu po život." heading
   - tracks heading upward as hero peels off
   - pins at top: 3px and stays there
   ============================================ */
function StickyPromoBtn() {
  const mobile = useIsMobile();
  const [btnState, setBtnState] = useState({ opacity: 0, top: 200, show: false, hidden: false });
  const prevScrollYRef = useRef(window.scrollY);
  const afterJakRef = useRef(false); // true once jak-pracujeme entered view while pinned
  const lockedVhRef = useRef(window.innerHeight); // lock vh on mount to avoid iOS URL bar jump

  useEffect(() => {
    const onScroll = () => {
      const heroSection = document.querySelector('[data-hero-section]');
      if (!heroSection) return;

      const sectionHeight = heroSection.offsetHeight;
      const heroH = sectionHeight / 1.8;
      const vh = lockedVhRef.current;
      const scrollY = window.scrollY;
      const isMobile = window.innerWidth < 768;
      const btnFraction = isMobile ? 0.57 : 0.46;
      const btnOffset = isMobile ? 0 : 20;

      prevScrollYRef.current = scrollY;

      // Opacity based on hero eased progress
      const threshold = sectionHeight * 0.42;
      const raw = Math.min(1, Math.max(0, scrollY / threshold));
      const p = Math.pow(raw, 0.5);
      const eased = p < 0.5 ? 2 * p * p : 1 - Math.pow(-2 * p + 2, 2) / 2;
      const opacity = Math.max(0, (eased - 0.4) / 0.6);

      if (opacity <= 0) {
        afterJakRef.current = false;
        setBtnState({ opacity: 0, top: Math.round(vh * btnFraction + btnOffset), show: false, hidden: false });
        return;
      }

      const unstickAt = heroH * 0.76;
      const pinAt = unstickAt + vh * btnFraction + btnOffset - 3;

      if (scrollY < pinAt) afterJakRef.current = false;

      const titleShift = isMobile ? 74 : 120;
      let top;
      if (scrollY <= unstickAt) {
        top = Math.round(vh * btnFraction + btnOffset + titleShift * (1 - eased));
      } else if (scrollY < pinAt) {
        top = Math.round(unstickAt - scrollY + vh * btnFraction + btnOffset);
      } else {
        top = 3;
      }

      // Desktop expansion: scroll-driven width 270px → full after pinning
      const EXPAND_DIST = 300;
      const expandRaw = Math.min(1, Math.max(0, (scrollY - pinAt) / EXPAND_DIST));
      const expandEased = expandRaw < 0.5
        ? 2 * expandRaw * expandRaw
        : 1 - Math.pow(-2 * expandRaw + 2, 2) / 2;
      const fullWidth = isMobile ? window.innerWidth - 10 : Math.min(window.innerWidth, 1440) - 160;
      const pillWidth = isMobile ? 230 : 270;
      const buttonWidth = top === 3 ? Math.round(pillWidth + (fullWidth - pillWidth) * expandEased) : null;
      const showExpandedText = expandRaw > 0.5;

      // Hide when kontakt section is reached
      let hidden = false;
      if (top === 3) {
        const kontaktSection = document.getElementById('kontakt');
        if (kontaktSection) {
          hidden = kontaktSection.getBoundingClientRect().top < window.innerHeight;
        }
      }

      setBtnState({ opacity: scrollY >= pinAt ? 1 : opacity, top, show: true, buttonWidth, showExpandedText, hidden });
    };

    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  if (!btnState.show && btnState.opacity <= 0) return null;

  return (
    <div style={{
      position: 'fixed',
      top: `${btnState.top}px`,
      left: 0,
      right: 0,
      zIndex: 200,
      display: 'flex',
      justifyContent: 'center',
      opacity: btnState.opacity,
      pointerEvents: btnState.opacity > 0.1 && !btnState.hidden ? 'auto' : 'none',
      transform: btnState.hidden ? 'translateY(-80px)' : 'translateY(0)',
      transition: 'transform 0.35s cubic-bezier(0.22, 1, 0.36, 1)',
    }}>
      <button
        onClick={scrollToKontakt}
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          justifyContent: btnState.showExpandedText ? 'space-between' : 'center',
          gap: mobile ? '11px' : '13px',
          padding: mobile
            ? (btnState.showExpandedText ? '14px 28px' : '16px 24px')
            : (btnState.showExpandedText ? '19px 48px' : '19px 34px'),
          borderRadius: '999px',
          background: '#a6192e',
          color: '#ffffff',
          fontFamily: 'var(--sans)',
          fontSize: mobile ? '14px' : '15px',
          fontWeight: 400,
          border: 'none',
          cursor: 'pointer',
          letterSpacing: '0.02em',
          width: btnState.buttonWidth ? `${btnState.buttonWidth}px` : undefined,
          overflow: 'hidden',
          whiteSpace: btnState.showExpandedText ? 'normal' : 'nowrap',
        }}
      >
        {btnState.showExpandedText ? (
          <>
            <span style={{ maxWidth: '70%', lineHeight: 1.1, textAlign: 'left' }}>
              <strong style={{ fontWeight: 600 }}>LETNÍ AKCE:</strong> Sleva 30 % na kuchyně a 3 spotřebiče zdarma
            </span>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12h14M13 5l7 7-7 7"/>
            </svg>
          </>
        ) : (
          <>
            Nyní se slevou 30 %
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12h14M13 5l7 7-7 7"/>
            </svg>
          </>
        )}
      </button>
    </div>
  );
}

Object.assign(window, { Logo, Nav, Hero, InfoMarquee, FloatingCta, PromoBar, StickyPromoBtn, useIsMobile, scrollToKontakt });
