// components.jsx — Icons, nav, footer, cart drawer, shared UI
// Components are exported to window so sections.jsx can use them.

/* =========================================================
   Icons — minimal stroke set
   ========================================================= */
const Ic = {
  search: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <circle cx="11" cy="11" r="7" />
      <path d="m20 20-3.5-3.5" />
    </svg>
  ),
  user: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <circle cx="12" cy="8" r="4" />
      <path d="M4 20c1.6-4 5-6 8-6s6.4 2 8 6" />
    </svg>
  ),
  bag: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <path d="M6 8h12l-1 12H7L6 8Z" />
      <path d="M9 8a3 3 0 0 1 6 0" />
    </svg>
  ),
  heart: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <path d="M12 20s-7-4.4-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 10c0 5.6-7 10-7 10Z" />
    </svg>
  ),
  heartFill: (p) => (
    <svg viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M12 20s-7-4.4-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 10c0 5.6-7 10-7 10Z" />
    </svg>
  ),
  arrow: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <path d="M5 12h14M14 6l6 6-6 6" />
    </svg>
  ),
  star: (p) => (
    <svg viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="m12 2 2.9 6.6 7.1.7-5.3 4.8 1.6 7-6.3-3.7-6.3 3.7 1.6-7L2 9.3l7.1-.7L12 2Z" />
    </svg>
  ),
  plus: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}>
      <path d="M12 5v14M5 12h14" />
    </svg>
  ),
  minus: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}>
      <path d="M5 12h14" />
    </svg>
  ),
  close: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <path d="m6 6 12 12M18 6 6 18" />
    </svg>
  ),
  slider: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <path d="M5 12h14M9 8l-4 4 4 4M15 8l4 4-4 4" />
    </svg>
  ),
  /* Benefit icons */
  collagen: (p) => (
    <svg viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="1.2" {...p}>
      <path d="M14 12c8 6 28 6 36 0" />
      <path d="M14 22c8 6 28 6 36 0" />
      <path d="M14 32c8 6 28 6 36 0" />
      <path d="M14 42c8 6 28 6 36 0" />
      <path d="M14 52c8 6 28 6 36 0" />
      <path d="M14 12v40M22 12v40M32 12v40M42 12v40M50 12v40" strokeOpacity=".35" />
    </svg>
  ),
  hydration: (p) => (
    <svg viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="1.2" {...p}>
      <path d="M32 8c8 11 14 19 14 28a14 14 0 0 1-28 0c0-9 6-17 14-28Z" />
      <path d="M24 36c0 5 3 8 8 8" strokeOpacity=".5" />
    </svg>
  ),
  shield: (p) => (
    <svg viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="1.2" {...p}>
      <path d="M32 8 12 16v12c0 14 8 24 20 28 12-4 20-14 20-28V16L32 8Z" />
      <path d="M22 30l8 8 14-14" strokeOpacity=".5" />
    </svg>
  ),
  clock: (p) => (
    <svg viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="1.2" {...p}>
      <circle cx="32" cy="32" r="22" />
      <path d="M32 18v14l10 6" />
      <circle cx="32" cy="32" r="1.5" fill="currentColor" />
    </svg>
  ),
};

/* =========================================================
   Brand mark — simplified V + helix
   ========================================================= */
function BrandMark({ size = 32, dark = false }) {
  const stroke = dark ? '#0E3D2E' : '#C9A47A';
  const v = dark ? '#0E3D2E' : '#0E3D2E';
  return (
    <svg viewBox="0 0 64 64" width={size} height={size}>
      {/* Arc */}
      <path d="M40 8 C 56 16, 56 48, 40 56" fill="none" stroke={stroke} strokeWidth="2" strokeLinecap="round" />
      {/* V */}
      <path
        d="M14 14 L 28 50 L 42 14"
        fill="none"
        stroke={v}
        strokeWidth="3.5"
        strokeLinejoin="round"
        strokeLinecap="round"
      />
      {/* Helix rungs */}
      <g stroke={stroke} strokeWidth="1.5" strokeLinecap="round">
        <path d="M34 18 Q 40 22, 46 18" />
        <path d="M34 26 Q 40 30, 46 26" />
        <path d="M34 34 Q 40 38, 46 34" />
        <path d="M34 42 Q 40 46, 46 42" />
      </g>
    </svg>
  );
}

