// ============================================================
// Shared components: Header, Footer, MobileDrawer, CollectionCard, Reveal
// ============================================================

const { useState, useEffect, useRef } = React;

// Reveal-on-scroll hook
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (typeof IntersectionObserver === "undefined") {
      el.classList.add("in");
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

function Reveal({ children, delay = 0, as: As = "div", className = "", ...rest }) {
  const ref = useReveal();
  return (
    <As
      ref={ref}
      className={`reveal ${className}`}
      style={{ transitionDelay: `${delay}ms` }}
      {...rest}
    >
      {children}
    </As>
  );
}

// Header — sticky, optionally dark variant
function Header({ route, navigate, dark = false }) {
  const [scrolled, setScrolled] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);

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

  const links = [
    { route: "restaurante", label: "Restaurante" },
    { route: "cafenele", label: "Cafenele" },
    { route: "hoteluri", label: "Hoteluri" },
    { route: "colectii", label: "Colecții" },
    { route: "despre", label: "Despre" },
  ];

  const go = (e, r) => {
    e.preventDefault();
    setDrawerOpen(false);
    navigate(r);
  };

  return (
    <React.Fragment>
      <header className={`site-header ${scrolled ? "scrolled" : ""} ${dark ? "on-dark" : ""}`}>
        <div className="container-wide header-row">
          <a className="brand" href="#home" onClick={(e) => go(e, "home")}>
            <span className="brand-mark">
              OWITHU<span className="accent">.</span>
            </span>
            <span className="brand-sub">Table Solutions · HoReCa</span>
          </a>
          <nav className="main-nav">
            {links.map((l) => (
              <a
                key={l.route}
                href={`#${l.route}`}
                onClick={(e) => go(e, l.route)}
                className={`nav-link ${route === l.route ? "active" : ""}`}
              >
                {l.label}
              </a>
            ))}
          </nav>
          <div className="nav-actions">
            <a className="btn btn-primary btn-sm" href="#oferta" onClick={(e) => go(e, "oferta")}>
              Cere ofertă <span className="arrow">→</span>
            </a>
            <button
              className="mobile-toggle"
              onClick={() => setDrawerOpen(true)}
              aria-label="Deschide meniu"
            >
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
                <line x1="3" y1="7" x2="21" y2="7" />
                <line x1="3" y1="12" x2="21" y2="12" />
                <line x1="3" y1="17" x2="21" y2="17" />
              </svg>
            </button>
          </div>
        </div>
      </header>

      <div className={`mobile-drawer ${drawerOpen ? "open" : ""}`}>
        <button
          className="mobile-drawer-close"
          onClick={() => setDrawerOpen(false)}
          aria-label="Închide meniu"
        >
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
            <line x1="6" y1="6" x2="18" y2="18" />
            <line x1="18" y1="6" x2="6" y2="18" />
          </svg>
        </button>
        <div style={{ maxWidth: 320 }}>
          {links.map((l) => (
            <a key={l.route} href={`#${l.route}`} className="nav-link" onClick={(e) => go(e, l.route)}>
              {l.label}
            </a>
          ))}
          <a
            className="btn btn-gold"
            href="#oferta"
            onClick={(e) => go(e, "oferta")}
            style={{ marginTop: 24 }}
          >
            Cere ofertă <span className="arrow">→</span>
          </a>
        </div>
      </div>
    </React.Fragment>
  );
}

