// DANOVI — 갤러리 (고정핀 4 + 전체 그리드 + 분야 필터 + 상세 오버레이)
function PinIcon() {
  return (
    <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true">
      <path fill="currentColor" d="M15.2 2.6a1 1 0 0 1 1.4 0l4.8 4.8a1 1 0 0 1 0 1.4l-1.3 1.3a1 1 0 0 1-1 .25l-3.1 3.1.4 3.4a1 1 0 0 1-.29.82l-.94.94a1 1 0 0 1-1.41 0l-3.3-3.3-4.9 4.9a.75.75 0 1 1-1.06-1.06l4.9-4.9-3.3-3.3a1 1 0 0 1 0-1.41l.94-.94a1 1 0 0 1 .82-.29l3.4.4 3.1-3.1a1 1 0 0 1 .25-1z"/>
    </svg>
  );
}

function WorksOverlay({ work, onClose }) {
  const [idx, setIdx] = React.useState(0);
  const shots = work.shots;
  React.useEffect(() => {
    const key = e => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') setIdx(i => Math.min(i + 1, shots.length - 1));
      if (e.key === 'ArrowLeft') setIdx(i => Math.max(i - 1, 0));
    };
    addEventListener('keydown', key);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { removeEventListener('keydown', key); document.body.style.overflow = prev; };
  }, [shots.length, onClose]);

  return (
    <div className="dn-ov" role="dialog" aria-modal="true" aria-label={work.title}>
      <button className="dn-ov-close" onClick={onClose} aria-label="닫기">✕</button>
      <div className="dn-ov-head">
        <span className="dn-ov-cat">{work.field}</span>
        <h2>{work.title}</h2>
        <p>{work.sub}</p>
        {work.note && <span className="dn-ov-note">{work.note}</span>}
        {work.href && <a className="dn-ov-case" href={work.href}>{work.id === 'ebook' ? '전자책 보기' : '케이스 보기'} <span className="arw">→</span></a>}
      </div>
      <div className="dn-ov-stage">
        <img key={idx} src={shots[idx]} alt={work.title + ' ' + (idx + 1)} />
        <button className="dn-ov-nav prev" disabled={idx === 0} onClick={() => setIdx(i => i - 1)} aria-label="이전">←</button>
        <button className="dn-ov-nav next" disabled={idx === shots.length - 1} onClick={() => setIdx(i => i + 1)} aria-label="다음">→</button>
      </div>
      <div className="dn-ov-foot">
        <span>{work.title}</span>
        <span className="dn-ov-count">{idx + 1} / {shots.length}</span>
      </div>
      {shots.length > 1 && (
        <div className="dn-ov-thumbs">
          {shots.map((s, i) => (
            <button key={s} className={i === idx ? 'on' : ''} onClick={() => setIdx(i)} aria-label={(i + 1) + '번째 컷'}>
              <img src={s} alt="" loading="lazy" />
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function GalleryCell({ w, onOpen }) {
  return (
    <button className={'dn-g-cell' + (w.pinned ? ' pinned' : '')} onClick={() => onOpen(w)} data-id={w.id}>
      <span className="dn-g-img">
        <img src={w.sq || w.img} alt={w.title + ' ' + w.sub} loading={w.pinned ? 'eager' : 'lazy'}
             style={w.imgPos ? { objectPosition: 'center ' + w.imgPos } : null} />
        {w.pinned && <span className="dn-g-pin" aria-label="고정됨"><PinIcon /></span>}
        {!w.pinned && w.shots.length > 1 && <span className="dn-g-multi" aria-label={w.shots.length + '컷'}><i /><i /></span>}
      </span>
      <span className="dn-g-meta"><b>{w.title}</b><em>{caption(w)}</em></span>
    </button>
  );
}

function WorksPage() {
  const initial = (() => {
    try { return decodeURIComponent(new URLSearchParams(location.search).get('cat') || '전체'); } catch (e) { return '전체'; }
  })();
  const [cat, setCat] = React.useState(WORK_FIELDS.indexOf(initial) >= 0 ? initial : '전체');
  const [open, setOpen] = React.useState(null);
  const match = w => cat === '전체' || w.field === cat;
  const pinned = FEATURED.filter(match);
  /* 최근 작업을 대표작업 바로 뒤에 둡니다. 예전에는 ARCHIVE 만 그려서
     RECENT 가 데이터에만 있고 화면에 안 나오는 버그가 있었습니다. */
  const rest = RECENT.concat(ARCHIVE).filter(match);

  const pick = c => {
    setCat(c);
    try { history.replaceState(null, '', c === '전체' ? './works.html' : './works.html?cat=' + encodeURIComponent(c)); } catch (e) {}
  };

  return (
    <main data-screen-label="Gallery" className="dn-works-page">
      <div className="dn-wrap">
        {/* 상단 소개 — 한 줄. 첫 화면에서 고정핀이 바로 보이게 합니다. */}
        <section className="dn-gabout">
          <h1 className="dn-gabout-lead">문의부터 최종 파일까지, 대표가 직접 합니다.</h1>
          <div className="dn-gabout-side">
            <span className="dn-gabout-sub">1인 스튜디오 · 온라인 진행</span>
            <KakaoButton sm />
          </div>
        </section>

        <div className="dn-g-head">
          <h2>전체 작업</h2>
          <span className="dn-g-total">{GALLERY.length}</span>
        </div>
        <div className="dn-filter" role="tablist">
          {['전체'].concat(WORK_FIELDS).map(c => (
            <button key={c} role="tab" aria-selected={cat === c} className={cat === c ? 'on' : ''} onClick={() => pick(c)}>
              {c}<em>{c === '전체' ? GALLERY.length : countField(c)}</em>
            </button>
          ))}
        </div>
        <div className="dn-g-grid">
          {pinned.map(w => <GalleryCell key={w.id} w={w} onOpen={setOpen} />)}
          {rest.map(w => <GalleryCell key={w.id} w={w} onOpen={setOpen} />)}
        </div>
      </div>
      {open && <WorksOverlay work={open} onClose={() => setOpen(null)} />}
    </main>
  );
}
Object.assign(window, { WorksPage, WorksOverlay, GalleryCell });
