/* global React */
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP, useCallback: useCallbackP } = React;

const CATS = ["All", "Renovation", "Investment", "In-Progress"];

function BeforeAfter({ before, after }) {
  const [x, setX] = useStateP(50);
  const [dragging, setDragging] = useStateP(false);
  const ref = useRefP(null);

  const onMove = (clientX) => {
    if (!ref.current) return;
    const r = ref.current.getBoundingClientRect();
    const pct = Math.max(0, Math.min(100, ((clientX - r.left) / r.width) * 100));
    setX(pct);
  };

  useEffectP(() => {
    if (!dragging) return;
    const mm = (e) => onMove(e.clientX);
    const tm = (e) => { if (e.touches[0]) onMove(e.touches[0].clientX); };
    const up = () => setDragging(false);
    window.addEventListener("mousemove", mm);
    window.addEventListener("mouseup", up);
    window.addEventListener("touchmove", tm);
    window.addEventListener("touchend", up);
    return () => {
      window.removeEventListener("mousemove", mm);
      window.removeEventListener("mouseup", up);
      window.removeEventListener("touchmove", tm);
      window.removeEventListener("touchend", up);
    };
  }, [dragging]);

  const onHoverMove = (e) => {
    if (window.matchMedia("(pointer: fine)").matches && !dragging) {
      onMove(e.clientX);
    }
  };

  return (
    <div
      className="beforeafter"
      ref={ref}
      style={{ "--x": x + "%" }}
      onMouseMove={onHoverMove}
      onMouseDown={(e) => { setDragging(true); onMove(e.clientX); }}
      onTouchStart={(e) => { setDragging(true); if (e.touches[0]) onMove(e.touches[0].clientX); }}
    >
      <div className="img before" style={{ backgroundImage: `url(${before})` }} />
      <div className="img after" style={{ backgroundImage: `url(${after})` }} />
      <span className="tag t-before">Before</span>
      <span className="tag t-after">After</span>
      <div className="handle" />
      <span className="hint">Hover or drag</span>
    </div>
  );
}

function ProjectModal({ project, onClose }) {
  const [imgIdx, setImgIdx] = useStateP(0);

  useEffectP(() => {
    setImgIdx(0);
  }, [project]);

  if (!project) return null;

  const total = project.gallery.length;
  const prev = () => setImgIdx(i => (i - 1 + total) % total);
  const next = () => setImgIdx(i => (i + 1) % total);

  return (
    <div
      className="modal-overlay is-open"
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div className="project-modal" role="dialog" aria-modal="true">
        {/* Image carousel */}
        <div className="modal-stage">
          <div
            className="modal-img"
            style={{ backgroundImage: `url(${project.gallery[imgIdx]})` }}
          />
          {total > 1 && (
            <>
              <button className="modal-nav prev" onClick={prev} aria-label="Previous image">
                <svg width="16" height="12" viewBox="0 0 16 12" fill="none">
                  <path d="M15 6H1M1 6L6 1M1 6L6 11" stroke="currentColor" strokeWidth="1.4"/>
                </svg>
              </button>
              <button className="modal-nav next" onClick={next} aria-label="Next image">
                <svg width="16" height="12" viewBox="0 0 16 12" fill="none">
                  <path d="M1 6H15M15 6L10 1M15 6L10 11" stroke="currentColor" strokeWidth="1.4"/>
                </svg>
              </button>
              <div className="modal-img-count">{imgIdx + 1} / {total}</div>
            </>
          )}
          {/* Header overlay */}
          <div className="modal-img-header">
            <div>
              <div className="modal-cat">{project.kind}</div>
              <div className="modal-title">{project.name}</div>
              <div className="modal-loc">{project.loc}</div>
            </div>
            <button className="modal-close" onClick={onClose} aria-label="Close">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M1 1L15 15M15 1L1 15" stroke="currentColor" strokeWidth="1.4"/>
              </svg>
            </button>
          </div>
        </div>

        {/* Thumbnail strip */}
        {total > 1 && (
          <div className="modal-thumbs">
            {project.gallery.map((g, i) => (
              <button
                key={i}
                className={"modal-thumb" + (i === imgIdx ? " is-active" : "")}
                style={{ backgroundImage: `url(${g})` }}
                onClick={() => setImgIdx(i)}
                aria-label={`Image ${i + 1}`}
              />
            ))}
          </div>
        )}

        {/* Before / after */}
        {project.hasBeforeAfter && (
          <div style={{ padding: "0 28px" }}>
            <div style={{
              fontFamily: "var(--ff-display)", fontSize: 11, letterSpacing: "0.22em",
              textTransform: "uppercase", color: "var(--brown)", marginBottom: 12, marginTop: 8,
            }}>Before & After</div>
            <BeforeAfter before={project.before} after={project.after} />
          </div>
        )}

        {/* Project info */}
        <div className="modal-info">
          <div className="panel-stats">
            <div className="panel-stat"><div className="lbl">Year</div><div className="v">{project.year}</div></div>
            <div className="panel-stat"><div className="lbl">Category</div><div className="v">{project.cat}</div></div>
            <div className="panel-stat"><div className="lbl">Size</div><div className="v">{project.sqft}</div></div>
            <div className="panel-stat"><div className="lbl">Bed/Bath</div><div className="v">{project.beds}</div></div>
          </div>
          <p>{project.blurb}</p>
        </div>
      </div>
    </div>
  );
}

function ProjectsSection() {
  const projects = window.PROJECTS;
  const [filter, setFilter] = useStateP("All");
  const [openId, setOpenId] = useStateP(null);

  const filtered = filter === "All" ? projects : projects.filter(p => p.cat === filter);
  const active = projects.find(p => p.id === openId);

  useEffectP(() => {
    const onKey = (e) => { if (e.key === "Escape") setOpenId(null); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  useEffectP(() => {
    document.body.style.overflow = openId ? "hidden" : "";
  }, [openId]);

  return (
    <section id="projects" className="section projects" data-screen-label="Projects">
      <div className="section-header">
        <div>
          <div className="index">03 · Projects</div>
          <h2>Selected work <span className="italic-accent">across South Florida.</span></h2>
        </div>
        <div className="header-right">
          <p className="lede" style={{ margin: 0 }}>
            {window.COPY.projectsLede}
          </p>
        </div>
      </div>

      {/* Filter tabs */}
      <div className="project-filters">
        {CATS.map(c => (
          <button
            key={c}
            className={"filter-btn" + (filter === c ? " is-active" : "")}
            onClick={() => setFilter(c)}
          >{c}</button>
        ))}
      </div>

      <div className="projects-grid">
        {filtered.map(p => (
          <div
            key={p.id}
            className="project-tile"
            onClick={() => setOpenId(p.id)}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => { if (e.key === "Enter") setOpenId(p.id); }}
          >
            <div className="cover" style={{ backgroundImage: `url(${p.cover})` }} />
            <span className="badge-tag">{p.cat}</span>
            <div className="corner-arrow">
              <svg width="11" height="11" viewBox="0 0 11 11" fill="none"><path d="M1 10L10 1M10 1H3M10 1V8" stroke="currentColor" strokeWidth="1.3"/></svg>
            </div>
            <div className="meta">
              <div>
                <div className="t">{p.name}</div>
                <div className="sub">{p.loc}</div>
              </div>
              <div className="sub year">{p.year}</div>
            </div>
          </div>
        ))}
      </div>

      {openId && (
        <ProjectModal project={active} onClose={() => setOpenId(null)} />
      )}
    </section>
  );
}

window.ProjectsSection = ProjectsSection;
