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

/* ───────────────────────── Reveal-on-scroll hook ───────────────────────── */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('is-in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.08, rootMargin: '0px 0px -8% 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

/* ───────────────────────── Nav ───────────────────────── */
function Nav({ active, onJump }) {
  const [top, setTop] = useState(true);
  useEffect(() => {
    const onScroll = () => setTop(window.scrollY < 40);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const items = [
    { id: 'work',    label: 'Work' },
    { id: 'about',   label: 'About' },
    { id: 'contact', label: 'Contact' },
  ];
  return (
    <nav className={`nav ${top ? 'is-top' : ''}`} aria-label="Primary">
      <button className="nav__brand" onClick={() => onJump('top')} aria-label="EzeRom home">
        <img className="mark" src="assets/logo-eze-white.png" alt="EzeRom" />
        <span style={{ fontSize: 13, letterSpacing: '0.22em', textTransform: 'uppercase', fontFamily: "'JetBrains Mono', monospace", color: 'var(--muted)' }}>
          ezerom.com.ar
        </span>
      </button>
      <ul className="nav__list">
        {items.map((it) => (
          <li key={it.id}>
            <button
              className={active === it.id ? 'is-active' : ''}
              onClick={() => onJump(it.id)}
            >
              {it.label}
            </button>
          </li>
        ))}
      </ul>
      <div className="nav__index">© MMXXVI</div>
    </nav>
  );
}

/* ───────────────────────── Hero ───────────────────────── */
function Hero() {
  return (
    <header className="hero" id="top" data-screen-label="Hero">
      <div className="hero__feature">
        <div className="tile__placeholder" aria-hidden="true" style={{ position: 'absolute', inset: 0 }}>
          <div className="id">FEATURED</div>
          <div className="lbl">[ drop image ]</div>
        </div>
        <image-slot id="hero-feature" shape="rect" fit="cover" placeholder=""></image-slot>
      </div>
      <div className="hero__meta reveal reveal--slow">
        <div>Based<span>Buenos Aires, AR</span></div>
        <div>Discipline<span>Photography</span></div>
        <div>Selected<span>2019 — 2026</span></div>
        <div>Status<span>Booking Q3 / Q4</span></div>
      </div>
      <div className="hero__scroll">↓ Scroll · 042 frames</div>
    </header>
  );
}

/* ───────────────────────── Tile + Gallery ───────────────────────── */
const TILES = [
  { id: 'f001', shape: 'p23', title: 'K.O / Julieta',  loc: 'Caballito · 2026' },
  { id: 'f002', shape: 'p43', title: 'Micaela',     loc: 'Caballito · 2025' },
  { id: 'f003', shape: 'p35', title: 'The Silence',            loc: 'Loft · 2021' },
  { id: 'f004', shape: 'sq',  title: 'Mirror / 02',            loc: 'Studio · 2024' },
  { id: 'f005', shape: 'p34', title: 'Delfina',                 loc: 'Caballito · 2023' },
  { id: 'f006', shape: 'p23', title: 'Studio / 09',            loc: 'Studio · 2019' },
  { id: 'f007', shape: 'p43', title: 'Rochi',                 loc: 'Caballito · 2018' },
  { id: 'f008', shape: 'l32', title: 'Body / 01',              loc: 'Studio · 2024' },
  { id: 'f009', shape: 'p35', title: 'Milagros',        loc: 'Caballito · 2021' },
  { id: 'f010', shape: 'p23', title: 'Vero',                    loc: 'La Plata · 2021' },
  { id: 'f011', shape: 'p43', title: 'Book / 12',         loc: 'Caballito · 2026' },
  { id: 'f012', shape: 'sq',  title: 'Luli',                   loc: 'Studio · 2019' },
  { id: 'f013', shape: 'p34', title: 'Behind',                 loc: 'Loft · 2023' },
  { id: 'f014', shape: 'p35', title: 'Guillermina',       loc: 'Studio · 2019' },
  { id: 'f015', shape: 'p23', title: 'Abby / 03',            loc: 'Palermo · 2019' },
];

function Tile({ idx, item }) {
  const num = String(idx + 1).padStart(3, '0');
  return (
    <figure className={`tile tile--${item.shape} reveal`} data-tile-id={item.id}>
      <div className="tile__inner">
        <div className="tile__placeholder" aria-hidden="true">
          <div className="id">{num} / {String(TILES.length).padStart(3, '0')}</div>
          <div className="lbl">[ drop image ]</div>
        </div>
        <image-slot
          id={`gallery-${item.id}`}
          shape="rect"
          fit="cover"
          placeholder=""
        ></image-slot>
      </div>
      <figcaption className="tile__caption">
        <span className="ttl">{item.title}</span>
        <span className="num">{num} · {item.loc}</span>
      </figcaption>
    </figure>
  );
}

function Gallery() {
  return (
    <section className="section" id="work" data-screen-label="Work — Masonry gallery">
      <div className="section__head reveal">
        <div className="section__num">§ 01 / WORK</div>
        <h2 className="section__title">Selected · 2019 — 2026</h2>
        <div className="section__tail">{TILES.length} frames · Updated 04 / 2026</div>
      </div>
      <div className="gallery">
        {TILES.map((t, i) => <Tile key={t.id} idx={i} item={t} />)}
      </div>
    </section>
  );
}

/* ───────────────────────── About ───────────────────────── */
function About() {
  return (
    <section className="section" id="about" data-screen-label="About">
      <div className="section__head reveal">
        <div className="section__num">§ 02 / ABOUT</div>
        <h2 className="section__title">The Studio</h2>
        <div className="section__tail">EST. 2019</div>
      </div>
      <div className="about">
        <div className="about__portrait reveal">
          <div className="tile__placeholder" aria-hidden="true" style={{ position: 'absolute', inset: 0 }}>
            <div className="id">PORTRAIT</div>
            <div className="lbl">[ drop image ]</div>
          </div>
          <image-slot id="about-portrait" shape="rect" fit="cover" placeholder=""></image-slot>
        </div>
        <div className="about__body reveal">
          <p>
            Based in Buenos Aires, my photography focuses on the body, intimacy, and light — creating editorial and sensual portraits that prioritize precision over decoration.
          </p>
          <p>
            Working on commission with models and agencies, the studio approaches each session as a unique piece: one idea, one light, one image.
          </p>
          <div className="about__stats">
            <div>Sessions<span>120+</span></div>
            <div>Publications<span>14</span></div>
            <div>Models<span>80+</span></div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ───────────────────────── Contact ───────────────────────── */
function ContactForm() {
  const KINDS = ['Editorial', 'Boudoir', 'Studio', 'Other'];
  const formRef = useRef(null);
  const [submitted, setSubmitted] = useState(false);
  const [submittedEmail, setSubmittedEmail] = useState('');
  const [kind, setKind] = useState('Editorial');
  const [sending, setSending] = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setSending(true);

    // Force a render cycle
    await new Promise(resolve => setTimeout(resolve, 0));

    const formData = new FormData(formRef.current);
    const name = formData.get('name');
    const email = formData.get('email');
    const message = formData.get('message');
    const date = formData.get('date');

    try {
      const res = await fetch('https://formspree.io/f/xzdwdjya', {
        method: 'POST',
        body: JSON.stringify({ name, email, type: kind, date, message }),
        headers: { 'Content-Type': 'application/json' }
      });

      if (res.ok) {
        await new Promise(resolve => setTimeout(resolve, 600));
        setSubmittedEmail(email);
        setSubmitted(true);
      }
    } catch (err) {
      console.error('Form error:', err);
    } finally {
      setSending(false);
    }
  }

  if (submitted) {
    return (
      <div className="form__success is-in">
        Message sent.
        <p>I'll respond within 48 hours · {submittedEmail}</p>
      </div>
    );
  }

  return (
    <form className="form reveal" ref={formRef} onSubmit={handleSubmit}>
      <div className="form__field">
        <label className="form__label" htmlFor="f-name">Name <span className="req">*</span></label>
        <input
          id="f-name" className="form__input" type="text" autoComplete="name"
          name="name" placeholder="Your name" required
        />
      </div>
      <div className="form__field">
        <label className="form__label" htmlFor="f-email">Email <span className="req">*</span></label>
        <input
          id="f-email" className="form__input" type="email" autoComplete="email"
          name="email" placeholder="you@domain.com" required
        />
      </div>
      <div className="form__field">
        <span className="form__label">Type</span>
        <div className="form__chips">
          {KINDS.map((k) => (
            <button
              key={k} type="button"
              className={`chip ${kind === k ? 'is-on' : ''}`}
              onClick={() => setKind(k)}
            >{k}</button>
          ))}
        </div>
      </div>
      <div className="form__field">
        <label className="form__label" htmlFor="f-date">Date</label>
        <input
          id="f-date" className="form__input" type="text"
          name="date" placeholder="Estimated month / year"
        />
      </div>
      <div className="form__field form__field--textarea">
        <label className="form__label" htmlFor="f-msg">Message <span className="req">*</span></label>
        <textarea
          id="f-msg" className="form__textarea" name="message"
          placeholder="Tell me about the session, idea, references…" rows={3} required
        />
      </div>
      <button type="submit" className="form__submit" disabled={sending}>
        {sending ? 'Sending…' : 'Send message'}
        <span className="arrow">→</span>
      </button>
    </form>
  );
}

function Contact() {
  return (
    <section className="section" id="contact" data-screen-label="Contact">
      <div className="section__head reveal">
        <div className="section__num">§ 03 / CONTACT</div>
        <h2 className="section__title">Let's Work Together</h2>
        <div className="section__tail">Buenos Aires · GMT-3</div>
      </div>
      <div className="contact">
        <div className="reveal">
          <h3 className="contact__intro">
            <span>Send me</span><br />
            <span className="thin">your idea.</span>
          </h3>
          <div className="contact__direct">
            Direct
            <a href="mailto:hola@ezerom.com.ar">hola@ezerom.com.ar</a>
            <a href="https://instagram.com/ezerom" target="_blank" rel="noreferrer">@ezerom · Instagram</a>
          </div>
        </div>
        <ContactForm />
      </div>
    </section>
  );
}

/* ───────────────────────── Image Modal ───────────────────────── */
function ImageModal({ src, onClose }) {
  if (!src) return null;

  useEffect(() => {
    const handleEsc = (e) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', handleEsc);
    return () => document.removeEventListener('keydown', handleEsc);
  }, [onClose]);

  return (
    <div
      style={{
        position: 'fixed',
        inset: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.7)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 1000,
        cursor: 'pointer',
      }}
      onClick={onClose}
    >
      <div
        style={{
          position: 'relative',
          maxWidth: '90vw',
          maxHeight: '90vh',
          cursor: 'default',
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <img
          src={src}
          alt="Enlarged view"
          style={{
            width: '100%',
            height: '100%',
            objectFit: 'contain',
            borderRadius: '4px',
          }}
        />
        <button
          onClick={onClose}
          style={{
            position: 'absolute',
            top: '12px',
            left: '12px',
            width: '40px',
            height: '40px',
            borderRadius: '50%',
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            border: 'none',
            cursor: 'pointer',
            fontSize: '24px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: '#000',
            fontWeight: 'bold',
          }}
        >
          ✕
        </button>
      </div>
    </div>
  );
}

/* ───────────────────────── Export Button (dev only) ───────────────────────── */
function ExportButton() {
  const isLocal = typeof window !== 'undefined' && (
    window.location.hostname === 'localhost' ||
    window.location.hostname === '127.0.0.1' ||
    window.location.hostname.startsWith('192.168.')
  );

  if (!isLocal) return null;

  function exportImages() {
    const data = localStorage.getItem('image-slots-state');
    if (!data) {
      alert('No images to export. Load some images first.');
      return;
    }

    const blob = new Blob([data], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = '.image-slots.state.json';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }

  return (
    <button
      onClick={exportImages}
      style={{
        position: 'fixed',
        bottom: 20,
        right: 20,
        padding: '10px 16px',
        backgroundColor: '#333',
        color: '#fff',
        border: 'none',
        borderRadius: '6px',
        cursor: 'pointer',
        fontSize: '12px',
        fontFamily: "'JetBrains Mono', monospace",
        zIndex: 999,
        opacity: 0.7,
        transition: 'opacity 0.2s'
      }}
      onMouseEnter={(e) => e.target.style.opacity = '1'}
      onMouseLeave={(e) => e.target.style.opacity = '0.7'}
    >
      Export Images
    </button>
  );
}

/* ───────────────────────── Footer ───────────────────────── */
function Footer() {
  return (
    <footer className="footer">
      <div>© 2026 Ezequiel Romera<br />All photographs reserved.</div>
      <div className="footer__center">EZEROM.COM.AR</div>
      <div className="footer__right">
        <a href="mailto:hola@ezerom.com.ar">Email</a>
        <a href="https://instagram.com/ezerom" target="_blank" rel="noreferrer">Instagram</a>
      </div>
    </footer>
  );
}

/* ───────────────────────── App ───────────────────────── */
function App() {
  const [active, setActive] = useState('work');
  const [modalSrc, setModalSrc] = useState(null);
  const isLocal = window.location.hostname === 'localhost' ||
                  window.location.hostname === '127.0.0.1' ||
                  window.location.hostname.startsWith('192.168.');
  useReveal();

  useEffect(() => {
    const ids = ['work', 'about', 'contact'];
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) setActive(e.target.id);
      });
    }, { rootMargin: '-40% 0px -50% 0px', threshold: 0 });
    ids.forEach((id) => {
      const el = document.getElementById(id);
      if (el) io.observe(el);
    });
    return () => io.disconnect();
  }, []);

  useEffect(() => {
    const handleImageClick = (e) => {
      if (e.detail?.src) {
        console.log('Modal event received, opening modal');
        setModalSrc(e.detail.src);
      }
    };

    document.addEventListener('image-click', handleImageClick);
    return () => document.removeEventListener('image-click', handleImageClick);
  }, []);

  function jump(id) {
    if (id === 'top') { window.scrollTo({ top: 0, behavior: 'smooth' }); return; }
    const el = document.getElementById(id);
    if (!el) return;
    const top = el.getBoundingClientRect().top + window.scrollY - 60;
    window.scrollTo({ top, behavior: 'smooth' });
  }

  return (
    <>
      <Nav active={active} onJump={jump} />
      <Hero />
      <main>
        <Gallery />
        <About />
        <Contact />
      </main>
      <Footer />
      <ExportButton />
      <ImageModal src={modalSrc} onClose={() => setModalSrc(null)} />
    </>
  );
}

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