// Home page sections
function useReveal() {
  React.useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.1 });
    document.querySelectorAll('.reveal').forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

function SocialLinks({ size = 16 }) {
  return (
    <>
      <a className="social-btn" href="#" aria-label="X / Twitter"><Icon name="x-twitter" size={size} /></a>
      <a className="social-btn" href="#" aria-label="Instagram"><Icon name="instagram" size={size} /></a>
      <a className="social-btn" href="#" aria-label="GitHub"><Icon name="github" size={size} /></a>
    </>
  );
}

function Hero({ lang, onNav }) {
  const c = window.COPY;
  return (
    <section className="hero container" id="home">
      <div className="hero-logo-bg">
        <div className="hero-logo-glow"></div>
        <img src="assets/logo-large.png" alt="" />
      </div>
      <div className="hero-meta">
        <span className="hero-dot"></span>
        <span className="mono">{c.hero.tag[lang]}</span>
        <span className="mono" style={{ color: 'var(--fg-dim)' }}>[ 01 / HOME ]</span>
      </div>
      <h1>
        Alanityc<br />
        <span className="hollow">Projects</span><span className="accent">.</span>
      </h1>
      <p className="hero-sub">{c.hero.sub[lang]}</p>
      <div className="hero-actions">
        <a className="btn btn-primary" onClick={() => onNav('work')}>
          {c.hero.primary[lang]} <Icon name="arrow-r" size={14} />
        </a>
        <a className="btn btn-ghost" onClick={() => onNav('indev')}>
          {c.hero.ghost[lang]}
        </a>
      </div>

      <div className="hero-bottom">
        <div className="hero-stats">
          <div className="hero-stat"><div className="n">02</div><div className="l">{lang === 'es' ? 'Publicados' : 'Released'}</div></div>
          <div className="hero-stat"><div className="n">03</div><div className="l">{lang === 'es' ? 'Plataformas' : 'Platforms'}</div></div>
          <div className="hero-stat"><div className="n">02</div><div className="l">{lang === 'es' ? 'En el horno' : 'Cooking'}</div></div>
        </div>
        <div className="hero-socials"><SocialLinks /></div>
        <div className="scroll-hint"><span className="mono">{c.hero.scroll[lang]}</span><span className="bar"></span></div>
      </div>
    </section>
  );
}

function KeyArt({ project, variant = 0 }) {
  const ref = React.useRef();
  React.useEffect(() => {
    const draw = () => window.drawKeyArt(ref.current, project, variant);
    draw();
    const ro = new ResizeObserver(draw);
    if (ref.current) ro.observe(ref.current);
    return () => ro.disconnect();
  }, [project.id, variant]);
  return <canvas ref={ref} />;
}

function ProjectCard({ project, lang, onOpen, size = 'default' }) {
  const cardRef = React.useRef();
  const handleMove = (e) => {
    const r = cardRef.current.getBoundingClientRect();
    cardRef.current.style.setProperty('--mx', ((e.clientX - r.left) / r.width * 100) + '%');
    cardRef.current.style.setProperty('--my', ((e.clientY - r.top) / r.height * 100) + '%');
  };
  const cls = 'project-card reveal' + (size === 'wide' ? ' wide' : size === 'third' ? ' third' : '');
  return (
    <article className={cls} ref={cardRef} onMouseMove={handleMove} onClick={() => onOpen(project.id)}>
      <div className="card-tag live">{project.kind === 'game' ? (lang === 'es' ? 'Videojuego' : 'Game') : (lang === 'es' ? 'App' : 'App')}</div>
      <div className="card-key-art">
        <KeyArt project={project} />
        <div className="card-shine"></div>
      </div>
      <div className="card-body">
        <div>
          <div className="card-title">{project.title}</div>
          <div className="card-desc">{project.tagline[lang]}</div>
          <div className="card-meta">
            <div className="platforms">
              {project.platforms.map(p => <div className="plat" key={p} title={p}><Icon name={p} size={12} /></div>)}
            </div>
            <span className="mono-sm" style={{ color: 'var(--fg-dim)' }}>· {project.year}</span>
          </div>
        </div>
        <div className="card-go"><Icon name="arrow-tr" size={18} stroke={2} /></div>
      </div>
    </article>
  );
}

