/* AKMBD Website — Work
   Featured-projects CAROUSEL (scroll-snap, prev/next, swipe, keyboard) +
   an expandable full-screen project DETAIL overlay (gallery + full info). */

const byId = (id) => AKM_PROJECTS.find(p => p.id === id);
const FEATURED = AKM_FEATURED.map(byId).filter(Boolean);

/* ---------------- Carousel ---------------- */
function Work({ onOpen }) {
  const trackRef = useRef(null);
  const [idx, setIdx] = useState(0);
  const n = FEATURED.length;

  const goTo = useCallback((i) => {
    const t = trackRef.current; if (!t) return;
    const clamped = (i + n) % n;
    const slide = t.children[clamped];
    if (slide) t.scrollTo({ left: slide.offsetLeft - t.offsetLeft, behavior:'smooth' });
  }, [n]);

  useEffect(() => {
    const t = trackRef.current; if (!t) return;
    let raf = null;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = null;
        const w = t.clientWidth || 1;
        setIdx(Math.round(t.scrollLeft / w));
      });
    };
    t.addEventListener('scroll', onScroll, { passive:true });
    return () => t.removeEventListener('scroll', onScroll);
  }, []);

  const onKey = (e) => {
    if (e.key === 'ArrowRight') { e.preventDefault(); goTo(idx+1); }
    if (e.key === 'ArrowLeft') { e.preventDefault(); goTo(idx-1); }
  };

  const Ctrl = ({ dir, onClick }) => {
    const [h, setH] = useState(false);
    return (
      <button onClick={onClick} onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)}
        aria-label={dir<0?'Previous project':'Next project'}
        style={{ width:52, height:52, borderRadius:2, cursor:'pointer', display:'inline-flex', alignItems:'center', justifyContent:'center',
          background: h?'var(--accent)':'transparent', color: h?'#fff':'var(--ink-1)',
          border:'1px solid var(--line-2)', borderColor: h?'var(--accent)':'var(--line-2)', transition:'all .2s' }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          {dir<0 ? <polyline points="15 18 9 12 15 6"/> : <polyline points="9 18 15 12 9 6"/>}
        </svg>
      </button>
    );
  };

  return (
    <section id="work" style={{ background:'var(--surface-1)', padding:'clamp(64px,9vw,120px) 0' }}>
      <div style={{ maxWidth:1320, margin:'0 auto', padding:'0 clamp(20px,5vw,48px)' }}>
        {/* header */}
        <div className="akm-work-head" style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', gap:24, flexWrap:'wrap', marginBottom:'clamp(32px,4vw,52px)' }}>
          <Reveal>
            <Eyebrow>Selected Work</Eyebrow>
            <h2 className="akm-h1" style={{ marginTop:18 }}>Featured Projects</h2>
          </Reveal>
          <Reveal style={{ display:'flex', alignItems:'center', gap:14 }}>
            <span style={{ fontFamily:'var(--font-display)', fontSize:13, letterSpacing:'0.14em', color:'var(--ink-3)', minWidth:62 }}>
              <span style={{ color:'var(--ink-1)' }}>{String(idx+1).padStart(2,'0')}</span> / {String(n).padStart(2,'0')}
            </span>
            <div style={{ display:'flex', gap:10 }}>
              <Ctrl dir={-1} onClick={()=>goTo(idx-1)} />
              <Ctrl dir={1} onClick={()=>goTo(idx+1)} />
            </div>
          </Reveal>
        </div>
      </div>

      {/* track (full-bleed, padded inner) */}
      <div ref={trackRef} className="akm-carousel" tabIndex={0} onKeyDown={onKey}
        style={{ display:'flex', overflowX:'auto', scrollSnapType:'x mandatory', scrollBehavior:'smooth', outline:'none' }}>
        {FEATURED.map((p, i) => (
          <article key={p.id} style={{ flex:'0 0 100%', scrollSnapAlign:'center', padding:'0 clamp(20px,5vw,48px)' }}>
            <div style={{ maxWidth:1320, margin:'0 auto' }}>
              <div className="akm-slide" style={{ display:'grid', gridTemplateColumns:'1.32fr 1fr', gap:'clamp(24px,4vw,56px)', alignItems:'stretch' }}>
                <button onClick={()=>onOpen(p)} className="akm-slide-media" aria-label={`Open ${p.title}`}
                  style={{ all:'unset', cursor:'pointer', position:'relative', display:'block' }}>
                  <div className="akm-img-clip" style={{ position:'relative', overflow:'hidden' }}>
                    <ProjPhoto img={p.img} ratio="4 / 3" label={p.title} />
                  </div>
                </button>
                <div style={{ display:'flex', flexDirection:'column', justifyContent:'center', paddingRight:'2%' }}>
                  <div style={{ display:'flex', alignItems:'center', gap:14, marginBottom:18 }}>
                    <span style={{ fontFamily:'var(--font-display)', fontSize:13, letterSpacing:'0.14em', color:'var(--accent)' }}>{String(i+1).padStart(2,'0')}</span>
                    <span style={{ width:24, height:1, background:'var(--line-2)' }}></span>
                    <span style={{ fontFamily:'var(--font-display)', fontSize:11.5, letterSpacing:'0.18em', textTransform:'uppercase', color:'var(--ink-3)' }}>{p.cat}</span>
                  </div>
                  <h3 className="akm-h2" style={{ marginBottom:18 }}>{p.title}</h3>
                  <div style={{ display:'flex', flexWrap:'wrap', gap:'8px 22px', marginBottom:20 }}>
                    {[['Location',p.place],['Scope',p.scope]].map(([k,v]) => (
                      <div key={k}>
                        <div style={{ fontFamily:'var(--font-display)', fontSize:10, letterSpacing:'0.16em', textTransform:'uppercase', color:'var(--ink-4)' }}>{k}</div>
                        <div style={{ fontFamily:'var(--font-body)', fontSize:14.5, color:'var(--ink-1)', marginTop:3 }}>{v}</div>
                      </div>
                    ))}
                  </div>
                  <p className="akm-body" style={{ maxWidth:440, marginBottom:26 }}>{p.blurb}</p>
                  <div><ArrowLink onClick={()=>onOpen(p)}>View project</ArrowLink></div>
                </div>
              </div>
            </div>
          </article>
        ))}
      </div>

      {/* progress ticks */}
      <div style={{ maxWidth:1320, margin:'clamp(28px,4vw,44px) auto 0', padding:'0 clamp(20px,5vw,48px)', display:'flex', gap:8 }}>
        {FEATURED.map((p,i) => (
          <button key={p.id} onClick={()=>goTo(i)} aria-label={`Go to ${p.title}`}
            style={{ flex:1, height:6, border:'none', padding:0, cursor:'pointer',
              background: i===idx ? 'var(--accent)' : 'var(--line-2)', transition:'background .3s' }} />
        ))}
      </div>
    </section>
  );
}

