/* Shared chrome for all Padre Studios pages.
 * Components on window: Backdrop, Header, Footer, Modal, Eyebrow, PageShell,
 * SkipLink, useViewport.
 *
 * Backdrop variants:
 *   hero    — rainy street photo + rain canvas + vignette (Landing only)
 *   quiet   — flat dark surface with subtle grain (interior pages)
 */

/* ---------- useViewport ---------- *
 * Single source of truth for responsive breakpoints. Returns a stable object
 * that updates only when the bucket changes — avoids re-renders on every px.
 */
function useViewport() {
  const compute = () => {
    if (typeof window === "undefined") {
      return { width: 1200, isMobile: false, isTablet: false, isDesktop: true };
    }
    const w = window.innerWidth;
    return {
      width: w,
      isMobile: w < 720,
      isTablet: w >= 720 && w < 1024,
      isDesktop: w >= 1024,
    };
  };
  const [vp, setVp] = React.useState(compute);
  React.useEffect(() => {
    let raf = 0;
    const onResize = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const next = compute();
        setVp((prev) =>
          prev.isMobile === next.isMobile &&
          prev.isTablet === next.isTablet &&
          prev.isDesktop === next.isDesktop
            ? prev
            : next
        );
      });
    };
    window.addEventListener("resize", onResize);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", onResize);
    };
  }, []);
  return vp;
}

/* ---------- SkipLink (a11y) ---------- */

const skipLinkStyles = {
  base: {
    position: "absolute",
    left: 16,
    top: -40,
    background: "var(--fg)",
    color: "var(--bg)",
    padding: "10px 14px",
    borderRadius: 8,
    fontFamily: "inherit",
    fontSize: 13,
    fontWeight: 500,
    textDecoration: "none",
    zIndex: 1000,
    transition: "top 160ms ease",
  },
};
function SkipLink() {
  return (
    <a
      href="#main"
      style={skipLinkStyles.base}
      onFocus={(e) => (e.currentTarget.style.top = "16px")}
      onBlur={(e) => (e.currentTarget.style.top = "-40px")}
    >
      Skip to content
    </a>
  );
}

/* ---------- Backdrop ---------- */

const backdropStyles = {
  wrap: {
    position: "absolute",
    inset: 0,
    zIndex: 0,
    overflow: "hidden",
    background: "var(--bg)",
  },
  img: {
    position: "absolute",
    inset: 0,
    width: "100%",
    height: "100%",
    objectFit: "cover",
    objectPosition: "center bottom",
  },
  vignetteHero: {
    position: "absolute",
    inset: 0,
    background:
      "linear-gradient(180deg, color-mix(in oklch, var(--bg-deep) 55%, transparent) 0%, color-mix(in oklch, var(--bg-deep) 18%, transparent) 22%, transparent 42%, color-mix(in oklch, var(--bg-deep) 55%, transparent) 72%, color-mix(in oklch, var(--bg-deep) 95%, transparent) 100%), radial-gradient(110% 70% at 65% 38%, transparent 0%, color-mix(in oklch, var(--bg-deep) 35%, transparent) 65%, color-mix(in oklch, var(--bg-deep) 80%, transparent) 100%)",
  },
  quiet: {
    position: "absolute",
    inset: 0,
    background:
      "radial-gradient(80% 60% at 50% 0%, color-mix(in oklch, var(--fg) 4%, transparent) 0%, transparent 60%), var(--bg-deep)",
  },
  grain: {
    position: "absolute",
    inset: 0,
    opacity: 0.35,
    mixBlendMode: "overlay",
    backgroundImage:
      "repeating-linear-gradient(0deg, color-mix(in oklch, var(--fg) 3%, transparent) 0 1px, transparent 1px 3px)",
    pointerEvents: "none",
  },
};

