/* ============================================================
   Farbodfilms — common components
   ============================================================ */

// ---- Logo ---------------------------------------------------
function Logo({ onClick, size = 18 }) {
  return (
    <button className="logo" onClick={onClick} style={{ fontSize: size }} aria-label="Farbodfilms home">
      <span className="logo-mark" aria-hidden="true">
        <span className="logo-aperture" />
      </span>
      <span className="logo-word">
        farbod<span className="logo-thin">films</span>
      </span>
    </button>
  );
}

// ---- Scene (a graded/ungraded "photo") ----------------------
function Scene({ sceneKey, grade = "ungraded", grain = false, className = "", style = {}, photo = null }) {
  // photo: { graded, slog } — render BOTH layers so they preload; the
  // grade just toggles opacity for an instant, lag-free swap on hover.
  if (photo) {
    const showGraded = grade !== "ungraded";
    return (
      <div className={"scene " + className} style={style}>
        <img className="scene-photo" src={photo.slog} alt="" draggable="false" />
        <img
          className="scene-photo scene-photo-graded"
          src={photo.graded}
          alt=""
          draggable="false"
          style={{ opacity: showGraded ? 1 : 0 }}
        />
        <div className="scene-vignette" />
        {grain && <div className="scene-grain" />}
      </div>
    );
  }
  const scene = SCENES[sceneKey] || Object.values(SCENES)[0];
  const g = GRADES[grade] || GRADES.ungraded;
  return (
    <div className={"scene " + className} style={style}>
      <div className="scene-img" style={{ background: scene.css, filter: g.filter }} />
      <div className="scene-grade" style={{ background: g.overlay }} />
      <div className="scene-vignette" />
      {grain && <div className="scene-grain" />}
    </div>
  );
}

// ---- Before / After slider ----------------------------------
function BeforeAfter({ sceneKey, grade, grain = false, label, photo = null }) {
  const [pos, setPos] = React.useState(58);
  const [dragging, setDragging] = React.useState(false);
  const ref = React.useRef(null);
  const [w, setW] = React.useState(0);

  const measure = React.useCallback(() => {
    if (ref.current) setW(ref.current.getBoundingClientRect().width);
  }, []);
  React.useEffect(() => {
    measure();
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, [measure]);

  const update = React.useCallback((clientX) => {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const p = ((clientX - r.left) / r.width) * 100;
    setPos(Math.max(0, Math.min(100, p)));
  }, []);

  React.useEffect(() => {
    if (!dragging) return;
    const move = (e) => {
      const x = e.touches ? e.touches[0].clientX : e.clientX;
      update(x);
    };
    const up = () => setDragging(false);
    window.addEventListener("mousemove", move);
    window.addEventListener("mouseup", up);
    window.addEventListener("touchmove", move, { passive: false });
    window.addEventListener("touchend", up);
    return () => {
      window.removeEventListener("mousemove", move);
      window.removeEventListener("mouseup", up);
      window.removeEventListener("touchmove", move);
      window.removeEventListener("touchend", up);
    };
  }, [dragging, update]);

  const start = (e) => {
    setDragging(true);
    const x = e.touches ? e.touches[0].clientX : e.clientX;
    update(x);
  };

  return (
    <div className="ba" ref={ref} onMouseDown={start} onTouchStart={start}>
      {/* graded (full) */}
      <Scene sceneKey={sceneKey} grade={grade} grain={grain} className="ba-layer" photo={photo} />
      {/* ungraded (clipped to left of handle) */}
      <div className="ba-clip" style={{ width: pos + "%" }}>
        <Scene
          sceneKey={sceneKey}
          grade="ungraded"
          grain={grain}
          className="ba-layer"
          photo={photo}
          style={{ width: w || "100%" }}
        />
      </div>

      <span className="ba-tag ba-tag-before" style={{ opacity: pos > 16 ? 1 : 0 }}>Original · SLOG</span>
      <span className="ba-tag ba-tag-after" style={{ opacity: pos < 84 ? 1 : 0 }}>{label || "Graded"}</span>

      <div className="ba-handle" style={{ left: pos + "%" }}>
        <div className="ba-line" />
        <div className="ba-grip">
          <span>‹</span><span>›</span>
        </div>
      </div>

      <div className="scene-cap mono">{photo ? "REAL FOOTAGE · drag to compare" : "SAMPLE · drag to compare"}</div>
    </div>
  );
}

// ---- Buttons ------------------------------------------------
function Btn({ children, onClick, variant = "solid", size = "md", full = false, className = "" }) {
  return (
    <button
      className={`btn btn-${variant} btn-${size} ${full ? "btn-full" : ""} ${className}`}
      onClick={onClick}
    >
      {children}
    </button>
  );
}

// ---- Nav ----------------------------------------------------
function Nav({ go, route, cartCount, openCart, theme }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const root = document.querySelector(".app-scroll");
    const el = root || window;
    const onScroll = () => {
      const y = root ? root.scrollTop : window.scrollY;
      setScrolled(y > 24);
    };
    el.addEventListener("scroll", onScroll);
    return () => el.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    { k: "shop", label: "Shop" },
    { k: "about", label: "About" },
    { k: "faq", label: "Install" },
  ];

  return (
    <header className={"nav " + (scrolled ? "nav-scrolled" : "")}>
      <div className="nav-inner">
        <Logo onClick={() => go("home")} />
        <nav className="nav-links">
          {links.map((l) => (
            <button
              key={l.k}
              className={"nav-link " + (route === l.k ? "is-active" : "")}
              onClick={() => go(l.k)}
            >
              {l.label}
            </button>
          ))}
        </nav>
        <div className="nav-right">
          <button className="nav-cart" onClick={openCart} aria-label="Open cart">
            <span className="mono">CART</span>
            <span className={"nav-cart-count " + (cartCount ? "has" : "")}>{cartCount}</span>
          </button>
        </div>
      </div>
    </header>
  );
}

// ---- Footer -------------------------------------------------
function Footer({ go }) {
  return (
    <footer className="footer">
      <div className="footer-top">
        <div className="footer-brand">
          <Logo onClick={() => go("home")} size={20} />
          <p className="footer-tag">Turning ordinary moments into cinematic stories.</p>
        </div>
        <div className="footer-cols">
          <div className="footer-col">
            <span className="footer-h mono">Shop</span>
            <button onClick={() => go("shop")}>All LUTs</button>
            <button onClick={() => go("product:daydream")}>Daydream</button>
            <button onClick={() => go("product:afterlight")}>Afterlight</button>
            <button onClick={() => go("product:ss26-bundle")}>SS26 Collection</button>
          </div>
          <div className="footer-col">
            <span className="footer-h mono">Help</span>
            <button onClick={() => go("faq")}>How to install</button>
            <button onClick={() => go("faq")}>Compatibility</button>
            <button onClick={() => go("about")}>About</button>
          </div>
          <div className="footer-col">
            <span className="footer-h mono">Follow</span>
            <a href="#" onClick={(e) => e.preventDefault()}>Instagram</a>
            <a href="#" onClick={(e) => e.preventDefault()}>YouTube</a>
            <a href="#" onClick={(e) => e.preventDefault()}>TikTok</a>
          </div>
        </div>
      </div>
      <div className="footer-bottom mono">
        <span>© 2026 Farbodfilms</span>
        <span>Made for filmmakers, by a filmmaker</span>
      </div>
    </footer>
  );
}

Object.assign(window, { Logo, Scene, BeforeAfter, Btn, Nav, Footer });