/* ---------------- Detail overlay ---------------- */
function ProjectDetail({ p, onClose, onNav }) {
  useEffect(() => {
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', onKey); };
  }, [onClose]);

  const all = FEATURED.length ? FEATURED : AKM_PROJECTS;
  const i = all.findIndex(x => x.id === p.id);
  const next = all[(i+1) % all.length];

  return (
    <div className="akm-overlay" style={{ position:'fixed', inset:0, zIndex:80, background:'var(--surface-0)', overflowY:'auto' }}>
      {/* top bar */}
      <div style={{ position:'sticky', top:0, zIndex:5, background:'rgba(248,248,250,.85)', backdropFilter:'blur(14px)', WebkitBackdropFilter:'blur(14px)', borderBottom:'1px solid var(--line-1)' }}>
        <div style={{ maxWidth:1320, margin:'0 auto', padding:'0 clamp(20px,5vw,48px)', height:64, display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <span style={{ fontFamily:'var(--font-display)', fontSize:11.5, letterSpacing:'0.18em', textTransform:'uppercase', color:'var(--ink-3)' }}>
            {p.cat}
          </span>
          <button onClick={onClose} aria-label="Close project"
            style={{ background:'none', border:'none', cursor:'pointer', display:'inline-flex', alignItems:'center', gap:10,
              fontFamily:'var(--font-display)', fontSize:11.5, letterSpacing:'0.16em', textTransform:'uppercase', color:'var(--ink-2)' }}>
            Close
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><line x1="5" y1="5" x2="19" y2="19"/><line x1="19" y1="5" x2="5" y2="19"/></svg>
          </button>
        </div>
      </div>

      {/* hero */}
      <div style={{ maxWidth:1320, margin:'0 auto', padding:'clamp(28px,4vw,52px) clamp(20px,5vw,48px) 0' }}>
        <Eyebrow>{p.scope}</Eyebrow>
        <h1 className="akm-display" style={{ fontSize:'clamp(36px,5vw,72px)', margin:'18px 0 0' }}>{p.title}</h1>
        <div style={{ marginTop:'clamp(28px,4vw,44px)' }}>
          <ProjPhoto img={p.img} ratio="16 / 9" label={p.title} />
        </div>
      </div>

      {/* body: overview + meta sidebar */}
      <div style={{ maxWidth:1320, margin:'0 auto', padding:'clamp(40px,5vw,64px) clamp(20px,5vw,48px) 0' }}>
        <div className="akm-detail-grid" style={{ display:'grid', gridTemplateColumns:'1.6fr 1fr', gap:'clamp(32px,5vw,72px)' }}>
          <div>
            <h2 className="akm-h3" style={{ marginBottom:20 }}>Overview</h2>
            {p.overview.map((para, k) => (
              <p key={k} className="akm-body-lg" style={{ marginBottom:18, maxWidth:620 }}>{para}</p>
            ))}
          </div>
          <aside style={{ borderTop:'1px solid var(--line-2)', paddingTop:24 }}>
            {[['Location',p.place],['Scope',p.scope],['Size',p.size]].map(([k,v]) => (
              <div key={k} style={{ display:'flex', justifyContent:'space-between', gap:16, padding:'12px 0', borderBottom:'1px solid var(--line-1)' }}>
                <span style={{ fontFamily:'var(--font-display)', fontSize:10.5, letterSpacing:'0.16em', textTransform:'uppercase', color:'var(--ink-4)' }}>{k}</span>
                <span style={{ fontFamily:'var(--font-body)', fontSize:14.5, color:'var(--ink-1)', textAlign:'right' }}>{v}</span>
              </div>
            ))}
            <div style={{ paddingTop:18 }}>
              <div style={{ fontFamily:'var(--font-display)', fontSize:10.5, letterSpacing:'0.16em', textTransform:'uppercase', color:'var(--ink-4)', marginBottom:12 }}>Services</div>
              <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
                {p.services.map(s => (
                  <span key={s} style={{ fontFamily:'var(--font-body)', fontSize:12.5, color:'var(--ink-2)', border:'1px solid var(--line-2)', padding:'6px 12px' }}>{s}</span>
                ))}
              </div>
            </div>
          </aside>
        </div>
      </div>

      {/* gallery */}
      <div style={{ maxWidth:1320, margin:'0 auto', padding:'clamp(40px,5vw,64px) clamp(20px,5vw,48px) 0' }}>
        <h2 className="akm-h3" style={{ marginBottom:22 }}>Gallery</h2>
        <div className="akm-gallery" style={{ display:'grid', gridTemplateColumns:'repeat(2, 1fr)', gap:'clamp(12px,1.6vw,20px)' }}>
          {(() => {
            const real = p.gallery || [];
            const fillers = real.length > 0 ? (real.length < (p.galleryCount || 0) ? 1 : 0) : 2;
            const items = [
              ...real.map(g => ({ kind:'img', img:g })),
              ...Array.from({ length: fillers }).map(() => ({ kind:'ph' })),
            ];
            return items.map((it, k) => {
              const wide = k % 3 === 0;
              const ratio = wide ? '16 / 10' : '4 / 3';
              const st = wide ? { gridColumn:'1 / -1' } : {};
              return it.kind === 'img'
                ? <ProjPhoto key={k} img={it.img} ratio={ratio} style={st} label={`${p.title} image ${k+1}`} />
                : <Placeholder key={k} label="Photography forthcoming" ratio={ratio} tag="Placeholder" style={st} />;
            });
          })()}
        </div>
      </div>

      {/* next project */}
      <div style={{ maxWidth:1320, margin:'clamp(48px,6vw,80px) auto 0', padding:'0 clamp(20px,5vw,48px) clamp(64px,8vw,110px)' }}>
        <button onClick={()=>onNav(next)} style={{ all:'unset', cursor:'pointer', display:'block', width:'100%' }}>
          <div style={{ borderTop:'1px solid var(--line-2)', paddingTop:28, display:'flex', alignItems:'flex-end', justifyContent:'space-between', gap:24, flexWrap:'wrap' }}>
            <div>
              <div style={{ fontFamily:'var(--font-display)', fontSize:11, letterSpacing:'0.18em', textTransform:'uppercase', color:'var(--ink-4)', marginBottom:12 }}>Next Project</div>
              <h3 className="akm-h2">{next.title}</h3>
            </div>
            <span style={{ fontFamily:'var(--font-display)', fontSize:13, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--accent)', display:'inline-flex', alignItems:'center', gap:10 }}>
              View <span style={{ fontSize:16 }}>&rarr;</span>
            </span>
          </div>
        </button>
      </div>
    </div>
  );
}

window.Work = Work;
window.ProjectDetail = ProjectDetail;
