// Packaging case page

// Inline carousel — mirrors the one used in Branding (kept local to this
// file because each Babel script gets its own scope and the original isn't
// exported to window).
function PkgCarousel({ slides }) {
  const [i, setI] = React.useState(0);
  const n = slides.length;
  const carouselRef = React.useRef(null);
  const go = (d) => {
    setI((p) => (p + d + n) % n);
    const el = carouselRef.current;
    if (el && getComputedStyle(el).overflowX === 'auto') {
      const slideW = el.querySelector('.mat-slide')?.offsetWidth || 0;
      el.scrollBy({ left: d * slideW, behavior: 'smooth' });
    }
  };
  const startX = React.useRef(null);
  const onDown = (e) => {startX.current = e.clientX;};
  const onUp = (e) => {
    if (startX.current == null) return;
    const dx = e.clientX - startX.current;
    startX.current = null;
    if (Math.abs(dx) > 50) go(dx < 0 ? 1 : -1);
  };
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === "ArrowLeft") go(-1);
      if (e.key === "ArrowRight") go(1);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [n]);
  return (
    <div className="mat-carousel" ref={carouselRef}>
      <div
        className="mat-track"
        onPointerDown={onDown}
        onPointerUp={onUp}
        style={{ transform: `translateX(-${i * 100}%)` }}>
        {slides.map((s) =>
        <div key={s.id} className="mat-slide">
            <Placeholder tag={s.tag} id={s.id} className="ph-mat" />
          </div>
        )}
      </div>
      <button className="mat-nav prev" onClick={() => go(-1)} aria-label="Anterior">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          <path d="M15 18l-6-6 6-6" />
        </svg>
      </button>
      <button className="mat-nav next" onClick={() => go(1)} aria-label="Siguiente">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          <path d="M9 18l6-6-6-6" />
        </svg>
      </button>
      <div className="mat-dots">
        {slides.map((_, j) =>
        <button
          key={j}
          className={`dot${j === i ? " active" : ""}`}
          onClick={() => setI(j)}
          aria-label={`Slide ${j + 1}`} />
        )}
      </div>
      <div className="mat-counter">
        <span className="mono">{String(i + 1).padStart(2, "0")}</span>
        <span className="mono dim"> / {String(n).padStart(2, "0")}</span>
      </div>
    </div>);

}