/* =========================================================
   Authenticity seal — used in hero
   ========================================================= */
function AuthSeal() {
  return (
    <svg viewBox="0 0 200 200">
      <defs>
        <path id="auth-curve" d="M100,100 m-78,0 a78,78 0 1,1 156,0 a78,78 0 1,1 -156,0" />
        <linearGradient id="auth-bg" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="#FBF8F3" />
          <stop offset="50%" stopColor="#F4EEE4" />
          <stop offset="100%" stopColor="#E3CDAE" />
        </linearGradient>
      </defs>
      <circle cx="100" cy="100" r="96" fill="url(#auth-bg)" stroke="#C9A47A" strokeWidth=".8" />
      <circle cx="100" cy="100" r="86" fill="none" stroke="#0E3D2E" strokeOpacity=".5" strokeWidth=".5" />
      <circle cx="100" cy="100" r="58" fill="none" stroke="#0E3D2E" strokeOpacity=".4" strokeWidth=".5" />
      <text fontSize="11" letterSpacing="3" fontFamily="Inter" fontWeight="500" fill="#0E3D2E">
        <textPath href="#auth-curve" startOffset="0">
          VELORA · BIOPEPTIDE SCIENCES · CERTIFIED PURE ·{' '}
        </textPath>
      </text>
      {/* center */}
      <text
        x="100"
        y="92"
        textAnchor="middle"
        fontFamily="Cormorant Garamond"
        fontSize="28"
        fill="#0E3D2E"
        letterSpacing="2"
      >
        V
      </text>
      <line x1="60" y1="108" x2="140" y2="108" stroke="#C9A47A" strokeWidth=".6" />
      <text x="100" y="124" textAnchor="middle" fontFamily="Inter" fontSize="8" fill="#0E3D2E" letterSpacing="2">
        AUTHENTIC
      </text>
      <text
        x="100"
        y="136"
        textAnchor="middle"
        fontFamily="Inter"
        fontSize="6.5"
        fill="#0E3D2E"
        opacity=".6"
        letterSpacing="1.5"
      >
        PURITY · INTEGRITY
      </text>
    </svg>
  );
}

/* =========================================================
   Vial visualisation — drawn in SVG, color-coded by product
   ========================================================= */
