const { useState, useEffect, useRef } = React;

const ArrowRight = () => (
  <svg width="20" height="10" viewBox="0 0 20 10" fill="none">
    <line x1="0" y1="5" x2="16" y2="5" stroke="currentColor" strokeWidth="1"/>
    <polyline points="12,1 17,5 12,9" fill="none" stroke="currentColor" strokeWidth="1"/>
  </svg>
);

// ── CURSOR ────────────────────────────────────────────────────────────────────
function Cursor({ page }) {
  const ref = useRef(null);
  useEffect(() => {
    let rx = -200, ry = -200, cx = -200, cy = -200, raf;
    const move = e => { rx = e.clientX; ry = e.clientY; };
    const over  = e => {
      const t = e.target.closest('a,button,[data-hover]');
      if (ref.current) ref.current.classList.toggle('cursor--big', !!t);
    };
    const tick = () => {
      cx += (rx - cx) * 0.2; cy += (ry - cy) * 0.2;
      if (ref.current) { ref.current.style.left = cx+'px'; ref.current.style.top = cy+'px'; }
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseover', over);
    raf = requestAnimationFrame(tick);
    return () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseover', over); cancelAnimationFrame(raf); };
  }, []);
  const isContact = page === 'contact';
  return <div ref={ref} className={`cursor${isContact ? ' cursor--white' : ''}`} aria-hidden="true" />;
}

// ── NAV ───────────────────────────────────────────────────────────────────────
function Nav({ page, navigate }) {
  const isContact = page === 'contact';
  return (
    <nav className={isContact ? 'nav--contact' : ''}>
      <span className="nl" onClick={() => navigate('home')}>
        <img src="images/momonimo-logo.png" alt="momonimo" />
      </span>
      <ul className="nr">
        {[['events','events'],['about','about'],['contact','contact']].map(([id,label]) => (
          <li key={id}>
            <a className={page === id ? 'on' : ''} onClick={() => navigate(id)}>{label}</a>
          </li>
        ))}
      </ul>
    </nav>
  );
}

// ── HOME ──────────────────────────────────────────────────────────────────────
const HOME_ITEMS = [
  { id:'mesa-viva',         src:'images/mesa-viva-06.jpg',        gc:'1 / span 4'  },
  { id:'veganuary-fisga',   src:'images/veganuary-fisga-06.jpg',  gc:'7 / span 3'  },
  { id:'momonimo-x-athena', src:'images/momonimo-x-athena-01.jpg',gc:'2 / span 4'  },
  { id:'mushroom-vessel',   src:'images/mushroom-vessel-01.jpg',  gc:'8 / span 3'  },
  { id:'pop-ups',           src:'images/pop-ups-07.jpg',          gc:'1 / span 3'  },
  { id:'funky-ferments',    src:'images/funky-ferments-02.jpg',   gc:'5 / span 4'  },
  { id:'fathers-house',     src:'images/fathers-house-01.jpg',    gc:'3 / span 4'  },
];

function Home({ navigate }) {
  return (
    <div className="home-wrap">
      <div className="home-header">
        <div className="hg-wordmark">momonimo</div>
        <div className="hg-tagline">
          <span className="acid-underline">food as question. food as thinking.</span>
        </div>
      </div>
      <div className="home-grid">
        {HOME_ITEMS.map(item => {
          const proj = PROJECTS.find(p => p.id === item.id);
          return (
            <button key={item.id} className="hg-item"
              style={{ gridColumn: item.gc }}
              onClick={() => navigate('project', item.id)}>
              <div className="hg-img">
                <img src={item.src} alt={proj?.title || ''} />
              </div>
              <div className="hg-lbl"><span className="hg-lbl-n">{proj?.title}</span></div>
            </button>
          );
        })}
      </div>
      <div className="home-foot">
        <span className="home-foot-cta" onClick={() => navigate('contact')}>
          <span className="acid-underline">get in touch</span>
        </span>
      </div>
    </div>
  );
}

// ── SCATTERED GALLERY ─────────────────────────────────────────────────────────
// Smaller images, varied aspect ratios, generous whitespace
const GAL_SEQ = [
  { gc:'1 / span 6',  ar:'4/3'  },  { gc:'8 / span 4',  ar:'3/4'  },  // row: 50%L + 33%R
  { gc:'2 / span 7',  ar:'3/2'  },                                       // row: wide center
  { gc:'1 / span 4',  ar:'3/4'  },  { gc:'6 / span 5',  ar:'4/3'  },  // row: 33%L + 42%R
  { gc:'3 / span 7',  ar:'4/3'  },                                       // row: inset left
  { gc:'1 / span 5',  ar:'4/5'  },  { gc:'7 / span 4',  ar:'4/3'  },  // row: portrait + land
  { gc:'2 / span 8',  ar:'3/2'  },                                       // row: wide
  { gc:'1 / span 4',  ar:'4/3'  },  { gc:'6 / span 4',  ar:'3/4'  },  // row: two smalls
  { gc:'4 / span 6',  ar:'4/3'  },                                       // row: right-leaning
];

function ScatteredGallery({ items }) {
  const flat = [];
  items.forEach(item => {
    if (item.type === 'upcoming') flat.push({ upcoming: true });
    else if (item.type === 'full') flat.push({ src: item.src });
    else if (item.type === 'pair') item.srcs.forEach(s => flat.push({ src: s }));
  });
  return (
    <div className="sgal">
      {flat.map((img, i) => {
        const layout = GAL_SEQ[i % GAL_SEQ.length];
        if (img.upcoming) return (
          <div key={i} className="sgal-ph" style={{gridColumn:'1 / span 12'}}>upcoming · images soon</div>
        );
        return (
          <div key={i} className="sgal-cell" style={{gridColumn: layout.gc, '--ar': layout.ar}}>
            <img src={img.src} alt="" loading="lazy" />
          </div>
        );
      })}
    </div>
  );
}

// ── PROJECT ───────────────────────────────────────────────────────────────────
function ProjectDetail({ project: p, navigate }) {
  if (!p) return null;
  const texts    = p.textBlocks   || (p.text   ? [p.text]   : []);
  const textsPt  = p.textPtBlocks || (p.textPt ? [p.textPt] : []);
  return (
    <div className="pp">
      <button className="pp-back" onClick={() => navigate('home')}>← work</button>
      <div className="ph">
        <h1 className="ph-title">{p.title}</h1>
        {p.subtitle && <p className="ph-sub">{p.subtitle}</p>}
        <p className="ph-meta">{p.metaLine1} · {p.metaLine2}</p>
      </div>

      <ScatteredGallery items={p.gallery} />

      <div className="pp-text">
        {texts.map((t, i) => <p key={i} className="pt">{t}</p>)}
        {textsPt.map((t, i) => <p key={i} className="ptpt">{t}</p>)}

        {p.ticketUrl && (
          <div className="pp-links">
            <a href={p.ticketUrl} target="_blank" rel="noreferrer" className="ticket-btn">get tickets</a>
            {p.festivalUrl && (
              <a href={p.festivalUrl} target="_blank" rel="noreferrer" className="festival-link">
                <span className="acid-underline">Gentler Futures 2026</span>
              </a>
            )}
          </div>
        )}

        {p.menuLabel && p.menu.length > 0 && (
          <div className="pmenu">
            <span className="pmenu-label">{p.menuLabel}</span>
            {p.menu.map((section, si) => (
              <div key={si}>
                {section.edition && <span className="medition">{section.edition}</span>}
                <div className="mcourses">
                  {section.items.map((item, ii) => (
                    <div key={ii}>
                      <p className="mc-en">{item.en}</p>
                      <p className="mc-pt">{item.pt}</p>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}

        <div className="pcred">
          {p.credits.map((c, i) => (
            <div key={i}>
              <span className="cr-l">{c.label}</span>
              <span className="cr-v">{c.value}</span>
            </div>
          ))}
        </div>

        <div className="pnav">
          <button className="pnav-a" onClick={() => p.prev ? navigate('project', p.prev.id) : navigate('home')}>
            ← {p.prev ? p.prev.label : 'all work'}
          </button>
          {p.next && (
            <button className="pnav-a" onClick={() => navigate('project', p.next.id)}>
              {p.next.label} →
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ── EVENTS ────────────────────────────────────────────────────────────────────
function Events({ navigate }) {
  return (
    <div className="ep">
      <div className="evlist">
        {EVENTS.map((ev, i) => (
          <div key={i} className={`evrow${ev.past ? ' past' : ''}`}
               onClick={() => navigate('project', ev.id)}>
            <div className="ev-date">
              <strong>{ev.month}</strong>
              <span>{ev.year}</span>
            </div>
            <div>
              <p className="ev-title">{ev.title}</p>
              <p className="ev-sub">{ev.sub}</p>
            </div>
            {ev.upcoming && <span className="ev-tag">upcoming</span>}
          </div>
        ))}
      </div>
      <div className="newslet">
        <p className="newslet-l">
          <span className="acid-underline">keep me updated</span>
        </p>
        <p className="newslet-t">occasional news about events, dinners, and new work. no spam, no schedule.</p>
        <p className="newslet-tp">novidades ocasionais sobre eventos, jantares e projectos. sem spam, sem frequência.</p>
        <form className="newslet-form"
              action="https://app.kit.com/forms/9278977/subscriptions"
              method="post" target="_blank">
          <input type="email" name="email_address" className="newslet-i"
                 placeholder="your@email.com" required />
          <button type="submit" className="newslet-btn"><ArrowRight /></button>
        </form>
      </div>
    </div>
  );
}

// ── ABOUT ─────────────────────────────────────────────────────────────────────
function About({ navigate }) {
  return (
    <div className="ap">
      <h1 className="a-name"><span className="acid-underline">momonimo</span></h1>
      <div className="a-text">
        <p className="a-bio">
          Mónica Esteves is a food designer and food artist working at the edges
          of edible experience. plant-based by ethical conviction, she has been
          lately drawn to fermentation, foraging and the question of food waste.
          she works with local and seasonal ingredients, with slow and attentive
          processes, at the intersection of concept and sensation. the entry point
          is always through the body, through flavour, through the object.
        </p>
        <p className="a-bio-pt">
          food designer e food artist a trabalhar nas margens da experiência comestível.
          plant-based por convicção ética, ultimamente atraída pela fermentação, foraging
          e a questão do desperdício alimentar. ingredientes locais e sazonais, processos
          lentos e atentos.
        </p>
        <div className="cv-list">
          {[
            ['practice', 'food design · food art · supper clubs · events · workshops · food styling · food product development · consultancy · ceramics · space design'],
            ['research', 'MSc Product and Industrial Design, FBAUP, University of Porto'],
            ['training', 'MSc Architecture, FAUP · MSc Product and Industrial Design, FBAUP · Culinary Practices'],
            ['based in', 'Porto, Portugal'],
          ].map(([label, value]) => (
            <div key={label} className="cv-row">
              <span className="cv-l">{label}</span>
              <span className="cv-v">{value}</span>
            </div>
          ))}
        </div>
        <span className="a-cta" onClick={() => navigate('contact')}>
          <span className="acid-underline">get in touch</span>
        </span>
      </div>
    </div>
  );
}

// ── CONTACT ───────────────────────────────────────────────────────────────────
function Contact() {
  return (
    <div className="cp">
      <div>
        <h1 className="c-head">let's make<br />something alive.</h1>
        <p className="c-avail">
          available for food design projects, artistic collaborations, supper clubs,
          workshops, residencies and consultancy. interested in working with cultural
          institutions, independent spaces and programmes with real conceptual density.
        </p>
        <div className="c-links">
          <a href="https://www.instagram.com/mo.mo.ni.mo/" target="_blank" rel="noreferrer" className="c-link">
            <p className="cn">Instagram</p>
            <p className="cs">@mo.mo.ni.mo</p>
          </a>
          <a href="mailto:mo.mo.ni.mo@hotmail.com" className="c-link">
            <p className="cn">Email</p>
            <p className="cs">mo.mo.ni.mo@hotmail.com</p>
          </a>
        </div>
      </div>
    </div>
  );
}

// ── APP ───────────────────────────────────────────────────────────────────────
function App() {
  const [page, setPage] = useState('home');
  const [projectId, setProjectId] = useState(null);
  const [fading, setFading] = useState(false);

  const navigate = (newPage, newProjectId = null) => {
    setFading(true);
    setTimeout(() => {
      setPage(newPage);
      setProjectId(newProjectId || null);
      setFading(false);
      window.scrollTo({ top: 0, behavior: 'instant' });
    }, 180);
  };

  const project = projectId ? PROJECTS.find(p => p.id === projectId) : null;

  return (
    <div>
      <Cursor page={page} />
      <Nav page={page} navigate={navigate} />
      <div className={`pw${fading ? ' fading' : ''}`}>
        {page === 'home'    && <Home navigate={navigate} />}
        {page === 'project' && <ProjectDetail project={project} navigate={navigate} />}
        {page === 'events'  && <Events navigate={navigate} />}
        {page === 'about'   && <About navigate={navigate} />}
        {page === 'contact' && <Contact />}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
