/* global React, ReactDOM, PageShell, PageHero, Crown, Icon, formatPrice, useT, useLang */
const { useState, useMemo, useEffect } = React;
const PER_PAGE = 12;

const Lightbox = ({ project, onClose }) => {
  const [imgIdx, setImgIdx] = useState(0);

  useEffect(() => { setImgIdx(0); }, [project && project.id]);

  useEffect(() => {
    const gallery = project ? (project.gallery && project.gallery.length ? project.gallery : [project.img]) : [];
    const onKey = e => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") setImgIdx(i => Math.max(0, i - 1));
      if (e.key === "ArrowRight") setImgIdx(i => Math.min(gallery.length - 1, i + 1));
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = project ? "hidden" : "";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [project, onClose]);

  const lang = useLang();
  const t = (window.NH_TRANSLATIONS && window.NH_TRANSLATIONS[lang]) || (window.NH_TRANSLATIONS && window.NH_TRANSLATIONS.EN) || {};
  const tp = t.projectsPage || {};
  const tc = t.common || {};

  if (!project) return null;

  const gallery = project.gallery && project.gallery.length ? project.gallery : [project.img];
  const currentImg = gallery[imgIdx];

  return (
    <div className="lightbox is-open" onClick={onClose}>
      <div className="lightbox__inner" onClick={e => e.stopPropagation()}>
        <button className="lightbox__close" onClick={onClose}><Icon name="close" size={16}/></button>

        {/* Gallery column */}
        <div className="lightbox__gallery">
          <div className="lightbox__gallery-main">
            {(() => {
              const isPng = currentImg.toLowerCase().endsWith('.png');
              const imgStyle = isPng
                ? { objectFit: 'contain', padding: '16px', boxSizing: 'border-box', background: '#fff' }
                : {};
              return <img src={currentImg} alt={project.name} key={currentImg} style={imgStyle}/>;
            })()}
            {imgIdx > 0 && (
              <button className="lightbox__nav lightbox__nav--prev" onClick={() => setImgIdx(i => i - 1)} aria-label="Previous image">
                <span className="lb-arrow-flip"><Icon name="arrow" size={17}/></span>
              </button>
            )}
            {imgIdx < gallery.length - 1 && (
              <button className="lightbox__nav lightbox__nav--next" onClick={() => setImgIdx(i => i + 1)} aria-label="Next image">
                <Icon name="arrow" size={17}/>
              </button>
            )}
            {gallery.length > 1 && (
              <div className="lightbox__dots">
                {gallery.map((_, i) => (
                  <button key={i} className={"lightbox__dot" + (i === imgIdx ? " is-active" : "")} onClick={() => setImgIdx(i)} aria-label={"Image " + (i + 1)}></button>
                ))}
              </div>
            )}
          </div>
          {gallery.length > 1 && (
            <div className="lightbox__gallery-controls">
              <button
                className={"lightbox__gallery-arrow" + (imgIdx === 0 ? " is-disabled" : "")}
                onClick={() => setImgIdx(i => Math.max(0, i - 1))}
                aria-label="Previous image"
              >
                <span className="lb-arrow-flip"><Icon name="arrow" size={16}/></span>
              </button>
              <span className="lightbox__gallery-counter">{imgIdx + 1} / {gallery.length}</span>
              <button
                className={"lightbox__gallery-arrow" + (imgIdx === gallery.length - 1 ? " is-disabled" : "")}
                onClick={() => setImgIdx(i => Math.min(gallery.length - 1, i + 1))}
                aria-label="Next image"
              >
                <Icon name="arrow" size={16}/>
              </button>
            </div>
          )}
          {gallery.length > 1 && (
            <div className="lightbox__thumbs">
              {gallery.map((img, i) => (
                <button key={i} className={"lightbox__thumb" + (i === imgIdx ? " is-active" : "")} onClick={() => setImgIdx(i)}>
                  <img src={img} alt={"View " + (i + 1)}/>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Content column */}
        <div className="lightbox__body">
          <div className="lightbox__body-top">
            <span className="eyebrow"><Crown/> {project.tag}</span>
            <h2 className="lightbox__title">{project.name}</h2>
            {project.description && (
              <p className="lightbox__desc">{project.description}</p>
            )}
          </div>

          <div className="lightbox__specs">
            <div className="lightbox__specs-heading">{tp.buildingParams || "Building parameters"}</div>
            {project.specs && project.specs.livingArea && (
              <div className="lightbox__spec-row">
                <span className="lightbox__spec-label">{tp.livingArea || "Living area"}</span>
                <span className="lightbox__spec-dots"></span>
                <span className="lightbox__spec-value">{project.specs.livingArea}</span>
              </div>
            )}
            <div className="lightbox__spec-row">
              <span className="lightbox__spec-label">{project.specs && project.specs.livingArea ? (tp.totalArea || "Total area") : (tp.floorArea || "Floor area")}</span>
              <span className="lightbox__spec-dots"></span>
              <span className="lightbox__spec-value">{project.area} m²</span>
            </div>
            {project.specs && project.specs.garage && (
              <div className="lightbox__spec-row">
                <span className="lightbox__spec-label">{tp.garage || "Garage"}</span>
                <span className="lightbox__spec-dots"></span>
                <span className="lightbox__spec-value">{project.specs.garage}</span>
              </div>
            )}
            <div className="lightbox__spec-row">
              <span className="lightbox__spec-label">{tp.levels || "Levels"}</span>
              <span className="lightbox__spec-dots"></span>
              <span className="lightbox__spec-value">{project.levels}</span>
            </div>
            {project.rooms && (
              <div className="lightbox__spec-row">
                <span className="lightbox__spec-label">{tp.rooms || "Rooms"}</span>
                <span className="lightbox__spec-dots"></span>
                <span className="lightbox__spec-value">{project.rooms}</span>
              </div>
            )}
            {project.specs && project.specs.cubicCapacity && (
              <div className="lightbox__spec-row">
                <span className="lightbox__spec-label">{tp.cubicCapacity || "Cubic capacity"}</span>
                <span className="lightbox__spec-dots"></span>
                <span className="lightbox__spec-value">{project.specs.cubicCapacity}</span>
              </div>
            )}
            {project.specs && project.specs.height && (
              <div className="lightbox__spec-row">
                <span className="lightbox__spec-label">{tp.heightLabel || "Height"}</span>
                <span className="lightbox__spec-dots"></span>
                <span className="lightbox__spec-value">{project.specs.height}</span>
              </div>
            )}
            {project.specs && project.specs.roofSlope && (
              <div className="lightbox__spec-row">
                <span className="lightbox__spec-label">{tp.roofSlope || "Roof slope"}</span>
                <span className="lightbox__spec-dots"></span>
                <span className="lightbox__spec-value">{project.specs.roofSlope}</span>
              </div>
            )}
            {project.specs && project.specs.roofArea && (
              <div className="lightbox__spec-row">
                <span className="lightbox__spec-label">{tp.roofArea || "Roof area"}</span>
                <span className="lightbox__spec-dots"></span>
                <span className="lightbox__spec-value">{project.specs.roofArea}</span>
              </div>
            )}
            {project.specs && project.specs.plotSize && (
              <div className="lightbox__spec-row">
                <span className="lightbox__spec-label">{tp.plotSize || "Min. plot size"}</span>
                <span className="lightbox__spec-dots"></span>
                <span className="lightbox__spec-value">{project.specs.plotSize}</span>
              </div>
            )}
            {project.specs && project.specs.uValue && (
              <div className="lightbox__spec-row">
                <span className="lightbox__spec-label">{tp.uValue || "Wall U-value"}</span>
                <span className="lightbox__spec-dots"></span>
                <span className="lightbox__spec-value">{project.specs.uValue}</span>
              </div>
            )}
            {project.specs && project.specs.windows && (
              <div className="lightbox__spec-row">
                <span className="lightbox__spec-label">{tp.windowsLabel || "Windows"}</span>
                <span className="lightbox__spec-dots"></span>
                <span className="lightbox__spec-value">{project.specs.windows}</span>
              </div>
            )}
            {project.specs && project.specs.assembly && (
              <div className="lightbox__spec-row">
                <span className="lightbox__spec-label">{tp.assemblyLabel || "Assembly time"}</span>
                <span className="lightbox__spec-dots"></span>
                <span className="lightbox__spec-value">{project.specs.assembly}</span>
              </div>
            )}
          </div>

          {project.included && project.included.length > 0 && (
            <div className="lightbox__included">
              <div className="lightbox__included-title">{tp.kitIncludes || "Kit includes"}</div>
              <ul className="lightbox__included-list">
                {project.included.map((item, i) => (
                  <li key={i}>
                    <Icon name="check" size={12}/>
                    <span>{item}</span>
                  </li>
                ))}
              </ul>
            </div>
          )}

          <div className="lightbox__footer">
            <a href="Contacts.html" className="btn btn--lg lightbox__cta" onClick={onClose}>
              {tp.requestQuote || "Request a quote"} <span className="arrow"><Icon name="arrow" size={14}/></span>
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};

const ProjectCard = ({ p, onOpen, levelSingular, levelPlural, viewDetails, roomsLabel }) => (
  <button className="project" onClick={() => onOpen(p)}>
    <div className="project__media">
      <span className="project__tag">{p.tag}</span>
      <img src={p.img} alt={p.name} loading="lazy"/>
      <div className="project__hover-hint">{viewDetails || "View details"}</div>
    </div>
    <div className="project__head">
      <h3>{p.name}</h3>
    </div>
    <div className="project__meta">
      <span><Icon name="area" size={14}/> {p.area} m²</span>
      <span><Icon name="levels" size={14}/> {p.levels} {p.levels > 1 ? (levelPlural || "levels") : (levelSingular || "level")}</span>
      {p.rooms && <span><Icon name="rooms" size={14}/> {p.rooms} {roomsLabel || "rooms"}</span>}
    </div>
  </button>
);

const CatalogInner = () => {
  const lang = useLang();
  const tr = ((window.NH_TRANSLATIONS && window.NH_TRANSLATIONS[lang]) || (window.NH_TRANSLATIONS && window.NH_TRANSLATIONS.EN) || {});
  const t = tr.projectsPage || {};
  const tc = tr.common || {};
  const all = window.NH_DATA.projects;
  const allLabel = t.all || "All";
  const tags = [allLabel, ...Array.from(new Set(all.map(p => p.tag)))];
  const [filter, setFilter] = useState(allLabel);
  const [page, setPage] = useState(1);
  const [openProject, setOpenProject] = useState(null);

  const filtered = useMemo(() => filter === allLabel ? all : all.filter(p => p.tag === filter), [filter, all, allLabel]);
  const totalPages = Math.ceil(filtered.length / PER_PAGE);
  const pageItems = filtered.slice((page - 1) * PER_PAGE, page * PER_PAGE);

  const handleFilter = tag => { setFilter(tag); setPage(1); };
  const handlePage = n => {
    setPage(n);
    const el = document.getElementById("catalog-top");
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 100, behavior: "smooth" });
  };

  return (
    <>
      <PageHero eyebrow={t.eyebrow || "Our Catalogue"} title={t.h2 || "Projects"} lead={t.lead || "House kits in active production. Click any house for specifications."}/>
      <section className="section" id="catalog-top">
        <div className="container">
          <div className="catalog__bar">
            <div className="catalog__filters">
              {tags.map(tag => (
                <button key={tag} className={filter === tag ? "is-active" : ""} onClick={() => handleFilter(tag)}>{tag}</button>
              ))}
            </div>
            <div className="catalog__count">
              {filtered.length} {t.filterCount || "projects"}
              {totalPages > 1 && ` · ${t.page || "page"} ${page} / ${totalPages}`}
            </div>
          </div>
          <div className="catalog__grid">
            {pageItems.map(p => (
              <ProjectCard
                key={p.id}
                p={p}
                onOpen={setOpenProject}
                levelSingular={tc.levelSingular}
                levelPlural={tc.levelPlural}
                viewDetails={t.viewDetails}
                roomsLabel={t.roomsLabel}
              />
            ))}
          </div>
          {totalPages > 1 && (
            <div className="pagination">
              {page > 1 && <a href="#" onClick={e => { e.preventDefault(); handlePage(page - 1); }} style={{ fontSize:18 }}>‹</a>}
              {Array.from({ length: totalPages }, (_, i) => i + 1).map(n => (
                <a key={n} href="#" className={n === page ? "is-active" : ""} onClick={e => { e.preventDefault(); handlePage(n); }}>{n}</a>
              ))}
              {page < totalPages && <a href="#" onClick={e => { e.preventDefault(); handlePage(page + 1); }} style={{ fontSize:18 }}>›</a>}
            </div>
          )}
        </div>
      </section>
      <section className="divider">
        <div className="container">
          <div className="divider__text">{t.noCta || "Don't see your"} <em>{t.noCta2 || "house"}</em>{t.noCta3 || "? We design custom."}</div>
          <a href="Contacts.html" className="btn btn--lg">{t.cta || "Get in Touch"} <span className="arrow"><Icon name="arrow" size={14}/></span></a>
        </div>
      </section>
      <Lightbox project={openProject} onClose={() => setOpenProject(null)}/>
    </>
  );
};

const Projects = () => (
  <PageShell current="projects">
    <CatalogInner/>
  </PageShell>
);

ReactDOM.createRoot(document.getElementById("root")).render(<Projects/>);