function Vial({ accent = '#7A5BC7', label = 'NAD+', strength = '500mg', angle = 0, scale = 1 }) {
  // accent = cap color
  return (
    <svg
      viewBox="0 0 200 320"
      style={{ transform: `rotate(${angle}deg) scale(${scale})`, transformOrigin: 'center', width: '120px' }}
    >
      <defs>
        <linearGradient id={`vialGlass-${label}`} x1="0" x2="1" y1="0" y2="0">
          <stop offset="0%" stopColor="rgba(255,255,255,.95)" />
          <stop offset="35%" stopColor="rgba(255,255,255,.55)" />
          <stop offset="55%" stopColor="rgba(220,220,210,.4)" />
          <stop offset="80%" stopColor="rgba(255,255,255,.65)" />
          <stop offset="100%" stopColor="rgba(180,180,165,.55)" />
        </linearGradient>
        <linearGradient id={`cap-${label}`} x1="0" x2="1" y1="0" y2="0">
          <stop offset="0%" stopColor={accent} stopOpacity=".75" />
          <stop offset="40%" stopColor={accent} />
          <stop offset="60%" stopColor={accent} />
          <stop offset="100%" stopColor={accent} stopOpacity=".6" />
        </linearGradient>
        <linearGradient id={`silver-${label}`} x1="0" x2="1" y1="0" y2="0">
          <stop offset="0%" stopColor="#9a9a92" />
          <stop offset="50%" stopColor="#e8e6df" />
          <stop offset="100%" stopColor="#8a8a82" />
        </linearGradient>
      </defs>
      {/* shadow */}
      <ellipse cx="100" cy="298" rx="58" ry="8" fill="rgba(14,61,46,.18)" />
      {/* colored cap (top) */}
      <rect
        x="68"
        y="22"
        width="64"
        height="22"
        rx="3"
        fill={`url(#cap-${label})`}
        stroke="rgba(0,0,0,.18)"
        strokeWidth=".6"
      />
      <ellipse cx="100" cy="22" rx="32" ry="4" fill={accent} opacity=".85" />
      {/* silver crimp */}
      <rect
        x="64"
        y="42"
        width="72"
        height="18"
        rx="2"
        fill={`url(#silver-${label})`}
        stroke="rgba(0,0,0,.18)"
        strokeWidth=".5"
      />
      <rect x="64" y="42" width="72" height="2" fill="rgba(0,0,0,.18)" />
      <rect x="64" y="56" width="72" height="2" fill="rgba(0,0,0,.18)" />
      {/* neck */}
      <path
        d="M76 60 L74 76 L126 76 L124 60 Z"
        fill={`url(#vialGlass-${label})`}
        stroke="rgba(0,0,0,.12)"
        strokeWidth=".6"
      />
      {/* body */}
      <rect
        x="62"
        y="76"
        width="76"
        height="208"
        rx="5"
        fill={`url(#vialGlass-${label})`}
        stroke="rgba(0,0,0,.16)"
        strokeWidth=".8"
        style={{ width: '74px' }}
      />
      {/* meniscus / liquid */}
      <path d="M62 100 Q 100 92, 138 100 L 138 110 Q 100 102, 62 110 Z" fill="rgba(255,255,255,.4)" />
      {/* label */}
      <rect x="68" y="124" width="64" height="124" rx="2" fill="#FCFAF5" stroke="rgba(0,0,0,.08)" />
      <text
        x="100"
        y="142"
        textAnchor="middle"
        fontFamily="Cormorant Garamond"
        fontSize="13"
        fill="#0E3D2E"
        letterSpacing="1.5"
        fontWeight="600"
      >
        VELORA
      </text>
      <line x1="78" y1="148" x2="122" y2="148" stroke="#C9A47A" strokeWidth=".4" />
      <text x="100" y="158" textAnchor="middle" fontFamily="Inter" fontSize="4.5" fill="#A8855A" letterSpacing=".5">
        BIOPEPTIDE SCIENCES
      </text>
      <text
        x="100"
        y="190"
        textAnchor="middle"
        fontFamily="Cormorant Garamond"
        fontWeight="600"
        fontSize={label.length > 5 ? 16 : label.length > 4 ? 18 : 22}
        fill="#0E3D2E"
      >
        {label}
      </text>
      <rect x="78" y="200" width="44" height="14" rx="2" fill={accent} />
      <text x="100" y="210" textAnchor="middle" fontFamily="Inter" fontWeight="600" fontSize="8" fill="#FCFAF5">
        {strength}
      </text>
      <text x="100" y="226" textAnchor="middle" fontFamily="Inter" fontSize="4.5" fill="#0E3D2E" letterSpacing=".5">
        LYOPHILIZED POWDER
      </text>
      <text x="100" y="234" textAnchor="middle" fontFamily="Inter" fontSize="4" fill="#6A6A60" letterSpacing=".4">
        For Professional Use Only
      </text>
      <line x1="78" y1="240" x2="122" y2="240" stroke="rgba(0,0,0,.1)" strokeWidth=".3" />
      <text x="100" y="250" textAnchor="middle" fontFamily="Inter" fontSize="4" fill="#6A6A60">
        3ml · Multi-dose Vial
      </text>
      {/* highlight */}
      <rect x="66" y="80" width="6" height="200" rx="3" fill="rgba(255,255,255,.7)" />
      <rect x="128" y="80" width="3" height="200" rx="2" fill="rgba(255,255,255,.4)" />
    </svg>
  );
}