function Backdrop({ variant = "hero", parallaxY = 0 }) {
  const { isMobile } = useViewport();
  if (variant === "hero") {
    return (
      <div style={backdropStyles.wrap} aria-hidden="true">
        {/* Source: https://unsplash.com/photos/cars-on-road-between-high-rise-buildings-during-night-time-hwSmGXSbn8o */}
        <img
          src="https://unsplash.com/photos/hwSmGXSbn8o/download?w=2400&q=85&fm=jpg"
          alt=""
          style={{
            ...backdropStyles.img,
            transform: `translate3d(0, ${parallaxY}px, 0) scale(1.06)`,
            transition: "transform 80ms linear",
          }}
        />
        {window.RainCanvas ? (
          <window.RainCanvas
            density={isMobile ? 10 : 18}
            angle={6}
            speed={1.05}
            color="rgba(190, 220, 245, 0.6)"
          />
        ) : null}
        <div style={backdropStyles.vignetteHero} />
      </div>
    );
  }
  return (
    <div style={backdropStyles.wrap} aria-hidden="true">
      <div style={backdropStyles.quiet} />
      <div style={backdropStyles.grain} />
    </div>
  );
}

/* ---------- Header ---------- */

const NAV_LINKS = [
  { label: "Work", href: "Work.html" },
  { label: "Studio", href: "Studio.html" },
  { label: "Process", href: "Process.html" },
  { label: "Journal", href: "Journal.html" },
  { label: "Contact", href: "Contact.html" },
];

const headerStyles = {
  wrap: {
    position: "sticky",
    top: 0,
    zIndex: 10,
    padding: "20px 32px 0",
  },
  wrapMobile: { padding: "14px 16px 0" },
  bar: {
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    gap: 24,
    height: 64,
    padding: "0 22px",
    borderRadius: 14,
    background: "color-mix(in oklch, var(--bg-deep) 30%, transparent)",
    border: "1px solid var(--glass-border)",
    backdropFilter: "blur(18px) saturate(140%)",
    WebkitBackdropFilter: "blur(18px) saturate(140%)",
    boxShadow:
      "0 1px 0 color-mix(in oklch, var(--fg) 10%, transparent) inset, 0 20px 40px -20px rgba(0,0,0,0.5)",
  },
  barMobile: { height: 56, padding: "0 14px 0 18px", gap: 12 },
  brand: {
    display: "inline-flex",
    alignItems: "center",
    color: "var(--fg)",
    textDecoration: "none",
    height: "100%",
  },
  brandLogo: {
    height: 55,
    width: "auto",
    display: "block",
  },
  brandLogoMobile: {
    height: 28,
  },
  nav: { display: "flex", alignItems: "center", gap: 28 },
  link: {
    fontSize: 13,
    letterSpacing: "0.02em",
    color: "var(--fg-dim)",
    textDecoration: "none",
    cursor: "pointer",
    transition: "color 160ms ease",
    position: "relative",
    padding: "8px 4px",
    borderRadius: 4,
  },
  linkActive: { color: "var(--fg)" },
  linkActiveDot: {
    position: "absolute",
    left: "50%",
    bottom: 0,
    transform: "translateX(-50%)",
    width: 4,
    height: 4,
    borderRadius: "50%",
    background: "var(--accent)",
  },
  actions: { display: "flex", alignItems: "center", gap: 10 },
  ghost: {
    fontSize: 13,
    color: "var(--fg-dim)",
    background: "transparent",
    border: "1px solid transparent",
    padding: "9px 14px",
    borderRadius: 999,
    cursor: "pointer",
    fontFamily: "inherit",
    letterSpacing: "0.02em",
  },
  cta: {
    fontSize: 13,
    color: "var(--bg)",
    background: "var(--fg)",
    border: "1px solid var(--fg)",
    padding: "9px 16px",
    borderRadius: 999,
    cursor: "pointer",
    fontFamily: "inherit",
    letterSpacing: "0.02em",
    fontWeight: 500,
    transition: "background 160ms ease, border-color 160ms ease",
    textDecoration: "none",
    display: "inline-flex",
    alignItems: "center",
  },

  /* mobile menu */
  burger: {
    width: 40,
    height: 40,
    border: "1px solid var(--glass-border)",
    background: "transparent",
    borderRadius: 999,
    cursor: "pointer",
    color: "var(--fg)",
    display: "inline-flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    gap: 4,
    padding: 0,
  },
  burgerLine: {
    width: 16,
    height: 1.5,
    background: "var(--fg)",
    borderRadius: 1,
    transition: "transform 220ms ease, opacity 180ms ease",
  },
  menuScrim: {
    position: "fixed",
    inset: 0,
    zIndex: 50,
    background: "color-mix(in oklch, var(--bg-deep) 88%, transparent)",
    backdropFilter: "blur(18px) saturate(140%)",
    WebkitBackdropFilter: "blur(18px) saturate(140%)",
    display: "flex",
    flexDirection: "column",
    padding: "84px 24px 32px",
  },
  menuLink: {
    display: "block",
    padding: "16px 0",
    fontSize: 28,
    letterSpacing: "-0.015em",
    color: "var(--fg)",
    textDecoration: "none",
    borderBottom: "1px solid var(--line)",
  },
  menuFoot: {
    marginTop: "auto",
    paddingTop: 24,
    display: "flex",
    flexDirection: "column",
    gap: 12,
  },
  menuCta: {
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
    gap: 10,
    background: "var(--fg)",
    color: "var(--bg)",
    padding: "16px 22px",
    borderRadius: 999,
    fontSize: 14,
    fontWeight: 500,
    textDecoration: "none",
  },
  menuMeta: {
    fontFamily: "ui-monospace, 'SF Mono', Menlo, Consolas, monospace",
    fontSize: 11,
    letterSpacing: "0.22em",
    textTransform: "uppercase",
    color: "var(--fg-faint)",
    textAlign: "center",
  },
};

