// Shared layout components: Header, Footer, Logo, Marquee, Reveal
// Exported to window so each page can use them.

const { useState, useEffect, useRef } = React;

// ---- Logo ----
function Logo({ inverted, dark }) {
  // dark=true forces white logo (used in footer/dark hero); inverted=true forces colored logo on light bg
  const useWhite = dark || !inverted;
  return (
    <a href="index.html" className="logo">
      <img
        src={useWhite ? "logo-white.png" : "logo-cropped.png"}
        alt="G Communities"
      />
    </a>
  );
}

// ---- Header ----
function Header({ active, theme = "dark" }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

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

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

  const links = [
    { label: "Home", href: "index.html", key: "home" },
    { label: "About", href: "about.html", key: "about" },
  ];

  const inverted = theme === "light" && !scrolled;

  return (
    <header
      className={`site-header ${scrolled ? "scrolled" : ""} ${theme === "light" ? "theme-light" : ""}`}
    >
      <div className="header-inner">
        <Logo inverted={inverted} dark={!inverted} />
        <nav
          className={`nav ${open ? "is-open" : ""}`}
          style={{ color: inverted && !open ? "#0a0a0a" : "#fafafa" }}
        >
          {open && (
            <button
              onClick={() => setOpen(false)}
              style={{
                position: "absolute",
                top: 24,
                right: 24,
                fontSize: 28,
                color: "#fafafa",
                width: 44,
                height: 44,
              }}
              aria-label="Close menu"
            >
              ×
            </button>
          )}
          {links.map((l) => (
            <a
              key={l.key}
              href={l.href}
              className={`nav-link ${active === l.key ? "is-active" : ""}`}
              onClick={() => setOpen(false)}
            >
              {l.label}
            </a>
          ))}
          <a
            href="contact.html"
            className="nav-cta"
            onClick={() => setOpen(false)}
          >
            Contact
          </a>
        </nav>
        <button
          className="menu-btn"
          onClick={() => setOpen(true)}
          aria-label="Open menu"
          style={{ color: inverted ? "#0a0a0a" : "#fafafa" }}
        >
          <svg width="22" height="14" viewBox="0 0 22 14" fill="none">
            <line
              x1="0"
              y1="1"
              x2="22"
              y2="1"
              stroke="currentColor"
              strokeWidth="1.2"
            />
            <line
              x1="0"
              y1="13"
              x2="22"
              y2="13"
              stroke="currentColor"
              strokeWidth="1.2"
            />
          </svg>
        </button>
      </div>
    </header>
  );
}

// ---- Reveal (intersection observer wrapper) ----
function Reveal({
  children,
  delay = 0,
  className = "",
  as: Tag = "div",
  ...rest
}) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setVisible(true);
          obs.disconnect();
        }
      },
      { threshold: 0.1, rootMargin: "0px 0px -10% 0px" },
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  return (
    <Tag
      ref={ref}
      className={`reveal ${visible ? "is-visible" : ""} ${className}`}
      style={{ transitionDelay: `${delay}ms` }}
      {...rest}
    >
      {children}
    </Tag>
  );
}

// ---- Animated text — line-clip reveal ----
function ClipLines({ lines, className = "", tag: Tag = "h1", delay = 0 }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setVisible(true);
          obs.disconnect();
        }
      },
      { threshold: 0.1 },
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return (
    <Tag ref={ref} className={`${className} ${visible ? "is-visible" : ""}`}>
      {lines.map((l, i) => (
        <span key={i} className="line-clip">
          <span style={{ transitionDelay: `${delay + i * 90}ms` }}>{l}</span>
        </span>
      ))}
    </Tag>
  );
}

// ---- Marquee ----
function Marquee({ items }) {
  const trackRef = useRef(null);
  const [width, setWidth] = useState(0);

  useEffect(() => {
    if (trackRef.current) {
      setWidth(trackRef.current.scrollWidth);
    }
  }, [items]);

  return (
    <div className="marquee">
      {width === 0 ? (
        // Invisible first render to measure
        <div ref={trackRef} className="marquee-track marquee-track--measure">
          {items.map((item, i) => (
            <span key={i} className="marquee-item">
              {item}
              <span className="dot"></span>
            </span>
          ))}
        </div>
      ) : (
        <div
          className="marquee-track"
          style={{ '--marquee-width': `${width}px` }}
        >
          {[...items, ...items].map((item, i) => (
            <span key={i} className="marquee-item">
              {item}
              <span className="dot"></span>
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

// ---- Arrow icon ----
function Arrow({ size = 18 }) {
  return (
    <svg
      className="arrow-icon"
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
    >
      <path
        d="M5 12h14M13 5l7 7-7 7"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

// ---- Down arrow ----
function DownArrow({ size = 24 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <path d="M12 5v14M5 13l7 7 7-7" stroke="currentColor" strokeWidth="1.2" />
    </svg>
  );
}

// ---- Footer ----
function Footer() {
  const year = new Date().getFullYear();
  return (
    <footer className="site-footer">
      <div style={{ maxWidth: 1400, margin: "0 auto", padding: "0 32px" }}>
        <div className="footer-grid">
          <div className="footer-col">
            <Logo dark={true} />
            <p
              style={{
                marginTop: 24,
                color: "var(--fg-muted)",
                fontSize: 14,
                lineHeight: 1.6,
                maxWidth: 320,
              }}
            >
              The lifestyle and community-management arm of G Group. Stewarding
              the daily rhythm of the places we call home.
            </p>
          </div>
          <div className="footer-col"></div>
          <div className="footer-col">
            <h4>Explore</h4>
            <a href="index.html">Home</a>
            <a href="about.html">About</a>
            <a href="contact.html">Contact</a>
          </div>
          <div className="footer-col">
            <h4>Get in Touch</h4>
            <p
              style={{
                color: "var(--fg-muted)",
                fontSize: 13,
                marginTop: 4,
                marginBottom: 2,
              }}
            >
              Call center
            </p>
            <a href="tel:0238277933">0238277933</a>
          </div>
        </div>

        <div className="footer-bottom">
          <p>© {year} G Communities. All rights reserved.</p>
        </div>
      </div>
    </footer>
  );
}

// Export to window
Object.assign(window, {
  Logo,
  Header,
  Footer,
  Reveal,
  ClipLines,
  Marquee,
  Arrow,
  DownArrow,
});