/* =========================================================
   Nav — showcase only (no cart / search / account)
   ========================================================= */
function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => {
      document.body.style.overflow = '';
    };
  }, [menuOpen]);

  const closeMenu = () => setMenuOpen(false);

  return (
    <>
      <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
        <div className="wrap-wide nav-inner">
          <div className="nav-left">
            <a href="#top" className="nav-link">
              Home
            </a>
            <a href="#about" className="nav-link">
              About
            </a>
            <a href="#science" className="nav-link">
              Science
            </a>
          </div>
          <a href="#top" className="nav-logo">
            <BrandMark size={30} dark />
            <span>VELORA</span>
          </a>
          <div className="nav-right">
            <a href="#products" className="nav-link">
              Products
            </a>
            <a href="#reviews" className="nav-link">
              Reviews
            </a>
            <a href="#contact" className="nav-link">
              Contact
            </a>
          </div>
          <button
            type="button"
            className={`nav-burger ${menuOpen ? 'open' : ''}`}
            onClick={() => setMenuOpen((o) => !o)}
            aria-label={menuOpen ? 'Close menu' : 'Open menu'}
            aria-expanded={menuOpen}
          >
            <span />
            <span />
            <span />
          </button>
        </div>
      </nav>

      <div className={`nav-mobile-scrim ${menuOpen ? 'open' : ''}`} onClick={closeMenu} aria-hidden="true" />
      <aside className={`nav-mobile-menu ${menuOpen ? 'open' : ''}`} aria-hidden={!menuOpen}>
        <div className="nav-mobile-hd">
          <BrandMark size={28} dark />
          <span className="nav-mobile-brand">VELORA</span>
        </div>
        <nav className="nav-mobile-inner">
          <a href="#top" className="nav-mobile-link" onClick={closeMenu}>
            Home
          </a>
          <a href="#about" className="nav-mobile-link" onClick={closeMenu}>
            About
          </a>
          <a href="#products" className="nav-mobile-link" onClick={closeMenu}>
            Products
          </a>
          <a href="#science" className="nav-mobile-link" onClick={closeMenu}>
            The Science
          </a>
          <a href="#showcase" className="nav-mobile-link" onClick={closeMenu}>
            Showcase
          </a>
          <a href="#results" className="nav-mobile-link" onClick={closeMenu}>
            Results
          </a>
          <a href="#reviews" className="nav-mobile-link" onClick={closeMenu}>
            Reviews
          </a>
          <a href="#contact" className="nav-mobile-link" onClick={closeMenu}>
            Contact
          </a>
        </nav>
        <div className="nav-mobile-foot">
          <span className="nav-mobile-foot-note">— BioPeptide Sciences —</span>
        </div>
      </aside>
    </>
  );
}

// (Cart drawer removed — showcase only.)

/* =========================================================
   NavWithLogo — drop-in replacement for <Nav/> that uses an
   image logo (uploads/logo.png) in place of the BrandMark
   + "VELORA" wordmark. Same nav-links, same mobile menu,
   same scroll/burger behaviour.

   To enable when the client provides the final logo:
     1. In app.jsx, comment out  <Nav/>  and put  <NavWithLogo/>
        in its place.
     2. (Optional) Adjust .nav-logo-img height in styles.css if
        you want the logo larger / smaller.
   ========================================================= */