function Header({ active }) {
  const { isMobile } = useViewport();
  const [hoverIdx, setHoverIdx] = React.useState(-1);
  const [menuOpen, setMenuOpen] = React.useState(false);

  React.useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => e.key === "Escape" && setMenuOpen(false);
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [menuOpen]);

  React.useEffect(() => {
    if (!isMobile && menuOpen) setMenuOpen(false);
  }, [isMobile, menuOpen]);

  return (
    <header style={{ ...headerStyles.wrap, ...(isMobile ? headerStyles.wrapMobile : null) }}>
      <div style={{ ...headerStyles.bar, ...(isMobile ? headerStyles.barMobile : null) }}>
        <a href="index.html" style={headerStyles.brand} aria-label="Padre Studios — home">
          <img
            src="logo.png?v=2"
            alt=""
            style={{
              ...headerStyles.brandLogo,
              ...(isMobile ? headerStyles.brandLogoMobile : null),
            }}
          />
        </a>

        {!isMobile && (
          <nav style={headerStyles.nav} aria-label="Primary">
            {NAV_LINKS.map((l, i) => {
              const isActive = active === l.label;
              return (
                <a
                  key={l.label}
                  href={l.href}
                  aria-current={isActive ? "page" : undefined}
                  style={{
                    ...headerStyles.link,
                    ...(isActive || hoverIdx === i ? headerStyles.linkActive : null),
                  }}
                  onMouseEnter={() => setHoverIdx(i)}
                  onMouseLeave={() => setHoverIdx(-1)}
                  onFocus={() => setHoverIdx(i)}
                  onBlur={() => setHoverIdx(-1)}
                >
                  {l.label}
                  {isActive ? <span style={headerStyles.linkActiveDot} aria-hidden="true" /> : null}
                </a>
              );
            })}
          </nav>
        )}

        {!isMobile ? (
          <div style={headerStyles.actions}>
            <a href="Signin.html" style={{ ...headerStyles.ghost, textDecoration: "none", display: "inline-flex", alignItems: "center" }}>Sign in</a>
            <a
              href="Contact.html"
              style={headerStyles.cta}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = "var(--accent)";
                e.currentTarget.style.borderColor = "var(--accent)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = "var(--fg)";
                e.currentTarget.style.borderColor = "var(--fg)";
              }}
            >
              Start a project →
            </a>
          </div>
        ) : (
          <button
            type="button"
            style={headerStyles.burger}
            aria-label={menuOpen ? "Close menu" : "Open menu"}
            aria-expanded={menuOpen}
            aria-controls="ps-mobile-menu"
            onClick={() => setMenuOpen((v) => !v)}
          >
            <span style={{ ...headerStyles.burgerLine, transform: menuOpen ? "translateY(2.75px) rotate(45deg)" : "none" }} />
            <span style={{ ...headerStyles.burgerLine, opacity: menuOpen ? 0 : 1, transform: menuOpen ? "scaleX(0.6)" : "none" }} />
            <span style={{ ...headerStyles.burgerLine, transform: menuOpen ? "translateY(-2.75px) rotate(-45deg)" : "none" }} />
          </button>
        )}
      </div>

      {isMobile && menuOpen && (
        <div id="ps-mobile-menu" style={headerStyles.menuScrim} role="dialog" aria-modal="true" aria-label="Site menu">
          <nav aria-label="Primary mobile">
            {NAV_LINKS.map((l) => {
              const isActive = active === l.label;
              return (
                <a
                  key={l.label}
                  href={l.href}
                  aria-current={isActive ? "page" : undefined}
                  style={{ ...headerStyles.menuLink, color: isActive ? "var(--accent)" : "var(--fg)" }}
                >
                  {l.label}
                  {isActive ? <span style={{ marginLeft: 12, fontSize: 14, color: "var(--fg-faint)" }}>—</span> : null}
                </a>
              );
            })}
          </nav>
          <div style={headerStyles.menuFoot}>
            <a href="Signin.html" style={{ ...headerStyles.menuCta, background: "transparent", color: "var(--fg)", border: "1px solid var(--glass-border)" }}>Sign in</a>
            <a href="Contact.html" style={headerStyles.menuCta}>Start a project →</a>
            <p style={headerStyles.menuMeta}>info@padrestudios.com · LA / CDMX</p>
          </div>
        </div>
      )}
    </header>
  );
}

