// Home — full-bleed hero + sticky stacked project cards + horizontal blog scroll
function Home({ lang, showCursorPreview = true }) {
  const es = lang === "es";

  const projects = [
  {
    num: "01", name: "Packaging",
    tag: es ? "Once años · Tridimage · Mendoza" : "Eleven years · Tridimage · Mendoza",
    route: "packaging",
    placeholder: "Packaging",
    c1: "#5b6a7a", c2: "#1c2530"
  },
  {
    num: "02", name: "Branding",
    tag: es ? "Identidad · Estrategia · Espacios" : "Identity · Strategy · Spaces",
    route: "branding",
    placeholder: "Branding",
    c1: "#7a3d2a", c2: "#2a140d"
  },
  {
    num: "03", name: "BAG",
    tag: es ? "Startup · Producto · Arte" : "Startup · Product · Art",
    route: "bag",
    placeholder: "Bag · Startup",
    c1: "#3a4a3e", c2: "#101a14"
  }];


  const posts = [
  { id: "mina-santa-cruz", date: "May 2026", future: false,
    title_es: "Cómo terminé haciendo workshops en una mina de oro en el medio de la Patagonia",
    title_en: "How I ended up running workshops in a gold mine in Patagonia",
    preview: "Mina · Santa Cruz" },
  { id: "tarjeta-debito", date: es ? "Próximo" : "Soon", future: true,
    title_es: "Una tarjeta de débito transparente", title_en: "A transparent debit card" },
  { id: "julio-le-parc", date: es ? "Próximo" : "Soon", future: true,
    title_es: "Julio Le Parc", title_en: "Julio Le Parc" },
  { id: "fancy-monas-deep", date: es ? "Próximo" : "Soon", future: true,
    title_es: "Fancy Monas backlights", title_en: "Fancy Monas backlights" }];


  // --- Intro de carga: revela el statement del hero l\u00ednea por l\u00ednea ---
  React.useLayoutEffect(() => {
    const root = document.documentElement;
    if (!root.classList.contains("intro-pending") || window.__introPlayed) return;
    const h1 = document.querySelector(".hero-statement");
    if (!h1) return;
    const text = h1.textContent;
    h1.textContent = "";
    const spans = [];
    text.split(/(\s+)/).forEach((tok) => {
      if (!tok) return;
      if (/^\s+$/.test(tok)) {
        h1.appendChild(document.createTextNode(tok));
      } else {
        const s = document.createElement("span");
        s.className = "hero-word";
        s.textContent = tok;
        h1.appendChild(s);
        spans.push(s);
      }
    });
    // Agrupar palabras por l\u00ednea visual (mismo offsetTop) y escalonar el delay.
    let lineTop = null, line = -1;
    spans.forEach((s) => {
      const top = s.offsetTop;
      if (lineTop === null || Math.abs(top - lineTop) > 2) { line++; lineTop = top; }
      s.style.animationDelay = (1.5 + line * 0.3) + "s";
    });
  }, []);

  React.useEffect(() => {
    const cards = document.querySelectorAll('.stack-card');

    const onScroll = () => {
      cards.forEach((card, i) => {
        const covered = Array.from(cards).filter((c, j) =>
        j < i && c.getBoundingClientRect().top <= 0
        ).length;
        const scale = 1 - covered * 0.047;
        const translateY = -47.5;
        card.style.transform =
        `translateY(${translateY}px) scale(${scale})`;
      });
    };

    onScroll();
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => entries.forEach((e) => {
        const letters = e.target.querySelectorAll('.letter');
        if (e.isIntersecting) {
          e.target._trTimers = [];
          letters.forEach((l, i) => {
            e.target._trTimers.push(setTimeout(() => l.classList.add('visible'), i * 30));
          });
        } else {
          (e.target._trTimers || []).forEach(clearTimeout);
          e.target._trTimers = [];
          letters.forEach((l) => l.classList.remove('visible'));
        }
      }),
      { threshold: 0, rootMargin: "-35% 0px -35% 0px" }
    );
    const els = document.querySelectorAll('[data-section] .text-reveal');
    console.log('[text-reveal] observer encontró', els.length, 'elementos .text-reveal');
    els.forEach((el) => observer.observe(el));
    return () => observer.disconnect();
  }, []);

  const blogScrollRef = React.useRef(null);
  const scrollBlog = (dir) => {
    const el = blogScrollRef.current;
    if (!el) return;
    const card = el.querySelector(".blog-card");
    const step = card ? card.getBoundingClientRect().width + 24 : 400;
    el.scrollBy({ left: dir * step, behavior: "smooth" });
  };

  return (
    <div className="page" data-screen-label="01 Home">
      {/* HERO — full-bleed colored placeholder, statement at bottom-left */}
      <section className="hero">
        <div className="hero-bg has-photo" aria-hidden="true">
          <img className="hero-photo" src="assets/HERO.webp" alt="" />
        </div>
        <div className="hero-content">
          <h1 className="hero-statement">
            {es ?
            "Me piden un plato, diseño un restaurante. Me piden un logo, armo una startup. Soy diseñador gráfico." :
            "They ask me for a dish, I design a restaurant. They ask me for a logo, I build a startup. I'm a graphic designer."}
          </h1>
          <div className="hero-meta">
            <span className="city">{es ? "Buenos Aires, AR" : "Buenos Aires, AR"}</span>
            <span style={{ color: "rgb(255, 138, 0)" }}>{es ? "Disponible · 2026" : "Available · 2026"}</span>
            <span>↓ {es ? "Scroll" : "Scroll"}</span>
          </div>
        </div>
      </section>

      {/* STACK — 3 project cards with sticky scroll */}
      <section className="section-pad" data-section="work">
        <div className="container">
        <div className="section-head-row" style={{ fontWeight: "200" }}>
          <div>
            <div className="label" style={{ marginBottom: 16 }}>{es ? "(03) Áreas de trabajo" : "(03) Areas of work"}</div>
            <h2 className="h-xl" style={{ maxWidth: "18ch", fontWeight: "600" }}>
              <TextReveal text={es ? "Tres caminos, un mismo oficio." : "Three paths, one craft."} />
            </h2>
          </div>
          <p className="lede lede-col" style={{ padding: "0px", margin: "16px 0px 17px", fontWeight: "600", color: "rgb(255, 255, 255)", fontSize: "clamp(18px, 4.6vw, 30px)", maxWidth: "700px" }}>
            <TextReveal text={es ?
              "+15 años entre el packaging, el branding y el producto digital. En cada proyecto, el encargo fue el punto de partida. Nunca el límite." :
              "+15 years across packaging, branding and digital product. In every project, the brief was the starting point. Never the limit."} />
          </p>
        </div>

        <div className="stack">
          {projects.map((p, i) => {
              return (
                <Link
                  key={p.num}
                  to={p.route}
                  className="stack-card"
                  style={{
                    zIndex: i + 1,
                    "--card-c1": p.c1,
                    "--card-c2": p.c2
                  }}>
                
                <div className="card-bg"></div>
                <image-slot
                    id={`CARD-${p.route}`}
                    shape="rect"
                    placeholder={p.placeholder}>
                </image-slot>
                <span className="card-tag">{p.placeholder}</span>
                <div className="card-foot">
                  <span className="num">{p.num}</span>
                  <span className="rule"></span>
                  <span className="name">{p.name}</span>
                </div>
              </Link>);

            })}
        </div>
        </div>
      </section>

      {/* PITCH — independiente, búsqueda de proyectos */}
      <section style={{ padding: "32px 0 48px" }} data-section="pitch">
        <div className="container">
          <p style={{ fontSize: "clamp(18px, 4.6vw, 30px)", fontWeight: "600", color: "rgb(255,255,255)", maxWidth: "700px", margin: 0, lineHeight: 1.35 }}>
            <TextReveal text={es ?
              "Hoy trabajo de forma independiente y busco proyectos donde el diseño sea una herramienta de pensamiento, no solo de ejecución. Si tenés un problema que todavía no sabés bien cómo resolver, probablemente sea un buen punto de partida para hablar." :
              "Today I work independently and look for projects where design is a thinking tool, not just an execution one. If you have a problem you don't quite know how to solve yet, that's probably a good starting point for a conversation."} />
          </p>

          <div className="pitch-footer">
            <div className="pitch-areas">
              <div className="label" style={{ marginBottom: 12 }}>{es ? "Servicios" : "Services"}</div>
              <ul>
                <li>{es ? "Estrategia y proceso" : "Strategy and process"}</li>
                <li>Branding</li>
                <li>Packaging</li>
                <li>{es ? "Diseño de producto" : "Product design"}</li>
              </ul>
              <Link to="about" className="pitch-about-link">
                {es ? "más sobre mí →" : "more about me →"}
              </Link>
            </div>
          </div>
        </div>
      </section>

      {/* BLOG — horizontal scroll cards */}
      <section className="section-pad" data-section="blog" style={{ paddingTop: "40px" }}>
        <div className="container">
          <div className="section-head-row">
            <div>
              <div className="label" style={{ marginBottom: 16 }}>{es ? "(01) Publicado" : "(01) Published"}</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 16 }}>
                <h2 className="h-xl">
                  <TextReveal text="Blog" />
                </h2>
                <span className="count mono" style={{ fontSize: "clamp(20px, 3vw, 48px)" }}>({posts.length})</span>
              </div>
              <p className="lede" style={{ marginTop: 16 }}>
                <TextReveal text={es ?
                "Notas que escribo cuando termino un proyecto. Procesos, errores y lo que me llevo de cada cliente." :
                "Notes I write when I finish a project. Processes, mistakes, and what I take away from each client."} />
              </p>
            </div>
          </div>
        </div>

        <div className="blog-scroll-wrap">
          <div className="blog-scroll" ref={blogScrollRef}>
            {posts.map((p) => {
              const title = es ? p.title_es : p.title_en;
              const body =
              <>
                  <div className="img">
                    <image-slot
                    id={`BLOG-${p.id}`}
                    shape="rect"
                    placeholder={p.preview || (es ? p.title_es : p.title_en)}>
                  </image-slot>
                    <span className="img-tag">IMG-{p.id.slice(0, 4).toUpperCase()}</span>
                    {!p.future && <span className="read-pill">Read</span>}
                  </div>
                  <div className="date">{p.date}</div>
                  <div className="title">{title}</div>
                </>;

              if (p.future) {
                return <div key={p.id} className="blog-card future" aria-disabled="true">{body}</div>;
              }
              return (
                <Link key={p.id} to="blog" sub={p.id} className="blog-card" data-cursor-preview={p.preview || title}>
                  {body}
                </Link>);

            })}
          </div>
          <div className="container">
            <div className="blog-scroll-tips">
              <span>← {es ? "Arrastrá para ver más" : "Drag to see more"} →</span>
              <div>
                <button onClick={() => scrollBlog(-1)} aria-label="prev">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M15 18l-6-6 6-6" /></svg>
                </button>
                <button onClick={() => scrollBlog(1)} aria-label="next">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M9 18l6-6-6-6" /></svg>
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>);

}

window.Home = Home;