function NavWithLogo() {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => {
      document.body.style.overflow = '';
    };
  }, [menuOpen]);

  const closeMenu = () => setMenuOpen(false);

  return (
    <>
      <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
        <div className="wrap-wide nav-inner">
          <div className="nav-left">
            <a href="#top" className="nav-link">
              Home
            </a>
            <a href="#about" className="nav-link">
              About
            </a>
            <a href="#science" className="nav-link">
              Science
            </a>
          </div>
          <a href="#top" className="nav-logo nav-logo-image" aria-label="Velora — home">
            <img src="uploads/logo.png" alt="Velora" className="nav-logo-img" />
          </a>
          <div className="nav-right">
            <a href="#products" className="nav-link">
              Products
            </a>
            <a href="#reviews" className="nav-link">
              Reviews
            </a>
            <a href="#contact" className="nav-link">
              Contact
            </a>
          </div>
          <button
            type="button"
            className={`nav-burger ${menuOpen ? 'open' : ''}`}
            onClick={() => setMenuOpen((o) => !o)}
            aria-label={menuOpen ? 'Close menu' : 'Open menu'}
            aria-expanded={menuOpen}
          >
            <span />
            <span />
            <span />
          </button>
        </div>
      </nav>

      <div className={`nav-mobile-scrim ${menuOpen ? 'open' : ''}`} onClick={closeMenu} aria-hidden="true" />
      <aside className={`nav-mobile-menu ${menuOpen ? 'open' : ''}`} aria-hidden={!menuOpen}>
        <button className="nav-mobile-close" onClick={closeMenu} aria-label="Close menu">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
            <path d="M6 6l12 12M18 6L6 18" />
          </svg>
        </button>
        <div className="nav-mobile-hd nav-mobile-hd-image">
          <img src="uploads/logo.png" alt="Velora" className="nav-mobile-logo-img" />
        </div>
        <nav className="nav-mobile-inner">
          <a href="#top" className="nav-mobile-link" onClick={closeMenu}>
            Home
          </a>
          <a href="#about" className="nav-mobile-link" onClick={closeMenu}>
            About
          </a>
          <a href="#products" className="nav-mobile-link" onClick={closeMenu}>
            Products
          </a>
          <a href="#science" className="nav-mobile-link" onClick={closeMenu}>
            The Science
          </a>
          <a href="#showcase" className="nav-mobile-link" onClick={closeMenu}>
            Showcase
          </a>
          <a href="#results" className="nav-mobile-link" onClick={closeMenu}>
            Results
          </a>
          <a href="#reviews" className="nav-mobile-link" onClick={closeMenu}>
            Reviews
          </a>
          <a href="#contact" className="nav-mobile-link" onClick={closeMenu}>
            Contact
          </a>
        </nav>
        <div className="nav-mobile-foot">
          <span className="nav-mobile-foot-note">— BioPeptide Sciences —</span>
        </div>
      </aside>
    </>
  );
}

/* =========================================================
   Footer
   ========================================================= */