// Footer
function Footer({ navigate }) {
  const go = (e, r) => {
    e.preventDefault();
    navigate(r);
  };
  return (
    <footer className="site-footer">
      <div className="container-wide">
        <div className="footer-grid">
          <div>
            <div className="footer-brand">OWITHU<span className="accent">.</span></div>
            <p style={{ color: "var(--silver-300)", maxWidth: 360, fontSize: 14, lineHeight: 1.55 }}>
              Soluții complete de vesela pentru restaurante, cafenele și hoteluri. Servicii complete, ofertă personalizată — fără minim de comandă afișat public.
            </p>
            <a
              className="btn btn-gold"
              href="#oferta"
              onClick={(e) => go(e, "oferta")}
              style={{ marginTop: 24 }}
            >
              Solicită ofertă <span className="arrow">→</span>
            </a>
          </div>
          <div>
            <h4>Segmente</h4>
            <a href="#restaurante" onClick={(e) => go(e, "restaurante")}>Restaurante</a>
            <a href="#cafenele" onClick={(e) => go(e, "cafenele")}>Cafenele</a>
            <a href="#hoteluri" onClick={(e) => go(e, "hoteluri")}>Hoteluri</a>
            <a href="#colectii" onClick={(e) => go(e, "colectii")}>Toate colecțiile</a>
          </div>
          <div>
            <h4>Companie</h4>
            <a href="#despre" onClick={(e) => go(e, "despre")}>Despre Owithu</a>
            <a href="#despre" onClick={(e) => go(e, "despre")}>Cum lucrăm</a>
            <a href="#oferta" onClick={(e) => go(e, "oferta")}>Cerere de ofertă</a>
          </div>
          <div>
            <h4>Contact</h4>
            <span style={{ display: "block", padding: "4px 0", color: "var(--silver-300)" }}>
              office@<span style={{ color: "var(--mustard)" }}>owithu</span>.placeholder
            </span>
            <span style={{ display: "block", padding: "4px 0" }}>+40 7XX XXX XXX</span>
            <span style={{ display: "block", padding: "4px 0" }}>București · România</span>
            <span style={{ display: "block", padding: "12px 0 4px", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--silver-500)" }}>
              L–V · 09:00–18:00
            </span>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© Owithu Management · 2026 · Demo prezentare client</div>
          <div style={{ display: "flex", gap: 24 }}>
            <a href="#" onClick={(e) => e.preventDefault()}>Termeni</a>
            <a href="#" onClick={(e) => e.preventDefault()}>Confidențialitate</a>
            <a href="#" onClick={(e) => e.preventDefault()}>GDPR</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// Collection card — used in grids
function CollectionCard({ collection, navigate, badge }) {
  const hasAlt = collection.images && collection.images.length > 1;
  const altImg = hasAlt ? collection.images[1] : null;
  return (
    <a
      className="collection-card"
      href={`#colectie/${collection.slug}`}
      onClick={(e) => {
        e.preventDefault();
        navigate(`colectie/${collection.slug}`);
      }}
    >
      <div className="img-wrap">
        <img
          className="cc-img cc-img-base"
          src={collection.images[0]}
          alt={`${collection.name} ${collection.finish}`}
          loading="lazy"
        />
        {hasAlt && (
          <img
            className="cc-img cc-img-alt"
            src={altImg}
            alt=""
            aria-hidden="true"
            loading="lazy"
          />
        )}
        {badge && <span className="img-badge">{badge}</span>}
      </div>
      <div>
        <div className="name-row">
          <h3 className="name">{collection.name}</h3>
          <span className="finish">{collection.finish}</span>
        </div>
        <div className="specs-row" style={{ marginTop: 8 }}>
          <span>
            <span className="dot" style={{ background: collection.swatch }}></span>
            {collection.palette}
          </span>
        </div>
        <div className="specs-row" style={{ marginTop: 6 }}>
          <span><span className="dot"></span>{collection.pieces} piese</span>
          <span><span className="dot"></span>{collection.persons} persoane</span>
        </div>
        <div className="cta-row" style={{ marginTop: 12 }}>
          Vezi detalii <span className="arrow">→</span>
        </div>
      </div>
    </a>
  );
}

// Promise/values row used on homepage + industry pages
function PromiseRow() {
  const items = [
    { num: "01", title: "Servicii complete", body: "Aranjament pentru 4–6 persoane, livrat ca un singur set: farfurii, boluri, căni, cești." },
    { num: "02", title: "Catalog stabil", body: "Aceeași colecție se reaprovizionează: piesele înlocuite păstrează identitatea mesei." },
    { num: "03", title: "Compatibilitate HoReCa", body: "Mașină de spălat vase, microunde, cuptor — finisaje verificate pentru frecvență mare." },
    { num: "04", title: "Ofertă personalizată", body: "Cantitatea, locația și tipul de operare se discută individual — fără preț listat public." },
  ];
  return (
    <div className="promise-grid">
      {items.map((it) => (
        <div className="promise-cell" key={it.num}>
          <span className="num">{it.num}</span>
          <h4>{it.title}</h4>
          <p>{it.body}</p>
        </div>
      ))}
    </div>
  );
}

// Marquee strip of collection names
function CollectionMarquee() {
  const names = ["Genesis", "Iris", "Magma", "Scandi", "Gourmet", "Moon", "Oxygen", "Cosmos", "Stellar", "Zen", "Island", "Cloud", "Stone", "Napoli", "Pure"];
  const items = [];
  for (let i = 0; i < 2; i++) {
    names.forEach((n, j) => {
      items.push(
        <React.Fragment key={`${i}-${j}`}>
          <span>{n}</span>
          <span className="sep">·</span>
        </React.Fragment>
      );
    });
  }
  return (
    <div className="marquee">
      <div className="marquee-track">{items}</div>
    </div>
  );
}

window.OwithuComponents = {
  Header, Footer, CollectionCard, PromiseRow, CollectionMarquee, Reveal, useReveal,
};