function Packaging({ lang }) {
  const es = lang === "es";
  return (
    <div className="page" data-screen-label="Packaging">
      <div className="container">
        <Link to="home" className="back-link">← {es ? "Volver" : "Back"}</Link>

        <header className="case-header">
          <div className="label" style={{ marginBottom: 24 }}>{es ? "Packaging · Oficio · Tridimage" : "Packaging · Craft · Tridimage"}</div>
          <h1 className="h-xl" style={{ maxWidth: "16ch" }}>
            {es ? "El packaging me enseñó el oficio" : "Packaging taught me the craft"}
          </h1>
          <p className="lede muted" style={{ marginTop: 32 }}>
            {es ?
            "Diseñar packaging es diseñar en el mundo real: con restricciones técnicas, objetivos de negocio y la certeza de que el resultado va a existir fuera de una pantalla. Eso me formó como diseñador más que cualquier otra disciplina." :
            "Designing packaging means designing in the real world: with technical constraints, business goals, and the certainty that the result will exist outside a screen. That shaped me more than any other discipline."}
          </p>
          <div className="case-meta-row">
            <div className="item"><span className="k">{es ? "Estudio" : "Studio"}</span><span className="v">Tridimage</span></div>
            <div className="item"><span className="k">{es ? "Duración" : "Duration"}</span><span className="v">{es ? "11 años" : "11 years"}</span></div>
            <div className="item"><span className="k">{es ? "Modalidad" : "Mode"}</span><span className="v">{es ? "In-house · Remoto" : "In-house · Remote"}</span></div>
            <div className="item"><span className="k">{es ? "Ubicación" : "Location"}</span><span className="v">Argentina</span></div>
          </div>
        </header>

        <Placeholder tag={es ? "Estantería · Bodega" : "Shelf · Winery"} id="PKG-HERO" className="ph-hero" />

        <Reveal className="prose-section">
          <h3>{es ? "Intro / Tridimage" : "Intro / Tridimage"}</h3>
          <div className="body-text">
            <h4>{es ? "Once años de oficio" : "Eleven years of craft"}</h4>
            <p>{es ?
              "Aprendí el oficio haciendo, corrigiéndome, defendiendo decisiones y entendiéndome con clientes, proveedores y equipos. Tridimage fue para mí esa escuela. Once años trabajando en uno de los estudios de packaging y branding más reconocidos de Argentina y la región, donde cada proyecto era una oportunidad de profundizar el criterio y afinar la mirada." :
              "I learned the craft by doing, correcting myself, defending decisions and working things out with clients, suppliers and teams. Tridimage was that school for me. Eleven years at one of the most recognized packaging and branding studios in Argentina and the region, where every project was an opportunity to deepen judgment and sharpen the eye."}</p>
            <p>{es ?
              "Ahí adquirí mis primeras herramientas como diseñador y con el tiempo fui dirigiendo proyectos propios para clientes de escalas muy distintas: desde pequeños emprendedores que lanzaban su primer producto hasta grandes corporaciones de consumo masivo, en Argentina, Latinoamérica y Europa. Esa variedad fue una formación en sí misma: aprender a leer contextos distintos, a adaptar el proceso y a entender que no hay una sola forma de resolver un problema de diseño." :
              "That's where I picked up my first tools as a designer, and over time I started leading my own projects for clients of very different scales: from small entrepreneurs launching their first product to large mass-consumption corporations, across Argentina, Latin America and Europe. That variety was a training in itself: learning to read different contexts, adapting the process, and understanding that there's no single way to solve a design problem."}</p>
          </div>
        </Reveal>

        <Reveal className="prose-section">
          <h3>{es ? "Mirada integral" : "Whole-system view"}</h3>
          <div className="body-text">
            <h4>{es ? "Forma y gráfica como un sistema" : "Form and graphics as one system"}</h4>
            <p>{es ?
              "Tridimage tenía un área de diseño industrial con profesionales muy sólidos. Trabajar junto a ellos en simultáneo fue lo que me permitió desarrollar una mirada integral del diseño: entender que la forma y lo gráfico no son capas separadas sino dos niveles de comunicación que tienen que funcionar juntos para contar una historia de marca coherente." :
              "Tridimage had an industrial design area with very solid professionals. Working alongside them in parallel is what let me develop a whole-system view of design: understanding that form and graphics are not separate layers but two levels of communication that have to work together to tell a coherent brand story."}</p>
            <p>{es ?
              "Un envase tiene estructura, volumen, peso, textura. Esas decisiones comunican antes de que el consumidor lea una sola palabra. Lo gráfico después refuerza, contrasta o amplifica lo que la forma ya dijo. Aprender a operar en esos dos niveles al mismo tiempo, y a que se potencien entre sí, cambió profundamente cómo enfrento cualquier proyecto de identidad visual, independientemente del soporte." :
              "A container has structure, volume, weight, texture. Those decisions communicate before the consumer reads a single word. The graphics then reinforce, contrast or amplify what the form already said. Learning to operate on both levels at once, and to make them strengthen each other, deeply changed how I approach any visual identity project, regardless of the medium."}</p>
          </div>
        </Reveal>

        <Reveal className="prose-section">
          <h3>{es ? "Mundo real" : "Real world"}</h3>
          <div className="body-text">
            <h4>{es ? "Diseño que vive en el mundo físico" : "Design that lives in the physical world"}</h4>
            <p>{es ?
              "El packaging existe en el mundo físico. Eso no es un detalle menor: significa que cada decisión de diseño tiene que contemplar desde el principio las condiciones reales en las que ese objeto va a existir. No solo la estética sino la viabilidad técnica, el costo de producción, la logística, la experiencia de quien lo usa y quien lo fabrica." :
              "Packaging exists in the physical world. That is not a minor detail: it means every design decision has to contemplate, from the start, the real conditions in which that object will exist. Not only aesthetics but technical viability, production cost, logistics, the experience of whoever uses it and whoever manufactures it."}</p>
            <p>{es ?
              "Muchos de los proyectos en los que trabajé no tenían como objetivo principal ser más atractivos para el consumidor. El foco estaba en optimizar materiales, reducir desperdicios, simplificar procesos de armado o mejorar la experiencia de carga y distribución. Eso me enseñó que el diseño es una herramienta con múltiples objetivos posibles, y que entender cuál es el objetivo real de cada proyecto es tan importante como saber diseñar." :
              "Many of the projects I worked on didn't have being more attractive to the consumer as their main goal. The focus was on optimizing materials, reducing waste, simplifying assembly processes or improving the loading and distribution experience. That taught me design is a tool with multiple possible objectives, and that understanding the real objective of each project is as important as knowing how to design."}</p>
          </div>
        </Reveal>

        <Reveal className="prose-section">
          <h3>{es ? "Estrategia" : "Strategy"}</h3>
          <div className="body-text">
            <h4>{es ? "Diagnóstico antes del diseño" : "Diagnosis before design"}</h4>
            <p>{es ?
              "Con el tiempo el estudio incorporó estrategia como servicio y fui parte de ese equipo. Hacíamos auditorías de diseño de marca y de producto: analizar el portfolio visual del cliente, detectar problemas de coherencia, posicionamiento o comunicación, y definir qué cambiar antes de empezar a diseñar." :
              "Over time the studio added strategy as a service and I was part of that team. We did brand and product design audits: analyzing the client's visual portfolio, detecting coherence, positioning or communication problems, and defining what to change before starting to design."}</p>
            <p>{es ?
              "Eso derivó en workshops con los equipos de los clientes en Argentina, Perú y México. El objetivo era integrar al cliente al proceso de diseño desde el diagnóstico, no solo desde la aprobación. Una metodología que después repliqué en proyectos muy distintos: una mina en la Patagonia, un restaurante en Buenos Aires, una startup de tecnología." :
              "That led to workshops with client teams in Argentina, Peru and Mexico. The goal was to bring the client into the design process from the diagnosis, not only from the approval. A methodology I later replicated in very different projects: a mine in Patagonia, a restaurant in Buenos Aires, a tech startup."}</p>
            <p>{es ?
              "El packaging me enseñó que el diseño más efectivo no parte de una idea brillante sino de un problema bien entendido. Eso cambió el orden en que enfrento cualquier proyecto." :
              "Packaging taught me the most effective design doesn't start from a brilliant idea but from a problem that is well understood. That changed the order in which I approach any project."}</p>
          </div>
        </Reveal>

        <Reveal as="div" className="case-fullblock" style={{ paddingTop: 32 }}>
          <PkgCarousel
            slides={[
            { id: "PKG-CAR-01", tag: es ? "Proyecto · 01" : "Project · 01" },
            { id: "PKG-CAR-02", tag: es ? "Proyecto · 02" : "Project · 02" },
            { id: "PKG-CAR-03", tag: es ? "Proyecto · 03" : "Project · 03" },
            { id: "PKG-CAR-04", tag: es ? "Proyecto · 04" : "Project · 04" },
            { id: "PKG-CAR-05", tag: es ? "Proyecto · 05" : "Project · 05" }]
            } />
        </Reveal>

        <Reveal className="prose-section">
          <h3>Mendoza</h3>
          <div className="body-text">
            <h4>{es ? "Otra forma de trabajar" : "Another way of working"}</h4>
            <p>{es ?
              "Luego, en mi etapa como freelancer, trabajé durante un tiempo para una agencia de Mendoza especializada en etiquetas de vino (YG Design). Una metodología completamente distinta: la agencia presentaba bocetos a lápiz muy esquemáticos, el cliente elegía un camino y mi trabajo era desarrollarlo en alta, resolver ilustraciones, tipografías, color y terminaciones, y armar un mockup realista para la presentación final." :
              "Later, in my freelance period, I worked for a while with a Mendoza agency specialized in wine labels. A completely different methodology: the agency presented very schematic pencil sketches, the client picked a direction and my job was to develop it in high finish, resolve illustrations, typography, color and finishings, and build a realistic mockup for the final presentation."}</p>
            <p>{es ?
              "Lo interesante de ese proceso era su especificidad técnica. Llevar un boceto a escala real en una botella implica resolver proporciones, ajustar jerarquías visuales y tomar decisiones que en el boceto original no estaban contempladas. Eso requería mucho criterio y autonomía. Y siempre me tomé la libertad de agregar opciones propias, a veces cercanas al boceto original, a veces más alejadas. Esa industria, la del vino, tiene además un nivel de exigencia estética y narrativa muy particular que disfruté mucho." :
              "What was interesting about that process was its technical specificity. Taking a sketch to real scale on a bottle means resolving proportions, adjusting visual hierarchies and making decisions that weren't contemplated in the original sketch. That required a lot of judgment and autonomy. And I always took the liberty of adding my own options, sometimes close to the original sketch, sometimes further away. The wine industry also has a particular level of aesthetic and narrative demand that I really enjoyed."}</p>
          </div>
        </Reveal>

        <section style={{ padding: "clamp(40px, 8vw, 72px) 0" }}>
          <h3 className="label" style={{ marginBottom: 24 }}>{es ? "Lo que se llevó adelante" : "Skills built along the way"}</h3>
          <div className="skills-grid">
            {[
            [es ? "Pensamiento 3D" : "3D thinking", "01"],
            [es ? "Criterio técnico" : "Technical eye", "02"],
            [es ? "Estrategia de marca" : "Brand strategy", "03"],
            ["Workshops", "04"],
            [es ? "Sistemas de diseño" : "Design systems", "05"],
            [es ? "Trabajo a escala" : "Working at scale", "06"]].
            map(([n, i]) =>
            <div key={i} className="cell">
                <span className="name">{n}</span>
                <span className="num">{i}</span>
              </div>
            )}
          </div>
        </section>

        <Reveal as="section" style={{ padding: "clamp(40px, 8vw, 72px) 0" }}>
          <h3 className="label" style={{ marginBottom: 32 }}>{es ? "Selección de proyectos" : "Selected projects"}</h3>
          <div className="grid-2">
            {[
            ["ENO", "ENO", "PKG-01", "YG Design", 2021],
            ["El Mistol", "El Mistol", "PKG-02", "Tridimage", 2009],
            ["Áltima", "Áltima", "PKG-03", "Tridimage", 2020],
            ["Luzón Dulce", "Luzón Dulce", "PKG-04", "YG Design", 2021],
            ["Pudú Helados", "Pudú Helados", "PKG-05", "YG Design", 2021],
            ["Organic Valley", "Organic Valley", "PKG-06", "Tridimage", 2019]].
            map(([es_, en_, id, studio, year], i) =>
            <div key={i} className="project">
                <Placeholder tag={es ? es_ : en_} id={id} className="ph-tall" />
                <div className="meta">
                  <div className="title">{es ? es_ : en_}</div>
                  <div className="sub">{studio} · {year}</div>
                </div>
              </div>
            )}
          </div>
        </Reveal>
      </div>

      <CTA lang={lang} />
    </div>);

}
window.Packaging = Packaging;