/* ---------- Footer ---------- */

const footerStyles = {
  wrap: {
    position: "relative",
    zIndex: 2,
    padding: "80px 56px 36px",
    borderTop: "1px solid var(--line)",
    background: "color-mix(in oklch, var(--bg-deep) 70%, transparent)",
    backdropFilter: "blur(8px)",
    WebkitBackdropFilter: "blur(8px)",
  },
  wrapMobile: { padding: "56px 20px 28px" },
  top: {
    display: "grid",
    gridTemplateColumns: "1.4fr repeat(4, 1fr)",
    gap: 40,
    marginBottom: 56,
  },
  topTablet: { gridTemplateColumns: "1fr 1fr", gap: 32 },
  topMobile: { gridTemplateColumns: "1fr", gap: 32, marginBottom: 40 },
  brandBlock: { display: "flex", flexDirection: "column", gap: 16 },
  brandLogo: {
    height: 56,
    width: "auto",
    display: "block",
    alignSelf: "flex-start",   // prevent the parent flex column from stretching us to 100% width
    margin: 0,
    background: "transparent", // belt-and-suspenders: ensure no UA default ever paints behind the img
  },
  brandLogoMobile: {
    height: 44,
  },
  brandSub: { fontSize: 14, color: "var(--fg-dim)", lineHeight: 1.55, maxWidth: 360, margin: 0 },
  colTitle: {
    fontFamily: "ui-monospace, 'SF Mono', Menlo, Consolas, monospace",
    fontSize: 10,
    letterSpacing: "0.22em",
    textTransform: "uppercase",
    color: "var(--fg-faint)",
    margin: "0 0 16px",
  },
  colList: {
    listStyle: "none",
    padding: 0,
    margin: 0,
    display: "flex",
    flexDirection: "column",
    gap: 10,
  },
  colLink: {
    fontSize: 13,
    color: "var(--fg-dim)",
    textDecoration: "none",
    transition: "color 140ms ease",
  },
  bottom: {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    paddingTop: 24,
    borderTop: "1px solid var(--line)",
    fontFamily: "ui-monospace, 'SF Mono', Menlo, Consolas, monospace",
    fontSize: 11,
    letterSpacing: "0.12em",
    textTransform: "uppercase",
    color: "var(--fg-faint)",
    flexWrap: "wrap",
    gap: 12,
  },
  bottomMobile: { flexDirection: "column", alignItems: "flex-start", gap: 8, fontSize: 10 },
};

