// design.jsx — WorkSlide: one design work per slideshow page.
//
// Design collections reuse the same left/right fade-slideshow shell as the
// Tech projects (DetailView), but WITHOUT the cover page — each slide is a
// single work shown as one large hero image + 3–4 smaller stills, with the
// project write-up (회사 · 제작 시기 · 담당 분야 · 주 사용 툴) beside it.
//
// Every image is a <Slot> (image-slot) with an author-set `src` default, so it
// renders immediately yet stays drag-drop replaceable.
//
// Exports to window: WorkSlide

// ── Centered image lightbox ────────────────────────────────────────────────
// A click on a filled still opens it enlarged & centered (not fullscreen),
// over a dimmed backdrop, with an X close button. Backdrop / X / Esc closes.
// Built as a single reused DOM node so it works from anywhere in the slideshow.
function ensureLightbox() {
  let lb = document.getElementById("pf-lightbox");
  if (lb) return lb;
  lb = document.createElement("div");
  lb.id = "pf-lightbox";
  lb.className = "pf-lb";
  lb.innerHTML =
    '<div class="pf-lb__backdrop"></div>' +
    '<figure class="pf-lb__fig"><img class="pf-lb__img" alt="" /></figure>' +
    '<button class="pf-lb__close" aria-label="닫기" title="닫기 (Esc)">' +
    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg></button>';
  document.body.appendChild(lb);
  const close = () => lb.classList.remove("is-open");
  lb.querySelector(".pf-lb__backdrop").addEventListener("click", close);
  lb.querySelector(".pf-lb__close").addEventListener("click", close);
  lb.querySelector(".pf-lb__img").addEventListener("click", close);
  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape" && lb.classList.contains("is-open")) close();
  });
  return lb;
}

function openLightbox(src) {
  const lb = ensureLightbox();
  lb.querySelector(".pf-lb__img").src = src;
  lb.classList.add("is-open");
}

// Click handler for a still wrapper: enlarge the image, but ignore clicks on
// the slot's edit controls (Replace/Remove) and leave empty slots to their
// own drop/browse behaviour.
function zoomShot(e, slotId, caption) {
  const ne = e.nativeEvent || e;
  if (ne.composedPath) {
    const path = ne.composedPath();
    if (path.some((el) => el && el.getAttribute && el.getAttribute("data-act"))) return;
  }
  const slot = document.getElementById(slotId);
  if (!slot) return;
  if (slot.hasAttribute("data-filled")) {
    const img = slot.shadowRoot && slot.shadowRoot.querySelector("img");
    const src = img && (img.getAttribute("src") || img.src);
    if (src) openLightbox(src);
  } else if (window.omelette && window.omelette.writeFile) {
    // Editable mode only: open the file picker for an empty slot. On the
    // deployed (read-only) site, clicking does nothing.
    const input = slot.shadowRoot && slot.shadowRoot.querySelector('input[type="file"]');
    if (input) input.click();
  }
}

// Click on an EMPTY video slot opens its file picker (its own prompt is hidden
// behind the BANG logo). Filled slots are left to the video's own controls.
function pickVideoIfEmpty(e, slotId) {
  const ne = e.nativeEvent || e;
  if (ne.composedPath) {
    const path = ne.composedPath();
    if (path.some((el) => el && el.getAttribute && (el.getAttribute("data-pv") || el.getAttribute("data-act")))) return;
  }
  const slot = document.getElementById(slotId);
  if (!slot || slot.hasAttribute("data-filled")) return;
  if (!(window.omelette && window.omelette.writeFile)) return; // read-only deploy: no upload picker
  const input = slot.shadowRoot && slot.shadowRoot.querySelector('input[type="file"]');
  if (input) input.click();
}

function WorkSlide({ project, work, n }) {
  const colId = project.id;
  // ART work = 1 video (large) + 4 stills, ALL starting blank for the user to
  // fill (drop a muted MP4/MOV in the video, images in the 4 stills). Labels
  // are kept as drop prompts. `maxw` makes uploads store at full resolution so
  // they stay crisp when opened large in the lightbox.
  const imgs = [work.hero, ...(work.gallery || [])].filter(Boolean).slice(0, 4);
  while (imgs.length < 4) imgs.push({ label: "이미지 " + (imgs.length + 1) });
  return (
    <div className="pf-wslide">
      <div className="pf-wslide__images">
        <div className="pf-wslide__big"
          onClick={(e) => pickVideoIfEmpty(e, `w-${colId}-${work.id}-video`)}>
          <VideoSlot id={`w-${colId}-${work.id}-video`} label="동영상 추가 (무음 MP4 · MOV)" radius={16} />
          <div className="pf-wslide__bigph" aria-hidden="true"><BangLogo /></div>
        </div>
        <div className="pf-wslide__strip pf-wslide__strip--4">
          {imgs.map((g, i) =>
            <div className="pf-wslide__shot" key={i}
              onClick={(e) => zoomShot(e, `w-${colId}-${work.id}-g${i}`)}>
              <Slot id={`w-${colId}-${work.id}-g${i}`} label={g.label} radius={12} maxw={2200} />
              <div className="pf-wslide__shotph" aria-hidden="true"><BangLogo /></div>
            </div>
          )}
        </div>
      </div>

      <div className="pf-wslide__text">
        <span className="pf-wslide__num">{String(n).padStart(2, "0")}</span>
        <h3 className="pf-wslide__title">{work.title}</h3>
        <p className="pf-wslide__summary">{work.summary}</p>

        <dl className="pf-wslide__meta">
          <div className="pf-wslide__mrow">
            <dt className="pf-wslide__mlabel">회사</dt>
            <dd className="pf-wslide__mval">{work.company}</dd>
          </div>
          <div className="pf-wslide__mrow">
            <dt className="pf-wslide__mlabel">제작 시기</dt>
            <dd className="pf-wslide__mval">{work.period}</dd>
          </div>
          <div className="pf-wslide__mrow">
            <dt className="pf-wslide__mlabel">담당 분야</dt>
            <dd className="pf-wslide__mval">{work.role}</dd>
          </div>
        </dl>

        <div className="pf-wslide__tools">
          {work.tools.map((t) => <Chip key={t} subtle>{t}</Chip>)}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WorkSlide, openLightbox });
