// shared.jsx — Logo, Nav, Footer, media placeholders, shared primitives.

const { useState, useEffect, useRef } = React;

// ─── Logo ──────────────────────────────────────────────────────────────────
function Logo({ tone = "light", size = "sm" }) {
  // tone "light" = white text + gold rules (use on dark bg)
  // tone "dark"  = ink text + gold rules (use on light bg)
  const ink = tone === "light" ? "#FFFFFF" : "#111111";
  const gold = tone === "light" ? "#D4A830" : "#B8891A";
  const wordSize = size === "lg" ? 66 : size === "md" ? 26 : 12;
  const wordSpacing = size === "lg" ? "0.19em" : size === "md" ? "0.17em" : "0.145em";
  const subSize = size === "lg" ? 19 : size === "md" ? 10.5 : 6.2;
  const subSpacing = size === "lg" ? "0.06em" : size === "md" ? "0.07em" : "0.075em";
  const ruleW = size === "lg" ? 132 : size === "md" ? 58 : 24;
  return (
    <div style={{ display: "inline-flex", flexDirection: "column", alignItems: "center", lineHeight: 1, background: "transparent" }}>
      <div
        style={{
          color: ink,
          fontWeight: 500,
          letterSpacing: wordSpacing,
          fontSize: wordSize,
          textTransform: "uppercase",
          paddingLeft: wordSpacing,
          fontFamily: "'DM Sans', system-ui, sans-serif",
          whiteSpace: "nowrap",
        }}
      >
        Signature
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: size === "lg" ? 10 : size === "md" ? 8 : 6, marginTop: size === "lg" ? 2 : 1 }}>
        <span style={{ width: ruleW, height: 1, background: gold, opacity: 0.95 }}></span>
        <div
          style={{
            color: ink,
            fontWeight: 400,
            letterSpacing: subSpacing,
            fontSize: subSize,
            textTransform: "uppercase",
            fontFamily: "'DM Sans', system-ui, sans-serif",
            whiteSpace: "nowrap",
            opacity: 0.98,
          }}
        >
          Estate Media
        </div>
        <span style={{ width: ruleW, height: 1, background: gold, opacity: 0.95 }}></span>
      </div>
    </div>
  );
}

// ─── Eyebrow label (no decorative rule — text only) ─────────────────────────
function Eyebrow({ children, tone = "dark", align = "left" }) {
  const ink = tone === "dark" ? "#111" : "#fff";
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: align === "center" ? "center" : "flex-start" }}>
      <span style={{
        color: ink, fontSize: 11, letterSpacing: "0.24em", textTransform: "uppercase",
        fontWeight: 500, opacity: tone === "dark" ? 0.7 : 0.85,
      }}>{children}</span>
    </div>
  );
}

// ─── Striped placeholder for unsupplied imagery ────────────────────────────
function Plate({ label, ratio = "4 / 3", tone = "light", caption, style = {}, src, alt, fit = "cover" }) {
  // tone: 'light' (warm grey) or 'dark' (charcoal) striped placeholder.
  const stripeA = tone === "dark" ? "#161616" : "#ECEAE6";
  const stripeB = tone === "dark" ? "#1C1C1C" : "#E4E1DB";
  const ink = tone === "dark" ? "rgba(255,255,255,0.55)" : "rgba(17,17,17,0.55)";
  const baseStyle = {
      aspectRatio: ratio,
      width: "100%",
      position: "relative",
      overflow: "hidden",
      ...style,
    };

  if (src) {
    return (
      <div style={baseStyle}>
        <img
          src={src}
          alt={alt || label || "Portfolio image"}
          loading="lazy"
          style={{ width: "100%", height: "100%", objectFit: fit, display: "block" }}
        />
      </div>
    );
  }

  return (
    <div style={{
      ...baseStyle,
      background: `repeating-linear-gradient(135deg, ${stripeA} 0 14px, ${stripeB} 14px 28px)`,
    }}>
      <div style={{
        position: "absolute", inset: 0,
        display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
        color: ink, fontFamily: "'DM Sans', system-ui, sans-serif",
        fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase",
        textAlign: "center", padding: "0 16px", gap: 4,
      }}>
        <div>{label}</div>
        {caption && <div style={{ opacity: 0.7, fontSize: 9 }}>{caption}</div>}
      </div>
    </div>
  );
}

