/* global React, ReactDOM, MainMenu, TypesMenu, ContactForm */
const { useState, useEffect } = React;

/* Image URL helper — points at the backend image route. The backend falls back
   to Unsplash for seeded ids, so the grid is populated before any upload. */
const HIMG = (filename, size = "web") => /^https?:\/\//.test(filename) ? filename : `/api/images/${size}/${encodeURIComponent(filename)}`;

function HomeTest() {
  const [overlay, setOverlay] = useState(null); // null | "menu" | "contact"
  const [typesOpen, setTypesOpen] = useState(false);
  const [tiles, setTiles] = useState(null); // null = loading
  const [galleries, setGalleries] = useState(null); // "+" category list (null = loading)

  // Fetch home grid from the API on mount.
  useEffect(() => {
    fetch("/api/home-grid")
      .then((r) => r.json())
      .then((data) => setTiles(Array.isArray(data) ? data : []))
      .catch(() => setTiles([]));
  }, []);

  // Fetch gallery categories so the "+" menu matches the galleries page.
  useEffect(() => {
    fetch("/api/galleries")
      .then((r) => r.json())
      .then((list) => setGalleries(Array.isArray(list) ? list : []))
      .catch(() => setGalleries([]));
  }, []);

  // lock body scroll while a full overlay is open
  useEffect(() => {
    document.body.style.overflow = (overlay) ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [overlay]);

  const openContact = () => { setOverlay("contact"); setTypesOpen(false); };
  const nav = (where) => {
    if (where === "portfolio") window.location.href = "../galleries_test/Galleries_Test.html";
    if (where === "about") window.location.href = "../about_test/About_Test.html";
  };
  const pickType = (key) => { window.location.href = `../galleries_test/Galleries_Test.html#${encodeURIComponent(key)}`; };

  const dim = typesOpen;

  return (
    <React.Fragment>
      {/* Fixed chrome */}
      <div className="h-logo" onClick={() => { setOverlay(null); setTypesOpen(false); window.scrollTo({ top: 0, behavior: "smooth" }); }}>
        <div className="lname">NICKO TRENCHEV</div>
        <div className="lsub">STUDIO</div>
      </div>
      <button className="h-chrome-label h-menu-btn" onClick={() => setOverlay("menu")}>MENU</button>
      <button className="h-chrome-label h-contact-btn" onClick={openContact}>CONTACT</button>

      <button className={`h-plus ${typesOpen ? "open" : ""}`} onClick={() => setTypesOpen((o) => !o)} aria-label="Gallery types">
        <svg viewBox="0 0 64 64">
          <line x1="32" y1="14" x2="32" y2="50" />
          <line x1="14" y1="32" x2="50" y2="32" />
        </svg>
      </button>

      {/* Photo grid */}
      <main>
        <div className={`h-grid ${dim ? "dim" : ""}`}>
          {(tiles || []).map((t, i) => (
            <div key={t.id ?? i} className={`h-tile ${t.is_bw ? "bw" : ""} ${t.is_tall ? "tall" : ""}`}>
              <div className="protected-image">
                <img src={HIMG(t.filename)} alt="" loading={i < 6 ? "eager" : "lazy"} onContextMenu={(e) => e.preventDefault()} draggable="false" />
                <div className="img-guard"></div>
              </div>
              <div className="cap-scrim"></div>
              {(t.caption_name || t.caption_venue) && (
                <div className="cap">
                  <div className="who">
                    <div className="n">{t.caption_name}</div>
                    <div className="v">{t.caption_venue}</div>
                  </div>
                  {t.caption_tag && <div className="tag">{t.caption_tag}</div>}
                </div>
              )}
            </div>
          ))}
        </div>
        <div className="h-grid-foot"></div>
      </main>

      {/* Types menu (over dimmed grid) — same component & data as the galleries page */}
      {typesOpen && galleries && <TypesMenu galleries={galleries} onPick={pickType} />}

      {/* Full overlays */}
      {overlay === "menu" && (
        <MainMenu onClose={() => setOverlay(null)} onContact={openContact} onNav={nav} />
      )}
      {overlay === "contact" && <ContactForm onClose={() => setOverlay(null)} />}
    </React.Fragment>
  );
}

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