/* Momo Studio — Portfolio (organic floating circles) + Case study panel */

const { useState, useMemo, useEffect, useRef } = React;

// Deterministic but pleasing organic placement.
// Generates radius + center for each project on a 1380x1100 stage.
function layoutDiscs(items, opts={}) {
  const W = opts.W || 1380, H = opts.H || 1100;
  const sizeMap = { large: 280, medium: 200, small: 150 };
  // Hand-tuned constellation anchors per index. We weave around the canvas.
  // Positions in % of stage. Carefully placed to avoid overlap.
  const anchors = [
    [0.20, 0.28], [0.46, 0.18], [0.72, 0.30], [0.88, 0.16],
    [0.14, 0.58], [0.34, 0.50], [0.58, 0.50], [0.80, 0.58],
    [0.22, 0.84], [0.46, 0.80], [0.66, 0.86], [0.86, 0.80],
    [0.08, 0.42], [0.38, 0.32], [0.62, 0.18], [0.10, 0.74],
    [0.30, 0.68], [0.54, 0.66], [0.76, 0.72], [0.90, 0.42],
  ];
  return items.map((it, i) => {
    const a = anchors[i % anchors.length];
    const sz = sizeMap[it.size || 'medium'];
    // Tiny deterministic jitter so it doesn't feel gridded
    const j = (n)=> ((Math.sin((i+1)*n)*1000)%1) * 16 - 8;
    return {
      ...it,
      x: a[0]*W + j(7.7),
      y: a[1]*H + j(3.3),
      r: sz,
    };
  });
}

const PortfolioDisc = ({ item, dimmed, onClick, mouse }) => {
  // Subtle parallax — each disc drifts slightly with mouse position
  const ref = useRef(null);
  const [enter, setEnter] = useState(false);
  useEffect(()=>{
    const t = setTimeout(()=>setEnter(true), 50 + Math.random()*400);
    return ()=>clearTimeout(t);
  },[]);
  const dx = mouse ? (mouse.x - 0.5) * 16 : 0;
  const dy = mouse ? (mouse.y - 0.5) * 16 : 0;
  return (
    <button
      ref={ref}
      className={`pt-disc ${dimmed?'dim':''}`}
      onClick={onClick}
      style={{
        left: item.x + dx,
        top:  item.y + dy,
        width: item.r,
        height: item.r,
        opacity: enter ? (dimmed?0.5:1) : 0,
        transform: enter ? 'translate(-50%,-50%) scale(1)' : 'translate(-50%,-50%) scale(0.6)',
      }}
      aria-label={item.title}
    >
      <img src={item.image} alt={item.title} loading="lazy"/>
      <div className="pt-yr">{item.year}</div>
      <div className="pt-label">{item.title}</div>
    </button>
  );
};

const PortfolioList = ({ items, onPick }) => (
  <div className="pt-list">
    {items.map((it, i) => (
      <div className="row reveal" key={it.id} onClick={()=>onPick(it)}>
        <div className="num">{String(i+1).padStart(2,'0')}</div>
        <div className="ttl">{it.title}</div>
        <div className="sub">{it.subtitle} · {it.location}</div>
        <div className="yr">{it.year}</div>
        <div className="arrow">→</div>
      </div>
    ))}
  </div>
);

const Portfolio = ({ projects, themes, onPick }) => {
  // Latest 4 — sort by year, then by source order
  const latest = useMemo(() => {
    return [...projects]
      .map((p, i) => ({ p, i }))
      .sort((a, b) => (b.p.year - a.p.year) || (a.i - b.i))
      .slice(0, 4)
      .map(x => x.p);
  }, [projects]);

  return (
    <section className="section" id="portfolio" style={{background:'var(--bg)'}}>
      <div className="container">
        <div className="s-head reveal">
          <h2>Latest<br/><span style={{fontStyle:'italic', color:'var(--moss)'}}>works.</span></h2>
          <div className="meta">
            <div style={{marginTop: 8}}>
              Four most recent projects from the studio.<br/>
              See the full index for everything 2014–2026.
            </div>
          </div>
        </div>

        <div className="latest-grid">
          {latest.map(p => (
            <button key={p.id} className="latest-card reveal" onClick={() => onPick(p)}>
              <div className="latest-frame">
                <img src={p.image} alt={p.title} loading="lazy"/>
              </div>
              <div className="latest-meta">
                <div className="latest-title">{p.title}</div>
                <div className="latest-sub">{p.location}</div>
              </div>
            </button>
          ))}
        </div>

        <div className="latest-all reveal">
          <a href="Projects.html">All projects →</a>
        </div>
      </div>
    </section>
  );
};

const CaseStudy = ({ item, onClose }) => {
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  const open = !!item;
  return (
    <>
      <div className={`case-overlay ${open?'open':''}`} onClick={onClose}/>
      <aside className={`case-panel ${open?'open':''}`} aria-hidden={!open}>
        {item && (
          <>
            <div className="case-close">
              <span>{item.theme.replace('-',' · ')} · {item.year}</span>
              <button onClick={onClose}>Close ✕</button>
            </div>
            <img className="case-hero" src={item.image} alt={item.title}/>
            <div className="case-body">
              <div className="eyebrow">{item.type}</div>
              <h2>{item.title}</h2>
              <div className="case-sub">{item.subtitle}</div>

              <div className="case-data">
                <div><div className="label">Location</div><div className="val">{item.location}</div></div>
                <div><div className="label">Year</div><div className="val">{item.year}</div></div>
                <div><div className="label">Role</div><div className="val">{item.role}</div></div>
                <div><div className="label">Status</div><div className="val">{item.status}</div></div>
                <div><div className="label">Client</div><div className="val">{item.client}</div></div>
                <div><div className="label">Collaborators</div><div className="val">{item.collaborators}</div></div>
              </div>

              <p className="case-summary">{item.summary}</p>

              {item.gallery && item.gallery.length > 1 && (
                <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap: 16, marginTop: 36}}>
                  {item.gallery.map((src,i) => (
                    <img key={i} src={src} alt="" style={{aspectRatio:'4/3', objectFit:'cover', width:'100%', borderRadius: 4}}/>
                  ))}
                </div>
              )}
            </div>
          </>
        )}
      </aside>
    </>
  );
};

Object.assign(window, { Portfolio, CaseStudy });