function WorkSection({ lang, onOpen }) {
  const [filter, setFilter] = React.useState('all');
  const c = window.COPY;
  const projects = window.PROJECTS;
  const shown = projects.filter(p => filter === 'all' ? true : (filter === 'apps' ? p.kind === 'app' : p.kind === 'game'));

  // Size variation for visual rhythm
  const sizes = ['default', 'default', 'wide', 'default', 'default', 'default', 'wide'];

  return (
    <section className="section" id="work">
      <div className="container">
        <div className="section-head reveal">
          <div>
            <div className="section-label mono"><span className="idx">[ 02 ]</span> <span>{c.sections.work.label[lang]}</span></div>
            <h2 style={{ marginTop: 18 }}>
              {c.sections.work.head1[lang]} <span className="hollow" style={{ WebkitTextStroke: '1.5px var(--fg)', color: 'transparent', fontStyle: 'italic', fontWeight: 400 }}>{c.sections.work.head2[lang]}</span><span className="accent">.</span>
            </h2>
          </div>
          <div className="tabs">
            {['all', 'apps', 'games'].map(k => (
              <button key={k} className={'tab' + (filter === k ? ' active' : '')} onClick={() => setFilter(k)}>
                {c.tabs[k][lang]}
              </button>
            ))}
          </div>
        </div>

        <div className="projects-grid">
          {shown.map((p, i) => <ProjectCard key={p.id} project={p} lang={lang} onOpen={onOpen} size={sizes[i % sizes.length]} />)}
        </div>
      </div>
    </section>
  );
}

