/* global React, useViewport, PageIntro */
const { useState: useStateP, useMemo: useMemoP, useRef: useRefP, useEffect: useEffectP } = React;

/* ------------------------------------------------------------------ */
/* Project list — sourced from the central PROJECTS registry          */
/* (window.PROJECTS, see Projects.jsx). Falls back to a small sample  */
/* if the registry hasn't loaded yet.                                 */
/* ------------------------------------------------------------------ */

const FALLBACK_PROJECTS = [
  { slug: "project-adelaide", name: "Adelaide Airport", city: "Adelaide", country: "Australia", year: 2025, category: "Aviation", collections: ["Gateway", "Twig"], image: "images/_legacy/projects/cairns-airport.webp" },
];

function getAllProjects() {
  if (!window.PROJECTS) return FALLBACK_PROJECTS;
  return window.PROJECTS.map(p => ({
    slug: p.slug,
    name: p.name,
    city: p.city,
    country: p.country,
    year: p.year,
    category: p.category,
    collections: (p.collections || []).map(c => c.name),
    image: p.indexImage || p.hero,
  }));
}

const CATEGORIES = [
  "All Projects", "Aviation", "Civic", "Education",
  "Hospitality", "Installations", "Retail", "Corporate",
  "Custom solution",
];

/* Country -> region groupings. "All regions" means no filter. */
const REGION_MAP = {
  "Australia": "Asia Pacific",
  "New Zealand": "Asia Pacific",
  "Japan": "Asia Pacific",
  "Malaysia": "Asia Pacific",
  "USA": "North America",
  "United States": "North America",
  "Canada": "North America",
  "United Kingdom": "Europe",
  "Spain": "Europe",
  "France": "Europe",
  "Germany": "Europe",
  "Italy": "Europe",
  "Argentina": "South America",
  "Brazil": "South America",
};

function regionFor(country) {
  return REGION_MAP[country] || "Other";
}

const PROJECT_REGIONS = ["All regions", "Asia Pacific", "North America", "Europe", "South America"];

/* ------------------------------------------------------------------ */
/* By-category dropdown                                                */
/* ------------------------------------------------------------------ */

