/* Components — Tierra de Vino y Sal */

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

/* ---------- Helpers ---------- */
function useReveal(deps = []) {
  useEffect(() => {
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const reveal = (el) => el.classList.add('in');

    let io;
    const setup = () => {
      const els = document.querySelectorAll('.reveal:not(.in)');
      if (reduce || !('IntersectionObserver' in window)) {
        els.forEach(reveal);
        return;
      }
      io = new IntersectionObserver(entries => {
        entries.forEach(e => {
          if (e.isIntersecting) { reveal(e.target); io.unobserve(e.target); }
        });
      }, { threshold: 0, rootMargin: '0px 0px -8% 0px' });
      els.forEach(el => {
        // immediate reveal if already in viewport at mount
        const r = el.getBoundingClientRect();
        if (r.top < window.innerHeight * 0.95 && r.bottom > 0) {
          reveal(el);
        } else {
          io.observe(el);
        }
      });
    };

    const raf = requestAnimationFrame(() => requestAnimationFrame(setup));
    // Safety fallback: if anything is still hidden after 1.5s (e.g. observer
    // didn't fire because of layout quirks), force-reveal everything.
    const safety = setTimeout(() => {
      document.querySelectorAll('.reveal:not(.in)').forEach(reveal);
    }, 1500);

    return () => {
      cancelAnimationFrame(raf);
      clearTimeout(safety);
      if (io) io.disconnect();
    };
  }, deps);
}

function useCountdown(targetISO) {
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);
  const target = new Date(targetISO).getTime();
  const diff = Math.max(0, target - now);
  const days = Math.floor(diff / 86400000);
  const hours = Math.floor((diff / 3600000) % 24);
  const minutes = Math.floor((diff / 60000) % 60);
  const seconds = Math.floor((diff / 1000) % 60);
  return { days, hours, minutes, seconds };
}

function Editable({ tag = 'span', value, onChange, editable, ...rest }) {
  const Tag = tag;
  const ref = useRef(null);
  return (
    <Tag
      ref={ref}
      data-editable={editable ? 'true' : undefined}
      contentEditable={editable}
      suppressContentEditableWarning
      onBlur={e => onChange && onChange(e.currentTarget.innerText)}
      dangerouslySetInnerHTML={{ __html: value }}
      {...rest}
    />
  );
}

/* ---------- Nav ---------- */
function Nav({ t, lang, setLang }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const go = (id) => (e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: 'smooth' });
  };
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <a href="#top" className="nav-logo" onClick={go('top')}>
        Melissa Franco
        <small>Tierra de vino y sal</small>
      </a>
      <div className="nav-links">
        <a href="#synopsis" onClick={go('synopsis')}>{t.nav.synopsis}</a>
        <a href="#characters" onClick={go('characters')}>{t.nav.characters}</a>
        <a href="#world" onClick={go('world')}>{t.nav.world}</a>
        <a href="#author" onClick={go('author')}>{t.nav.author}</a>
        <a href="#buy" onClick={go('buy')}>{t.nav.buy}</a>
      </div>
      <div className="nav-right">
        <div className="lang-switch" role="group" aria-label="language">
          <button className={lang === 'es' ? 'active' : ''} onClick={() => setLang('es')}>ES</button>
          <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
        </div>
      </div>
    </nav>
  );
}