function InDevSection({ lang }) {
  const c = window.COPY;
  return (
    <section className="section" id="indev" style={{ paddingTop: 0 }}>
      <div className="container">
        <div className="section-head reveal">
          <div>
            <div className="section-label mono"><span className="idx">[ 03 ]</span> <span>{c.sections.indev.label[lang]}</span></div>
            <h2 style={{ marginTop: 18 }}>
              {c.sections.indev.head1[lang]} <span className="hollow" style={{ WebkitTextStroke: '1.5px var(--fg)', color: 'transparent', fontStyle: 'italic', fontWeight: 400 }}>{c.sections.indev.head2[lang]}</span><span className="accent">.</span>
            </h2>
          </div>
          <div className="mono" style={{ maxWidth: 320, textTransform: 'none', fontSize: 13, letterSpacing: '0.02em', color: 'var(--fg-muted)' }}>
            {lang === 'es' ? 'Teasers de lo que llegará. Menos detalle, más misterio.' : 'Teasers of what\'s coming. Less detail, more mystery.'}
          </div>
        </div>

        <div className="indev-grid">
          {window.IN_DEV.map((p) => (
            <div key={p.id} className="indev-card reveal">
              <div className="indev-head">
                <span className="mono-sm" style={{ color: 'var(--fg-dim)' }}>{p.eta}</span>
                <span className="indev-stage">{lang === 'es' ? 'Próximamente' : 'Coming soon'}</span>
              </div>
              <div className="indev-title">{p.title}</div>
              <div className="indev-kind">{p.kind}</div>
              <div className="indev-desc">{p.desc[lang]}</div>
              <div className="indev-progress">
                <div className="track"><div className="fill" style={{ width: p.progress + '%' }}></div></div>
                <div className="label">
                  <span>{p.stage[lang]}</span>
                  <span>{p.progress}%</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function DevlogSection({ lang }) {
  const c = window.COPY;
  return (
    <section className="section" id="devlog" style={{ paddingTop: 0 }}>
      <div className="container">
        <div className="section-head reveal">
          <div>
            <div className="section-label mono"><span className="idx">[ 04 ]</span> <span>{c.sections.devlog.label[lang]}</span></div>
            <h2 style={{ marginTop: 18 }}>
              {c.sections.devlog.head1[lang]} <span className="hollow" style={{ WebkitTextStroke: '1.5px var(--fg)', color: 'transparent', fontStyle: 'italic', fontWeight: 400 }}>{c.sections.devlog.head2[lang]}</span><span className="accent">.</span>
            </h2>
          </div>
          <a className="btn btn-ghost" href="#">{lang === 'es' ? 'Todas las entradas' : 'All posts'} <Icon name="arrow-r" size={14} /></a>
        </div>

        <div className="devlog-list">
          {window.DEVLOG.map((d, i) => (
            <div key={i} className="devlog-item reveal">
              <div className="devlog-num">#{String(window.DEVLOG.length - i).padStart(3, '0')}</div>
              <div>
                <div className="devlog-title">{d.title[lang]}</div>
                <div className="devlog-excerpt">{d.excerpt[lang]}</div>
              </div>
              <div className="devlog-meta">{d.date}<br /><span style={{ color: 'var(--accent)' }}>{d.tag}</span></div>
              <div className="devlog-arrow"><Icon name="arrow-r" size={18} /></div>
            </div>
          ))}
        </div>

        <div className="ai-note"><span className="dot"></span> {c.aiNote[lang]}</div>
      </div>
    </section>
  );
}

function ContactSection({ lang }) {
  const c = window.COPY;
  const [form, setForm] = React.useState({ name: '', email: '', message: '' });
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);

  const submit = (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = lang === 'es' ? 'Requerido' : 'Required';
    if (!/\S+@\S+\.\S+/.test(form.email)) errs.email = lang === 'es' ? 'Email inválido' : 'Invalid email';
    if (form.message.trim().length < 10) errs.message = lang === 'es' ? 'Mín. 10 caracteres' : 'Min. 10 chars';
    setErrors(errs);
    if (Object.keys(errs).length === 0) {
      setSent(true);
      setTimeout(() => { setSent(false); setForm({ name: '', email: '', message: '' }); }, 4000);
    }
  };

  return (
    <section className="section" id="contact" style={{ paddingTop: 0 }}>
      <div className="container">
        <div className="section-head reveal" style={{ marginBottom: 60 }}>
          <div className="section-label mono"><span className="idx">[ 05 ]</span> <span>{c.sections.contact.label[lang]}</span></div>
        </div>

        <div className="contact-grid">
          <div className="reveal">
            <div className="contact-display">
              {c.contactTitle.l1[lang]} <span className="hollow">{c.contactTitle.l2[lang]}</span><br />
              <span className="accent">{c.contactTitle.l3[lang]}</span>
            </div>
            <p style={{ color: 'var(--fg-muted)', marginTop: 24, maxWidth: '42ch', fontSize: 17 }}>{c.contactSub[lang]}</p>
            <div style={{ marginTop: 32 }}>
              <div className="mono" style={{ marginBottom: 12 }}>{lang === 'es' ? 'O escríbenos' : 'Or write us'}</div>
              <a href="mailto:hello@alanityc.dev" style={{ fontSize: 22, letterSpacing: '-0.02em', display: 'inline-flex', alignItems: 'center', gap: 10, borderBottom: '1px solid var(--line-2)', paddingBottom: 4 }}>hello@alanityc.dev <Icon name="arrow-tr" size={16} /></a>
            </div>
          </div>

          <div className="reveal">
            {sent ? (
              <div className="form-success">
                <Icon name="check" size={14} /> &nbsp; {lang === 'es' ? 'MENSAJE RECIBIDO. TE RESPONDEMOS PRONTO.' : 'MESSAGE RECEIVED. WE\'LL GET BACK SOON.'}
              </div>
            ) : (
              <form onSubmit={submit} noValidate>
                <div className="form-field">
                  <label>{lang === 'es' ? 'Nombre' : 'Name'}</label>
                  <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} className={errors.name ? 'err' : ''} />
                  {errors.name && <span className="form-err">{errors.name}</span>}
                </div>
                <div className="form-field">
                  <label>Email</label>
                  <input type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} className={errors.email ? 'err' : ''} />
                  {errors.email && <span className="form-err">{errors.email}</span>}
                </div>
                <div className="form-field">
                  <label>{lang === 'es' ? 'Mensaje' : 'Message'}</label>
                  <textarea value={form.message} onChange={e => setForm({ ...form, message: e.target.value })} className={errors.message ? 'err' : ''} />
                  {errors.message && <span className="form-err">{errors.message}</span>}
                </div>
                <button type="submit" className="btn btn-primary" style={{ width: '100%', justifyContent: 'center' }}>
                  {lang === 'es' ? 'Enviar mensaje' : 'Send message'} <Icon name="arrow-r" size={14} />
                </button>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function Marquee({ lang }) {
  const items = [
    { es: 'Apps de utilidad', en: 'Utility apps' },
    { es: 'Videojuegos indie', en: 'Indie games' },
    { es: 'iOS · Android', en: 'iOS · Android' },
    { es: 'Windows · Mac', en: 'Windows · Mac' },
    { es: 'Hecho en Madrid', en: 'Made in Madrid' },
    { es: 'Enviado al mundo', en: 'Shipped worldwide' }
  ];
  const list = [...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee-inner">
        {list.map((it, i) => (
          <span key={i} className="marquee-item">
            {it[lang]} <span className="dot">◆</span>
          </span>
        ))}
      </div>
    </div>
  );
}

function Footer({ lang, onNav }) {
  const c = window.COPY;
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-top">
          <div className="footer-word">
            Alanityc<br /><span className="hollow">Projects</span>
          </div>
          <div className="footer-col">
            <h4>{lang === 'es' ? 'Navegar' : 'Navigate'}</h4>
            <a onClick={() => onNav('work')}>{c.nav.work[lang]}</a>
            <a onClick={() => onNav('indev')}>{c.nav.indev[lang]}</a>
            <a onClick={() => onNav('devlog')}>{c.nav.devlog[lang]}</a>
            <a onClick={() => onNav('contact')}>{c.nav.contact[lang]}</a>
          </div>
          <div className="footer-col">
            <h4>{lang === 'es' ? 'Social' : 'Social'}</h4>
            <a href="#">X / Twitter</a>
            <a href="#">Instagram</a>
            <a href="#">GitHub</a>
            <a href="mailto:hello@alanityc.dev">hello@alanityc.dev</a>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Alanityc Projects</span>
          <span>{c.footerColophon[lang]}</span>
          <span>v.2026.04 ◆ All systems nominal</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Hero, WorkSection, InDevSection, DevlogSection, ContactSection, Marquee, Footer, KeyArt, ProjectCard, SocialLinks, useReveal });