// ─── Full-screen media lightbox (opened via window.semOpenLightbox/semOpenMedia) ───
function MediaLightbox({ mediaType = "image", src, alt, poster, canNavigate = false, onPrev, onNext, onClose }) {
  const closeRef = useRef(null);

  useEffect(() => {
    closeRef.current?.focus();
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (mediaType === "image" && canNavigate && e.key === "ArrowLeft" && typeof onPrev === "function") onPrev();
      if (mediaType === "image" && canNavigate && e.key === "ArrowRight" && typeof onNext === "function") onNext();
    };
    document.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [canNavigate, mediaType, onClose, onNext, onPrev]);

  const isVideo = mediaType === "video";

  return (
    <div className="sem-lightbox" role="dialog" aria-modal="true" aria-label={isVideo ? "Full screen video" : "Full screen image"}>
      <button type="button" className="sem-lightbox-backdrop" onClick={onClose} aria-label="Close image view" />
      <div className="sem-lightbox-frame">
        <button
          ref={closeRef}
          type="button"
          className="sem-lightbox-close"
          onClick={onClose}
          aria-label="Close"
        >
          ×
        </button>
        {!isVideo && canNavigate && (
          <React.Fragment>
            <button type="button" className="sem-lightbox-nav sem-lightbox-nav-prev" onClick={onPrev} aria-label="Previous image">
              ‹
            </button>
            <button type="button" className="sem-lightbox-nav sem-lightbox-nav-next" onClick={onNext} aria-label="Next image">
              ›
            </button>
          </React.Fragment>
        )}
        {isVideo ? (
          <video className="sem-lightbox-video" src={src} poster={poster || ""} controls autoPlay playsInline preload="metadata" />
        ) : (
          <img className="sem-lightbox-img" src={src} alt={alt || ""} />
        )}
      </div>
    </div>
  );
}

// ─── Nav ───────────────────────────────────────────────────────────────────
function Nav({ route, setRoute }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => {
      // On the home page, transition once user scrolls past hero (90vh).
      // On other pages, nav is always 'scrolled' (white state).
      const threshold = route === "home" ? window.innerHeight * 0.9 : 0;
      setScrolled(window.scrollY > threshold);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [route]);

  // Force scrolled state on non-home routes
  const isDark = !scrolled && route === "home";
  const items = [
    { id: "services", label: "Services" },
    { id: "portfolio", label: "Portfolio" },
    { id: "about", label: "About" },
    { id: "blog", label: "Journal" },
    { id: "contact", label: "Contact" },
  ];

  return (
    <header className={`sem-nav ${isDark ? "is-dark" : "is-light"}`}>
      <div className="sem-nav-inner">
        <button className="sem-nav-brand" onClick={() => { setRoute("home"); window.scrollTo({ top: 0 }); }} aria-label="Signature Estate Media — Home">
          <Logo tone={isDark ? "light" : "dark"} size="sm" />
        </button>
        <nav className="sem-nav-links" aria-label="Primary">
          {items.map((it) => (
            <button
              key={it.id}
              className={`sem-nav-link ${route === it.id ? "is-active" : ""}`}
              onClick={() => { setRoute(it.id); window.scrollTo({ top: 0 }); }}
            >
              {it.label}
            </button>
          ))}
          <a href="/guide" className="sem-nav-link">Guide</a>
        </nav>
        <button className="sem-nav-menu" onClick={() => setOpen(v => !v)} aria-label="Menu" aria-expanded={open}>
          <span></span><span></span>
        </button>
      </div>
      {open && (
        <div className="sem-nav-mobile">
          {items.map((it) => (
            <button
              key={it.id}
              className="sem-nav-mobile-link"
              onClick={() => { setRoute(it.id); setOpen(false); window.scrollTo({ top: 0 }); }}
            >{it.label}</button>
          ))}
          <a href="/guide" className="sem-nav-mobile-link">Guide</a>
        </div>
      )}
    </header>
  );
}