/* ---------- Hero ---------- */
function Hero({ t, heroVariant, editable, copy, setCopy }) {
  const cd = useCountdown('2026-05-18T09:00:00');
  return (
    <section className="hero" id="top" data-hero={heroVariant} data-screen-label="01 Hero">
      {heroVariant === 'video' && (
        <div className="hero-video-bg">
          <video src="assets/presentacion.mp4" autoPlay muted loop playsInline />
        </div>
      )}

      <div className="wrap">
        <div className="hero-grid">
          <div className="hero-copy">
            <div className="hero-eyebrow">
              <span className="eyebrow">{t.hero.eyebrow}</span>
              <span className="eyebrow" style={{opacity:.55}}>· {t.hero.release}</span>
            </div>

            <h1 className="hero-title">
              <Editable tag="span" editable={editable} value={copy.title_1} onChange={v=>setCopy({title_1:v})} /><br />
              {t.hero.title_2} <span className="amp">{t.hero.title_amp}</span><br />
              {t.hero.title_3}
            </h1>

            <div className="hero-author script">{t.hero.author}</div>

            <p className="hero-pitch">
              <Editable tag="span" editable={editable} value={copy.pitch} onChange={v=>setCopy({pitch:v})} />
            </p>

            <div className="hero-cta">
              <a className="btn" href="#buy" onClick={e=>{e.preventDefault();document.getElementById('buy').scrollIntoView({behavior:'smooth',block:'start'});}}>
                {t.hero.cta_buy} <span className="arrow">→</span>
              </a>
              <a className="btn btn-ghost" href="#video" onClick={e=>{e.preventDefault();document.getElementById('video').scrollIntoView({behavior:'smooth',block:'start'});}}>
                {t.hero.cta_video}
              </a>
            </div>

            <div className="countdown" aria-label="cuenta atrás">
              {[
                ['days', cd.days],
                ['hours', cd.hours],
                ['minutes', cd.minutes],
                ['seconds', cd.seconds],
              ].map(([k, v]) => (
                <div className="cd-box" key={k}>
                  <strong>{String(v).padStart(2,'0')}</strong>
                  <span>{t.countdown[k]}</span>
                </div>
              ))}
            </div>
          </div>

          {heroVariant !== 'video' && (
            <div className="hero-cover-stage">
              <svg className="hero-vine tl" viewBox="0 0 200 200" fill="none" stroke="currentColor" strokeWidth="1.2">
                <path d="M20 30 C 60 60, 100 40, 140 80 S 180 140, 160 180" />
                <ellipse cx="60" cy="50" rx="14" ry="9" transform="rotate(-30 60 50)" fill="currentColor" opacity=".3"/>
                <ellipse cx="100" cy="65" rx="14" ry="9" transform="rotate(20 100 65)" fill="currentColor" opacity=".25"/>
                <ellipse cx="140" cy="100" rx="14" ry="9" transform="rotate(-10 140 100)" fill="currentColor" opacity=".3"/>
              </svg>
              <div className={`hero-cover ${heroVariant === 'portrait' ? 'hero-cover-portrait' : ''}`}>
                {heroVariant === 'portrait'
                  ? <img src="assets/melissa-recortada.png" alt="Melissa Franco" />
                  : <img src="assets/portada-libro.jpeg" alt="Tierra de vino y sal — portada" />
                }
              </div>
              <svg className="hero-vine br" viewBox="0 0 200 200" fill="none" stroke="currentColor" strokeWidth="1.2">
                <path d="M20 30 C 60 60, 100 40, 140 80 S 180 140, 160 180" />
                <ellipse cx="60" cy="50" rx="14" ry="9" fill="currentColor" opacity=".3"/>
                <ellipse cx="100" cy="65" rx="14" ry="9" fill="currentColor" opacity=".25"/>
              </svg>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

/* ---------- Sinopsis ---------- */
function Synopsis({ t }) {
  return (
    <section className="synopsis" id="synopsis" data-screen-label="02 Sinopsis">
      <div className="wrap-narrow">
        <p className="synopsis-quote reveal">{t.synopsis.quote}</p>
        <div className="synopsis-grid reveal">
          <div className="synopsis-label">
            <div>{t.synopsis.label}</div>
          </div>
          <div className="synopsis-body">
            <span className="synopsis-place">{t.synopsis.place}</span>
            <p>{t.synopsis.p1}</p>
            <p>{t.synopsis.p2}</p>
            <p>{t.synopsis.p3}</p>
            <p>{t.synopsis.p4}</p>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Personajes ---------- */
function Characters({ t }) {
  return (
    <section className="characters" id="characters" data-screen-label="03 Personajes">
      <div className="wrap">
        <div className="characters-header reveal">
          <div>
            <div className="eyebrow">{t.characters.eyebrow}</div>
            <h2 className="section-title" style={{marginTop: 14}} dangerouslySetInnerHTML={{__html: t.characters.title}} />
          </div>
          <p className="section-intro">{t.characters.intro}</p>
        </div>

        <div className="char-grid">
          <div className="char-card reveal">
            <div className="char-name">Emilia Espinosa</div>
            <div className="char-photo"><img src="assets/emilia.png" alt="Emilia" /></div>
            <div className="char-meta">
              <div>{t.characters.emilia.role}</div>
            </div>
            <p className="char-quote">{t.characters.emilia.quote}</p>
          </div>

          <div className="char-card offset reveal">
            <div className="char-name">Álvaro Alcázar</div>
            <div className="char-photo"><img src="assets/alvaro.png" alt="Álvaro" /></div>
            <div className="char-meta">
              <div>{t.characters.alvaro.role}</div>
            </div>
            <p className="char-quote">{t.characters.alvaro.quote}</p>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Mundo ---------- */
function World({ t }) {
  return (
    <section className="world" id="world" data-screen-label="04 Mundo">
      <div className="wrap">
        <div className="world-header reveal">
          <div className="eyebrow">{t.world.eyebrow}</div>
          <h2 className="section-title" dangerouslySetInnerHTML={{__html: t.world.title}} />
        </div>

        <div className="themes-grid reveal">
          {t.world.themes.map((th, i) => (
            <div className="theme" key={i}>
              <div className="theme-num">— {String(i+1).padStart(2,'0')}</div>
              <h3 className="theme-title">{th.title}</h3>
              <p className="theme-body">{th.body}</p>
            </div>
          ))}
        </div>

        <div className="keywords reveal" style={{marginTop: 70}}>
          {t.world.keywords.map((k, i) => <span className="keyword" key={i}>{k}</span>)}
        </div>
      </div>
    </section>
  );
}

/* ---------- Vídeo ---------- */
function Video({ t }) {
  const ref = useRef(null);
  const [playing, setPlaying] = useState(false);
  const onPlay = () => {
    if (!ref.current) return;
    ref.current.muted = false;
    ref.current.controls = true;
    ref.current.play();
    setPlaying(true);
  };
  return (
    <section className="video-section" id="video" data-screen-label="05 Video">
      <div className="wrap-narrow">
        <div className="eyebrow reveal">{t.video.eyebrow}</div>
        <h2 className="section-title reveal" style={{marginTop: 14}}>{t.video.title}</h2>
        <p className="section-intro reveal" style={{margin: '14px auto 0', textAlign: 'center', maxWidth: 540}}>{t.video.intro}</p>

        <div className="video-shell reveal">
          <video ref={ref} src="assets/presentacion.mp4" preload="metadata" playsInline poster="assets/portada-mockup.jpeg" />
          <div className={`video-play ${playing ? 'hidden' : ''}`} onClick={onPlay}>
            <div className="ring">
              <svg viewBox="0 0 24 24"><polygon points="6,4 20,12 6,20" /></svg>
            </div>
            <div className="label">{t.video.play}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Autora ---------- */
function Author({ t }) {
  return (
    <section className="author" id="author" data-screen-label="06 Autora">
      <div className="wrap">
        <div className="author-grid">
          <div className="author-photo-wrap reveal">
            <div className="author-photo author-photo-cutout">
              <div className="author-photo-stage">
                <div className="author-photo-halo" />
                <img src="assets/melissa-recortada.png" alt="Melissa Franco" />
              </div>
            </div>
            <div className="author-photo-frame" />
          </div>
          <div className="reveal">
            <div className="eyebrow author-eyebrow">{t.author.eyebrow}</div>
            <h2 className="author-name">{t.author.name}</h2>
            <div className="author-place script">{t.author.place}</div>
            <div className="author-bio">
              <p>{t.author.bio_p1}</p>
              <p>{t.author.bio_p2}</p>
              <p>{t.author.bio_p3}</p>
            </div>
            <div className="author-prev">
              <h4>{t.author.prev_label}</h4>
              <ul>
                {t.author.prev.map((b,i) => <li key={i}><em>{b.title}</em> {b.meta}</li>)}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Compra ---------- */
function Buy({ t }) {
  return (
    <section className="buy" id="buy" data-screen-label="07 Comprar">
      <div className="wrap-narrow">
        <div className="eyebrow reveal">{t.buy.eyebrow}</div>
        <h2 className="section-title reveal" style={{marginTop: 14}} dangerouslySetInnerHTML={{__html: t.buy.title}} />
        <p className="section-intro reveal" style={{margin: '14px auto 0', textAlign: 'center', maxWidth: 540}}>{t.buy.intro}</p>

        <div className="buy-cover reveal">
          <img src="assets/portada-libro.jpeg" alt="Portada — Tierra de vino y sal" />
        </div>

        <div className="stores reveal">
          {t.buy.stores.map((s,i) => (
            <a key={i} className="store" href={s.href} target="_blank" rel="noopener">
              <div>
                <div className="store-name">{s.name}</div>
                <div className="store-meta">{s.meta}</div>
              </div>
              <div className="store-arrow">→</div>
            </a>
          ))}
        </div>

        <div className="reveal" style={{marginTop: 60}}>
          <div className="eyebrow" style={{textAlign:'center', marginBottom: 18}}>{t.buy.facts_label}</div>
          <div className="fact-sheet">
            {t.buy.facts.map((f,i) => (
              <div className="fact" key={i}>
                <div className="fact-label">{f.label}</div>
                <div className="fact-value">{f.value}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Newsletter ---------- */
function Newsletter({ t }) {
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState('');
  const submit = (e) => {
    e.preventDefault();
    if (!/^[^@]+@[^@]+\.[^@]+$/.test(email)) {
      setStatus('invalid');
      return;
    }
    setStatus('thanks');
    setEmail('');
  };
  return (
    <section className="newsletter" id="newsletter" data-screen-label="08 Newsletter">
      <div className="wrap-narrow">
        <div className="eyebrow reveal">{t.newsletter.eyebrow}</div>
        <h2 className="reveal">{t.newsletter.title}</h2>
        <p className="reveal">{t.newsletter.intro}</p>
        <form className="nl-form reveal" onSubmit={submit}>
          <input type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder={t.newsletter.placeholder} required />
          <button type="submit">{t.newsletter.submit}</button>
        </form>
        <div className="nl-status">
          {status === 'thanks' && t.newsletter.thanks}
          {status === 'invalid' && t.newsletter.invalid}
        </div>
      </div>
    </section>
  );
}

/* ---------- Footer ---------- */
function Footer({ t }) {
  const socials = [
    { name: 'Instagram', href: 'https://instagram.com/melissafrancoescritora', handle: '@melissafrancoescritora',
      icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor"/></svg> },
    { name: 'YouTube', href: 'https://youtube.com/@melissafrancoescritora', handle: '@melissafrancoescritora',
      icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="2" y="5" width="20" height="14" rx="3"/><polygon points="10,9 16,12 10,15" fill="currentColor" stroke="none"/></svg> },
    { name: 'Facebook', href: 'https://www.facebook.com/melissa.francotorrecilla', handle: 'Melissa Franco Torrecilla',
      icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M14 8h2V5h-2c-1.7 0-3 1.3-3 3v2H9v3h2v8h3v-8h2.5l.5-3H14V8z" fill="currentColor" stroke="none"/></svg> },
  ];
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <div className="footer-logo">Melissa Franco</div>
            <p className="footer-tag">{t.footer.tag}</p>
            <a className="footer-mail" href={`mailto:${t.footer.contact_email}`}>
              <span className="footer-mail-label">{t.footer.contact_label}</span>
              <span className="footer-mail-value">{t.footer.contact_email}</span>
            </a>
          </div>
          <div>
            <h4>{t.footer.follow}</h4>
            <div className="social-buttons">
              {socials.map((s, i) => (
                <a key={i} className="social-btn" href={s.href} target="_blank" rel="noopener" aria-label={s.name}>
                  <span className="social-btn-icon">{s.icon}</span>
                  <span className="social-btn-text">
                    <strong>{s.name}</strong>
                    <em>{s.handle}</em>
                  </span>
                </a>
              ))}
            </div>
          </div>
          <div>
            <h4>{t.footer.publisher_links}</h4>
            <a className="publisher-card" href="https://www.ed-versatil.com/" target="_blank" rel="noopener">
              <div>
                <strong>{t.footer.publisher_store}</strong>
                <span>ed-versatil.com</span>
              </div>
              <span className="store-arrow">→</span>
            </a>
          </div>
        </div>
        <div className="footer-bottom">
          <span>{t.footer.copyright}</span>
          <span>{t.footer.publisher}</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Hero, Synopsis, Characters, World, Video, Author, Buy, Newsletter, Footer, useReveal });