function Footer() {
  return (
    <footer className="footer">
      <div className="wrap-wide">
        <div className="footer-grid">
          <div>
            <div className="footer-brand">VELORA</div>
            <div className="footer-tag">— BioPeptide Sciences —</div>
            <p className="footer-blurb">
              Precision peptide formulations born of laboratory rigor and the unhurried art of luxury skincare.
            </p>
            <div className="footer-socials">
              <a
                href="https://www.facebook.com/people/Velorabiopeptide/61590647421475/"
                target="_blank"
                rel="noreferrer"
                aria-label="Facebook"
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M13 22v-8h3l.5-4H13V7.5c0-1.2.3-2 2-2h2V2.1C16.7 2 15.6 2 14.5 2 11.8 2 10 3.7 10 6.9V10H7v4h3v8h3z" />
                </svg>
              </a>
              <a href="https://instagram.com/velora.biopeptide" target="_blank" rel="noreferrer" aria-label="Instagram">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
                  <rect x="3" y="3" width="18" height="18" rx="5" />
                  <circle cx="12" cy="12" r="4" />
                  <circle cx="17.5" cy="6.5" r="1" fill="currentColor" />
                </svg>
              </a>
              <a href="https://tiktok.com/@velorabiopeptide" target="_blank" rel="noreferrer" aria-label="TikTok">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M14 4v9.5a3 3 0 1 1-3-3v3a.5.5 0 1 0 .5.5V4h2.5a3.5 3.5 0 0 0 3 3v2.5a5.5 5.5 0 0 1-3-1V4Z" />
                </svg>
              </a>
              <a href="#" aria-label="Viber">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M12 2C6.5 2 2 5.7 2 10.5c0 2.5 1.3 4.8 3.4 6.3v3.7l3.3-2c1 .2 2.1.3 3.3.3 5.5 0 10-3.7 10-8.3S17.5 2 12 2Zm-2.8 4.6c.3-.2.8-.1 1 .2l.8 1c.2.3.2.7-.1 1l-.5.5c-.2.2-.2.5-.1.7l1.5 2c.2.3.5.3.7.1l.4-.4c.3-.3.8-.2 1.1.1l.6.8c.2.3.5.4.8.2l.7-.4c.4-.2.8-.2 1.1.1l1.6 1.6c.3.3.4.7.2 1l-.5.8c-.3.5-.9.6-1.4.4-3-1.1-5-3.2-6-6-.2-.5 0-1.1.5-1.4l.7-.4Z" />
                </svg>
              </a>
            </div>
          </div>
          <div>
            <h5>Browse</h5>
            <a href="#products">Products</a>
            <a href="#showcase">Showcase</a>
            <a href="#science">The Science</a>
            <a href="#results">Results</a>
          </div>
          <div>
            <h5>Reach Us</h5>
            <a href="#contact">Contact</a>
            <a href="#reviews">Reviews</a>
            <a href="mailto:hello@velorabiopeptide.com">hello@velorabiopeptide.com</a>
          </div>
        </div>
        <div className="footer-bot">
          <span>© 2026 Velora BioPeptide Sciences · For Professional Use Only</span>
        </div>
      </div>
    </footer>
  );
}

/* =========================================================
   Reveal — CSS-animation wrapper (always visible, fades in)
   ========================================================= */
function Reveal({ children, delay = 0, as: As = 'div', ...rest }) {
  const cn = `reveal ${delay ? `reveal-delay-${delay}` : ''} ${rest.className || ''}`;
  return (
    <As {...rest} className={cn}>
      {children}
    </As>
  );
}

/* =========================================================
   MessengerWidget — Floating chat button (lower-right)
   Uses m.me deep link. Replace MSGR_HANDLE with the real
   Facebook Page username when ready.
   ========================================================= */
const MSGR_HANDLE = 'veloramainexclusive';
const MSGR_ID = '61590148993303';
const MSGR_WEB_URL = `https://www.facebook.com/messages/t/${MSGR_ID}`;
const MSGR_APP_URL = `fb-messenger://user-thread/${MSGR_ID}`;

// On mobile (iOS/Android), try to launch the Messenger app directly.
// Fall back to the web URL if the app doesn't open. On desktop, the
// default <a target="_blank"> behavior handles opening in a new tab.
function openMessengerChat(e) {
  const ua = (typeof navigator !== 'undefined' && navigator.userAgent) || '';
  const isIOS = /iPad|iPhone|iPod/.test(ua) && !window.MSStream;
  const isAndroid = /Android/.test(ua);
  if (!isIOS && !isAndroid) return;

  if (e && e.preventDefault) e.preventDefault();

  let appOpened = false;
  const onVisChange = () => {
    if (document.hidden) appOpened = true;
  };
  document.addEventListener('visibilitychange', onVisChange);

  window.location.href = MSGR_APP_URL;

  setTimeout(() => {
    document.removeEventListener('visibilitychange', onVisChange);
    if (!appOpened && !document.hidden) {
      window.location.href = MSGR_WEB_URL;
    }
  }, 1500);
}