// ─── Footer ────────────────────────────────────────────────────────────────
function Footer({ setRoute }) {
  const cols = [
    { h: "Studio", items: [
      ["Services", "services"],
      ["Portfolio", "portfolio"],
      ["About", "about"],
      ["Journal", "blog"],
      ["Contact", "contact"],
    ]},
    { h: "Coverage", items: [
      ["Greater London"],
      ["Central · West · North"],
      ["Home Counties on request"],
    ]},
    { h: "Credentials", items: [
      ["DEA accredited"],
      ["CAA-compliant drone"],
      ["Public liability insured"],
      ["Professional indemnity insured"],
    ]},
  ];
  return (
    <footer className="sem-footer">
      <div className="sem-footer-top">
        <div className="sem-footer-brand">
          <Logo tone="light" size="md" />
          <p className="sem-footer-tagline">London property media</p>
          <a
            href="https://www.instagram.com/signature_estate_media/"
            target="_blank"
            rel="noopener noreferrer"
            className="sem-footer-instagram"
            aria-label="Instagram — @signature_estate_media"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
              <rect x="2" y="2" width="20" height="20" rx="5" stroke="currentColor" strokeWidth="1.5" />
              <circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="1.5" />
              <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none" />
            </svg>
          </a>
        </div>
        <div className="sem-footer-cols">
          {cols.map((c, i) => (
            <div key={i} className="sem-footer-col">
              <div className="sem-footer-h">{c.h}</div>
              <ul>
                {c.items.map((it, j) => (
                  <li key={j}>
                    {it[1] ? (
                      <button onClick={() => { setRoute(it[1]); window.scrollTo({ top: 0 }); }}>{it[0]}</button>
                    ) : (
                      <span>{it[0]}</span>
                    )}
                  </li>
                ))}
              </ul>
            </div>
          ))}
          <div className="sem-footer-col">
            <div className="sem-footer-h">Contact</div>
            <ul>
              <li><a href="mailto:hello@signatureestatemedia.co.uk">hello@signatureestatemedia.co.uk</a></li>
              <li><span>By appointment · London</span></li>
            </ul>
          </div>
        </div>
      </div>
      <div className="sem-footer-rule"></div>
      <div className="sem-footer-bottom">
        <div className="sem-footer-copy">© 2026 Signature Estate Media · London</div>
        <div className="sem-footer-recruit">
          Interested in working as a property media operator?{" "}
          <span className="sem-footer-recruit-cta">
            <button type="button" onClick={() => { setRoute("contact"); window.scrollTo({ top: 0 }); }}>Get in touch</button>.
          </span>
        </div>
      </div>
    </footer>
  );
}

// ─── CTA button ────────────────────────────────────────────────────────────
function CTA({ children, tone = "dark", onClick, size = "md" }) {
  // tone "dark"  -> CTA on dark backgrounds (gold border, gold text, white on hover)
  // tone "light" -> CTA on light backgrounds (ink border, ink text)
  const c = tone === "dark"
    ? { border: "#D4A830", text: "#fff", hover: "#D4A830" }
    : { border: "#111", text: "#111", hover: "#111" };
  return (
    <button
      className={`sem-cta sem-cta-${tone} sem-cta-${size}`}
      onClick={onClick}
      style={{
        "--cta-border": c.border, "--cta-text": c.text, "--cta-hover": c.hover,
      }}
    >
      <span>{children}</span>
      <svg width="18" height="10" viewBox="0 0 18 10" fill="none" aria-hidden="true">
        <path d="M1 5H17M17 5L13 1M17 5L13 9" stroke="currentColor" strokeWidth="1.25" strokeLinecap="square"/>
      </svg>
    </button>
  );
}

// ─── Section heading (eyebrow + title) ─────────────────────────────────────
function SectionHead({ eyebrow, title, intro, tone = "dark", align = "left" }) {
  return (
    <div className={`sem-section-head sem-section-head-${align}`}>
      <Eyebrow tone={tone} align={align}>{eyebrow}</Eyebrow>
      <h2 className="sem-section-title">{title}</h2>
      {intro && <p className="sem-section-intro">{intro}</p>}
    </div>
  );
}

Object.assign(window, {
  Logo,
  Eyebrow,
  Plate,
  Nav,
  Footer,
  CTA,
  SectionHead,
  MediaLightbox,
  ImageLightbox: MediaLightbox,
});
