/* global React, ProjectImage */
// Archive — filterable, sortable project list with density modes (sparse / comfortable / dense / list)

function FilterBar({ types, statuses, years, filter, setFilter, density, setDensity, sort, setSort, count, total }) {
  return (
    <div
      style={{
        position: "sticky",
        top: 0,
        zIndex: 20,
        background: "color-mix(in oklab, var(--bg) 92%, transparent)",
        backdropFilter: "blur(10px)",
        WebkitBackdropFilter: "blur(10px)",
        borderBottom: "1px solid var(--line-soft)",
        padding: "16px 32px",
      }}
    >
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24, flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
          <span className="t-mono" style={{ color: "var(--muted)", marginRight: 6 }}>Filtre:</span>
          {types.map((t) => (
            <button
              key={t}
              className="tag"
              data-active={filter.type === t}
              onClick={() => setFilter((f) => ({ ...f, type: t }))}
            >
              {t}
            </button>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <span className="t-mono" style={{ color: "var(--muted)" }}>{count} / {total}</span>
          <span style={{ width: 1, height: 16, background: "var(--line)" }} />
          <span className="t-mono" style={{ color: "var(--muted)" }}>Sırala:</span>
          {["yeni", "eski", "alfabe"].map((s) => (
            <button
              key={s}
              className="tag"
              data-active={sort === s}
              onClick={() => setSort(s)}
            >
              {s}
            </button>
          ))}
          <span style={{ width: 1, height: 16, background: "var(--line)" }} />
          <div style={{ display: "flex", gap: 4 }}>
            {[
              { id: "sparse", icon: "□" },
              { id: "comfortable", icon: "▦" },
              { id: "dense", icon: "▣" },
              { id: "list", icon: "≡" },
            ].map((d) => (
              <button
                key={d.id}
                onClick={() => setDensity(d.id)}
                style={{
                  width: 28, height: 28,
                  border: "1px solid var(--line)",
                  borderRadius: 4,
                  color: density === d.id ? "var(--bg)" : "var(--fg)",
                  background: density === d.id ? "var(--fg)" : "transparent",
                  fontSize: 13,
                  display: "inline-flex",
                  alignItems: "center",
                  justifyContent: "center",
                }}
                title={d.id}
              >
                {d.icon}
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function ProjectCard({ project, navigate, density }) {
  const ratio = density === "sparse" ? "4 / 3" : density === "comfortable" ? "3 / 4" : "1 / 1";
  return (
    <button
      onClick={() => navigate({ page: "project", id: project.id })}
      style={{ textAlign: "left", display: "block" }}
      onMouseEnter={(e) => {
        const img = e.currentTarget.querySelector(".pc-img");
        if (img) img.style.transform = "scale(1.02)";
      }}
      onMouseLeave={(e) => {
        const img = e.currentTarget.querySelector(".pc-img");
        if (img) img.style.transform = "scale(1)";
      }}
    >
      <div style={{ overflow: "hidden" }}>
        <div className="pc-img" style={{ transition: "transform 600ms cubic-bezier(0.2,0.7,0.2,1)" }}>
          <ProjectImage project={project} index={0} ratio={ratio} showMeta={false} />
        </div>
      </div>
      <div style={{ padding: "14px 0 0", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
        <div>
          <div className="t-mono" style={{ color: "var(--muted)" }}>
            {project.location} · {project.type}
          </div>
          <div
            style={{
              fontFamily: "var(--font-display)",
              fontSize: density === "sparse" ? 32 : density === "comfortable" ? 24 : 18,
              marginTop: 6,
              lineHeight: 1.1,
              letterSpacing: "-0.01em",
            }}
          >
            {project.title}
          </div>
        </div>
        <span className="t-mono t-num" style={{ color: "var(--muted)" }}>{project.year}</span>
      </div>
      {density === "sparse" && (
        <p style={{ marginTop: 12, fontSize: 14, lineHeight: 1.5, color: "var(--muted)", textWrap: "pretty", maxWidth: 520 }}>
          {project.summary}
        </p>
      )}
    </button>
  );
}

function ProjectRow({ project, navigate, hovered, setHovered, idx }) {
  return (
    <li
      onMouseEnter={() => setHovered(project.id)}
      onMouseLeave={() => setHovered(null)}
      onClick={() => navigate({ page: "project", id: project.id })}
      style={{
        display: "grid",
        gridTemplateColumns: "60px 1.8fr 1.2fr 1fr 1fr 80px",
        gap: 24,
        alignItems: "center",
        padding: "18px 0",
        borderTop: "1px solid var(--line-soft)",
        cursor: "pointer",
        transition: "padding-left 220ms ease, color 220ms ease",
        paddingLeft: hovered === project.id ? 16 : 0,
        color: hovered && hovered !== project.id ? "var(--muted)" : "var(--fg)",
      }}
    >
      <span className="t-mono" style={{ color: "var(--muted)" }}>{String(idx + 1).padStart(2, "0")}</span>
      <span className="t-display" style={{ fontSize: 24, lineHeight: 1, letterSpacing: "-0.01em" }}>
        {project.title}
      </span>
      <span style={{ color: "var(--muted)", fontSize: 14 }}>{project.location}</span>
      <span className="t-mono" style={{ color: "var(--muted)" }}>{project.type}</span>
      <span className="t-mono" style={{ color: "var(--muted)" }}>{project.status || ""}</span>
      <span className="t-mono t-num" style={{ color: "var(--muted)", textAlign: "right" }}>{project.year}</span>
    </li>
  );
}

function Archive({ projects, navigate, tweaks }) {
  const [filter, setFilter] = React.useState({ type: "Tümü" });
  const [sort, setSort] = React.useState("yeni");
  const [density, setDensity] = React.useState(tweaks.density || "comfortable");
  const [hovered, setHovered] = React.useState(null);
  const [pos, setPos] = React.useState({ x: 0, y: 0 });

  React.useEffect(() => { if (tweaks.density) setDensity(tweaks.density); }, [tweaks.density]);

  const filtered = React.useMemo(() => {
    let result = projects.slice();
    if (filter.type !== "Tümü") result = result.filter((p) => p.type === filter.type);
    if (sort === "yeni") result.sort((a, b) => b.year - a.year);
    if (sort === "eski") result.sort((a, b) => a.year - b.year);
    if (sort === "alfabe") result.sort((a, b) => a.title.localeCompare(b.title, "tr"));
    return result;
  }, [projects, filter, sort]);

  const gridCols = {
    sparse: "repeat(2, 1fr)",
    comfortable: "repeat(3, 1fr)",
    dense: "repeat(4, 1fr)",
  }[density];

  return (
    <div className="page-in" onMouseMove={(e) => setPos({ x: e.clientX, y: e.clientY })}>
      <div style={{ padding: "56px 32px 24px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16 }}>
          <h1 className="t-display" style={{ fontSize: "clamp(56px, 7vw, 104px)", margin: 0, fontStyle: "italic" }}>
            Arşiv
          </h1>
          <span className="t-mono" style={{ color: "var(--muted)" }}>Bergama · İzmir</span>
        </div>
        <p style={{ color: "var(--muted)", maxWidth: 640, fontSize: 16, lineHeight: 1.5, margin: 0 }}>
          Mimarlık pratiğimden seçili projeler; konut, villa ve restorasyon.
          Türüne göre filtreleyin.
        </p>
      </div>

      <FilterBar
        types={window.PROJECT_TYPES}
        filter={filter}
        setFilter={setFilter}
        density={density}
        setDensity={setDensity}
        sort={sort}
        setSort={setSort}
        count={filtered.length}
        total={projects.length}
      />

      {density === "list" ? (
        <div style={{ padding: "8px 32px 88px" }}>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "60px 1.8fr 1.2fr 1fr 1fr 80px",
              gap: 24,
              padding: "16px 0 12px",
            }}
            className="t-mono"
          >
            <span style={{ color: "var(--muted)" }}>№</span>
            <span style={{ color: "var(--muted)" }}>Proje</span>
            <span style={{ color: "var(--muted)" }}>Konum</span>
            <span style={{ color: "var(--muted)" }}>Tür</span>
            <span style={{ color: "var(--muted)" }}>Durum</span>
            <span style={{ color: "var(--muted)", textAlign: "right" }}>Yıl</span>
          </div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
            {filtered.map((p, i) => (
              <ProjectRow
                key={p.id}
                project={p}
                idx={i}
                navigate={navigate}
                hovered={hovered}
                setHovered={setHovered}
              />
            ))}
            <li style={{ borderTop: "1px solid var(--line-soft)" }} />
          </ul>
          {hovered && (
            <div
              style={{
                position: "fixed",
                left: Math.min(pos.x + 24, window.innerWidth - 280),
                top: Math.min(pos.y - 180, window.innerHeight - 380),
                width: 260,
                zIndex: 50,
                pointerEvents: "none",
              }}
            >
              <ProjectImage project={filtered.find((p) => p.id === hovered)} index={0} ratio="3 / 4" showMeta={false} />
            </div>
          )}
        </div>
      ) : (
        <div style={{ padding: "32px 32px 88px" }}>
          <div style={{ display: "grid", gridTemplateColumns: gridCols, gap: density === "sparse" ? 56 : density === "comfortable" ? 32 : 20, rowGap: density === "sparse" ? 96 : density === "comfortable" ? 56 : 36 }}>
            {filtered.map((p) => (
              <ProjectCard key={p.id} project={p} navigate={navigate} density={density} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

window.Archive = Archive;