function FilterDropdown({ value, onChange, options, minWidth = 200, listMinWidth = 240 }) {
  const [open, setOpen] = useStateP(false);
  const ref = useRefP(null);

  useEffectP(() => {
    if (!open) return;
    const onDocClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", onDocClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDocClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  return (
    <div ref={ref} style={{ position: "relative", display: "inline-block" }}>
      <button
        onClick={() => setOpen(!open)}
        style={{
          fontFamily: "inherit",
          fontSize: 13,
          letterSpacing: "0.02em",
          fontWeight: 500,
          color: "#1a1917",
          background: "transparent",
          border: "0.5px solid #1a1917",
          borderRadius: 0,
          padding: "10px 16px",
          cursor: "pointer",
          display: "inline-flex",
          alignItems: "center",
          gap: 10,
          minWidth,
          justifyContent: "space-between",
        }}>
        <span>{value}</span>
        <span style={{
          display: "inline-block",
          transition: "transform 160ms ease",
          transform: open ? "rotate(180deg)" : "rotate(0deg)",
          fontSize: 10,
          color: "#6c6862",
        }}>▼</span>
      </button>
      {open && (
        <div style={{
          position: "absolute",
          top: "calc(100% - 0.5px)",
          left: 0,
          minWidth: listMinWidth,
          background: "#ffffff",
          border: "0.5px solid #1a1917",
          borderTop: "0.5px solid rgba(26,25,23,0.12)",
          padding: "8px 0",
          zIndex: 30,
          boxShadow: "0 12px 32px rgba(26,25,23,0.08)",
        }}>
          {options.map((c) => (
            <button
              key={c}
              onClick={() => { onChange(c); setOpen(false); }}
              style={{
                display: "block",
                width: "100%",
                textAlign: "left",
                fontFamily: "inherit",
                fontSize: 14,
                lineHeight: 1.4,
                fontWeight: c === value ? 500 : 400,
                color: "#1a1917",
                background: "transparent",
                border: "none",
                padding: "10px 18px",
                cursor: "pointer",
                letterSpacing: "-0.005em",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "#f5f3ef"}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
            >
              {c}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Projects page                                                       */
/* ------------------------------------------------------------------ */

function ProjectsPage({ setScreen }) {
  const vw = useViewport();
  const isMobile = vw < 760;
  const cols = vw < 600 ? 1 : vw < 960 ? 2 : 3;

  const [category, setCategory] = useStateP("All Projects");
  const [region, setRegion] = useStateP("All regions");
  const [collection, setCollection] = useStateP("All collections");

  const allProjects = useMemoP(() => getAllProjects(), []);
  const collectionOptions = useMemoP(() => {
    const set = new Set();
    allProjects.forEach(p => (p.collections || []).forEach(c => c && set.add(c)));
    return ["All collections", ...Array.from(set).sort((a, b) => a.localeCompare(b))];
  }, [allProjects]);
  const filtered = useMemoP(() => {
    return allProjects.filter(p => {
      if (category !== "All Projects" && p.category !== category) return false;
      if (region !== "All regions" && regionFor(p.country) !== region) return false;
      if (collection !== "All collections" && !(p.collections || []).includes(collection)) return false;
      return true;
    });
  }, [category, region, collection, allProjects]);

  return (
    <>
      {/* Hero */}
      <PageIntro
        eyebrow="Projects"
        title="Specified globally, for twenty years."
        body="A working portfolio of projects using Derlot furniture. Filter by category or browse the full set."
      />

      {/* Filter bar */}
      <section style={{
        padding: isMobile ? "20px 20px" : "24px max(24px, 3vw)",
        maxWidth: 1440,
        margin: "0 auto",
        borderTop: "0.5px solid rgba(26,25,23,0.18)",
        borderBottom: "0.5px solid rgba(26,25,23,0.18)",
        display: "flex",
        flexDirection: isMobile ? "column" : "row",
        alignItems: isMobile ? "flex-start" : "center",
        justifyContent: "space-between",
        gap: isMobile ? 14 : 24,
      }}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12, alignItems: "center" }}>
          <FilterDropdown value={category} onChange={setCategory} options={CATEGORIES} />
          <FilterDropdown value={region} onChange={setRegion} options={PROJECT_REGIONS} minWidth={180} listMinWidth={220} />
          <FilterDropdown value={collection} onChange={setCollection} options={collectionOptions} minWidth={190} listMinWidth={230} />
        </div>
        <div style={{ fontSize: 13, color: "#6c6862" }}>
          <b style={{ fontWeight: 500, color: "#1a1917" }}>{filtered.length}</b>{" "}
          {filtered.length === 1 ? "project" : "projects"}
          {category !== "All Projects" && <span> · {category}</span>}
          {region !== "All regions" && <span> · {region}</span>}
          {collection !== "All collections" && <span> · {collection}</span>}
        </div>
      </section>

      {/* Grid */}
      <section style={{ padding: isMobile ? "40px 20px 96px" : "64px max(24px, 3vw) 120px", maxWidth: 1440, margin: "0 auto" }}>
        {filtered.length === 0 ? (
          <div style={{ padding: "120px 0", textAlign: "center", color: "#6c6862", fontSize: 15 }}>
            No projects in this category yet.
          </div>
        ) : (
          <div style={{
            display: "grid",
            gridTemplateColumns: `repeat(${cols}, 1fr)`,
            gap: isMobile ? 32 : "56px 32px",
          }}>
            {filtered.map((p) => (
              <ProjectCard key={p.name} p={p} onClick={p.slug ? () => setScreen(p.slug) : null} />
            ))}
          </div>
        )}
      </section>
    </>
  );
}

function ProjectCard({ p, onClick }) {
  const [hover, setHover] = useStateP(false);
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={onClick || undefined}
      style={{ cursor: onClick ? "pointer" : "default" }}>
      <div style={{
        aspectRatio: "4/3",
        background: "#e4e2da",
        overflow: "hidden",
        position: "relative",
      }}>
        {p.image ? (
          <img src={p.image} srcSet={window.IMG && window.IMG.srcsetFor(p.image)} sizes={window.IMG && window.IMG.sizes()} alt={p.name} loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block", transition: "transform 900ms cubic-bezier(0.2,0.6,0.2,1)", transform: hover ? "scale(1.02)" : "scale(1)" }} />
        ) : (
          <div style={{
            position: "absolute", inset: 0,
            background: "#d9d7ce",
            opacity: hover ? 1 : 0,
            transition: "opacity 280ms ease",
          }} />
        )}
        <div style={{
          position: "absolute", top: 14, left: 14,
          fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase",
          color: "#1a1917", fontWeight: 500,
          background: "rgba(245,243,239,0.88)", padding: "4px 8px",
          backdropFilter: "blur(4px)",
        }}>{p.category}</div>
      </div>
      <div style={{ height: "0.5px", background: "rgba(26,25,23,0.18)", marginTop: 16 }} />
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 12, gap: 16 }}>
        <div style={{ fontSize: 18, color: "#1a1917", fontWeight: 500, letterSpacing: "-0.01em" }}>{p.name}</div>
        <div style={{ fontSize: 11, color: "#6c6862", letterSpacing: "0.12em", textTransform: "uppercase", flexShrink: 0 }}>{p.year}</div>
      </div>
      <div style={{ fontSize: 13, color: "#6c6862", marginTop: 6, letterSpacing: "0.02em" }}>
        {p.city} · {p.country}
      </div>
      <div style={{ fontSize: 12, color: "#6c6862", marginTop: 8, letterSpacing: "0.04em" }}>
        {p.collections.join(" · ")}
      </div>
    </div>
  );
}

window.ProjectsPage = ProjectsPage;