function MessengerLogo({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true">
      <path
        fill="currentColor"
        d="M12 2C6.5 2 2 6.2 2 11.4c0 2.9 1.4 5.5 3.6 7.2V22l3.3-1.8c.9.3 1.9.4 3 .4 5.5 0 10-4.2 10-9.4S17.5 2 12 2Zm1 12.5-2.6-2.7-5 2.7 5.5-5.8 2.6 2.7 5-2.7-5.5 5.8Z"
      />
    </svg>
  );
}

function MessengerWidget() {
  const [open, setOpen] = React.useState(false);
  const [seen, setSeen] = React.useState(false);
  const msgrUrl = `https://www.facebook.com/messages/t/${MSGR_ID}`;

  React.useEffect(() => {
    if (open) setSeen(true);
  }, [open]);

  return (
    <div className="msgr-root" aria-live="polite">
      <div className={`msgr-card ${open ? 'open' : ''}`} role="dialog" aria-label="Velora Messenger preview">
        <div className="msgr-card-hd">
          <div className="msgr-card-avatar">
            <MessengerLogo size={22} />
          </div>
          <div className="msgr-card-who">
            <b>Velora Concierge</b>
            <span>
              <i className="msgr-dot-live" /> Online · replies within 12h
            </span>
          </div>
          <button className="msgr-card-x" onClick={() => setOpen(false)} aria-label="Close">
            ×
          </button>
        </div>
        <div className="msgr-card-body">
          <div className="msgr-bubble">
            Hi! Welcome to <b>Velora BioPeptide Sciences</b>. Tap below to continue this chat on Messenger — we'll help
            you choose the right protocol.
          </div>
        </div>
        {/*
        <a className="msgr-card-cta" href={msgrUrl} target="_blank" rel="noopener noreferrer">
          <MessengerLogo size={18} /> Continue on Messenger
        </a>
        */}
        <a
          className="msgr-card-cta"
          href={msgrUrl}
          target="_blank"
          rel="noopener noreferrer"
          onClick={openMessengerChat}
        >
          <MessengerLogo size={18} /> Continue on Messenger
        </a>
        <span className="msgr-card-foot">Powered by Facebook Messenger</span>
      </div>

      <button
        type="button"
        className={`msgr-fab ${open ? 'is-open' : ''}`}
        onClick={() => setOpen((o) => !o)}
        aria-expanded={open}
        aria-label={open ? 'Close Messenger preview' : 'Chat with Velora on Messenger'}
      >
        <span className="msgr-fab-icon">
          {open ? (
            <svg width="22" height="22" viewBox="0 0 24 24" aria-hidden="true">
              <path
                fill="currentColor"
                d="M18.3 5.7 12 12l6.3 6.3-1.4 1.4L10.6 13.4 4.3 19.7 2.9 18.3 9.2 12 2.9 5.7 4.3 4.3l6.3 6.3 6.3-6.3z"
              />
            </svg>
          ) : (
            <MessengerLogo size={26} />
          )}
        </span>
        {!open && !seen && <span className="msgr-fab-ping" />}
        <span className="msgr-fab-tip">Chat with us</span>
      </button>
    </div>
  );
}

/* =========================================================
   ScrollTopButton — Floating "back to top" (lower-right,
   stacked above the Messenger FAB). Appears only after the
   user has scrolled past the threshold.
   ========================================================= */
function ScrollTopButton() {
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    const THRESHOLD = 400;
    const onScroll = () => setVisible(window.scrollY > THRESHOLD);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const toTop = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <button
      type="button"
      className={`scroll-top-fab ${visible ? 'show' : ''}`}
      onClick={toTop}
      aria-label="Scroll back to top"
      aria-hidden={!visible}
      tabIndex={visible ? 0 : -1}
    >
      <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
        <path
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          d="M12 19V5M5 12l7-7 7 7"
        />
      </svg>
    </button>
  );
}

Object.assign(window, {
  Ic,
  BrandMark,
  AuthSeal,
  Vial,
  Nav,
  NavWithLogo,
  Footer,
  Reveal,
  MessengerWidget,
  ScrollTopButton,
});