function FooterCol({ title, items }) {
  return (
    <div>
      <h4 style={footerStyles.colTitle}>{title}</h4>
      <ul style={footerStyles.colList}>
        {items.map((it) => (
          <li key={it.label}>
            <a
              href={it.href}
              style={footerStyles.colLink}
              onMouseEnter={(e) => (e.currentTarget.style.color = "var(--fg)")}
              onMouseLeave={(e) => (e.currentTarget.style.color = "var(--fg-dim)")}
              onFocus={(e) => (e.currentTarget.style.color = "var(--fg)")}
              onBlur={(e) => (e.currentTarget.style.color = "var(--fg-dim)")}
            >
              {it.label}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

function Footer() {
  const { isMobile, isTablet } = useViewport();
  const topStyle = {
    ...footerStyles.top,
    ...(isTablet ? footerStyles.topTablet : null),
    ...(isMobile ? footerStyles.topMobile : null),
  };
  return (
    <footer style={{ ...footerStyles.wrap, ...(isMobile ? footerStyles.wrapMobile : null) }}>
      <div style={topStyle}>
        <div style={footerStyles.brandBlock}>
          <img
            src="logo.png?v=2"
            alt="Padre Studios"
            style={{
              ...footerStyles.brandLogo,
              ...(isMobile ? footerStyles.brandLogoMobile : null),
            }}
          />
          <p style={footerStyles.brandSub}>
            A small independent studio for websites, mobile apps, and quiet
            software. San Antonio, TX.
          </p>
        </div>
        <FooterCol
          title="Sitemap"
          items={[
            { label: "Work", href: "Work.html" },
            { label: "Studio", href: "Studio.html" },
            { label: "Process", href: "Process.html" },
            { label: "Journal", href: "Journal.html" },
            { label: "Contact", href: "Contact.html" },
          ]}
        />
        <FooterCol
          title="Services"
          items={[
            { label: "Websites", href: "Process.html" },
            { label: "Mobile Apps", href: "Process.html" },
            { label: "Design Systems", href: "Process.html" },
            { label: "Product Strategy", href: "Process.html" },
          ]}
        />
        <FooterCol
          title="Elsewhere"
          items={[
            { label: "Instagram", href: "#" },
            { label: "Vimeo", href: "#" },
            { label: "Are.na", href: "#" },
            { label: "LinkedIn", href: "#" },
          ]}
        />
        <FooterCol
          title="Contact"
          items={[
            { label: "info@padrestudios.com", href: "mailto:info@padrestudios.com" },
            /*{ label: "+1 (555) 555 5555", href: "tel:+1555555555" },*/
            /*{ label: "333 Vision Rd", href: "#" },*/
            { label: "San Antonio, TX", href: "#" },
          ]}
        />
      </div>
      <div style={{ ...footerStyles.bottom, ...(isMobile ? footerStyles.bottomMobile : null) }}>
        <span>© 2026 Padre Studios</span>
        <span>Made quietly in San Antonio, TX</span>
        <span>v.04 · April 2026</span>
      </div>
    </footer>
  );
}

/* ---------- Modal ---------- */

const modalStyles = {
  scrim: {
    position: "fixed",
    inset: 0,
    background: "rgba(0,0,0,0.7)",
    backdropFilter: "blur(8px)",
    WebkitBackdropFilter: "blur(8px)",
    zIndex: 100,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    padding: 32,
  },
  scrimMobile: { padding: 16 },
  panel: {
    position: "relative",
    width: "100%",
    maxWidth: 1100,
    aspectRatio: "16 / 9",
    background: "#000",
    borderRadius: 12,
    overflow: "hidden",
    border: "1px solid var(--glass-border)",
    boxShadow: "0 40px 100px -20px rgba(0,0,0,0.7)",
  },
  close: {
    position: "absolute",
    top: 14,
    right: 14,
    width: 36,
    height: 36,
    borderRadius: "50%",
    background: "rgba(0,0,0,0.5)",
    border: "1px solid var(--glass-border)",
    color: "var(--fg)",
    cursor: "pointer",
    fontFamily: "inherit",
    fontSize: 16,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    zIndex: 2,
    backdropFilter: "blur(8px)",
  },
  placeholder: {
    position: "absolute",
    inset: 0,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    color: "var(--fg-faint)",
    fontFamily: "ui-monospace, 'SF Mono', Menlo, Consolas, monospace",
    fontSize: 12,
    letterSpacing: "0.22em",
    textTransform: "uppercase",
    backgroundImage:
      "repeating-linear-gradient(135deg, rgba(255,255,255,0.04) 0 2px, transparent 2px 14px)",
  },
};

function Modal({ open, onClose, children }) {
  const { isMobile } = useViewport();
  const closeBtnRef = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    setTimeout(() => closeBtnRef.current?.focus(), 0);
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div
      style={{ ...modalStyles.scrim, ...(isMobile ? modalStyles.scrimMobile : null) }}
      onClick={onClose}
      role="dialog"
      aria-modal="true"
      aria-label="Reel"
    >
      <div style={modalStyles.panel} onClick={(e) => e.stopPropagation()}>
        <button
          ref={closeBtnRef}
          type="button"
          style={modalStyles.close}
          onClick={onClose}
          aria-label="Close"
        >
          ✕
        </button>
        {children || (
          <div style={modalStyles.placeholder}>
            [ reel video — drop &lt;video&gt; here ]
          </div>
        )}
      </div>
    </div>
  );
}

/* ---------- Eyebrow ---------- */

const eyebrowStyles = {
  wrap: {
    display: "inline-flex",
    alignItems: "center",
    gap: 10,
    fontFamily: "ui-monospace, 'SF Mono', Menlo, Consolas, monospace",
    fontSize: 11,
    letterSpacing: "0.22em",
    textTransform: "uppercase",
    color: "var(--fg-dim)",
  },
  dot: {
    width: 6,
    height: 6,
    borderRadius: "50%",
    background: "var(--accent)",
    boxShadow: "0 0 12px var(--accent)",
  },
};

function Eyebrow({ children, dot = true }) {
  return (
    <div style={eyebrowStyles.wrap}>
      {dot ? <span style={eyebrowStyles.dot} aria-hidden="true" /> : null}
      <span>{children}</span>
    </div>
  );
}

/* ---------- PageShell ---------- */

const shellStyles = {
  shell: {
    position: "relative",
    minHeight: "100vh",
    width: "100%",
    overflow: "hidden",
    background: "var(--bg-deep)",
    color: "var(--fg)",
    display: "flex",
    flexDirection: "column",
  },
  content: {
    position: "relative",
    zIndex: 2,
    display: "flex",
    flexDirection: "column",
    flex: 1,
    minHeight: "100vh",
  },
};

function PageShell({ active, backdrop = "quiet", children }) {
  return (
    <div style={shellStyles.shell}>
      <SkipLink />
      <Backdrop variant={backdrop} />
      <div style={shellStyles.content}>
        <Header active={active} />
        <main id="main">{children}</main>
        <Footer />
      </div>
    </div>
  );
}

Object.assign(window, { Backdrop, Header, Footer, Modal, Eyebrow, PageShell, SkipLink, useViewport });
