// About, Motion (YouTube), Services, Shop, Contact footer
const { useState: useStateS } = React;

function BioProse() {
  return (
    <div className="bio bio--prose mono">
      <p>
        Mapa López es creadora audiovisual especializada en la construcción de
        narrativas visuales y sonoras que combinan dirección, edición,
        fotografía y diseño sonoro. Su práctica integra lo técnico y lo creativo
        para dar forma a piezas donde la imagen, el cuerpo y el contexto
        dialogan de manera constante.
      </p>
      <p>
        Desarrolla proyectos colaborativos con un enfoque sensible y
        contemporáneo, explorando la estética, la memoria y las dinámicas
        sociales como ejes narrativos. Desde la dirección y la producción hasta
        el diseño visual, su trabajo busca crear piezas coherentes, expresivas y
        adaptables a distintos formatos y plataformas.
      </p>
    </div>
  );
}

function BioFragments() {
  return (
    <div className="bio bio--fragments mono">
      <p className="bio__frag">
        Creadora audiovisual. Dirección, edición, fotografía y diseño sonoro.
      </p>
      <p className="bio__frag">
        Narrativas visuales y sonoras donde la imagen, el cuerpo y el contexto
        dialogan.
      </p>
      <p className="bio__frag">
        Enfoque sensible, contemporáneo. Estética, memoria y dinámicas sociales
        como ejes.
      </p>
      <p className="bio__frag">
        Piezas coherentes, adaptables a distintos formatos y plataformas.
      </p>
    </div>
  );
}

function BioIndex() {
  return (
    <div className="bio bio--index mono">
      <div className="bio__item">
        <span className="bio__n muted">01 / PRÁCTICA</span>
        <p>
          Creadora audiovisual especializada en narrativas visuales y sonoras
          que combinan dirección, edición, fotografía y diseño sonoro. Integra
          lo técnico y lo creativo para dar forma a piezas donde la imagen, el
          cuerpo y el contexto dialogan.
        </p>
      </div>
      <div className="bio__item">
        <span className="bio__n muted">02 / ENFOQUE</span>
        <p>
          Proyectos colaborativos con una mirada sensible y contemporánea.
          Estética, memoria y dinámicas sociales como ejes narrativos. Desde la
          dirección hasta el diseño visual, un trabajo expresivo y adaptable.
        </p>
      </div>
    </div>
  );
}

function BioDropcap() {
  return (
    <div className="bio bio--dropcap">
      <p className="bio__lede serif">
        <span className="bio__cap">M</span>apa López es creadora audiovisual
        especializada en la construcción de narrativas visuales y sonoras que
        combinan dirección, edición, fotografía y diseño sonoro. Su práctica
        integra lo técnico y lo creativo para dar forma a piezas donde la
        imagen, el cuerpo y el contexto dialogan de manera constante.
      </p>
      <p className="bio__body mono">
        Desarrolla proyectos colaborativos con un enfoque sensible y
        contemporáneo, explorando la estética, la memoria y las dinámicas
        sociales como ejes narrativos. Desde la dirección y la producción hasta
        el diseño visual, su trabajo busca crear piezas coherentes, expresivas y
        adaptables a distintos formatos y plataformas.
      </p>
    </div>
  );
}

function About() {
  const variant =
    (typeof document !== "undefined" && document.documentElement.dataset.bio) ||
    "prose";
  const [, forceRender] = useStateS(0);

  // re-render when [data-bio] changes on <html>
  React.useEffect(() => {
    const obs = new MutationObserver(() => forceRender((n) => n + 1));
    obs.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ["data-bio"],
    });
    return () => obs.disconnect();
  }, []);

  const current = document.documentElement.dataset.bio || "prose";
  const Body =
    {
      prose: BioProse,
      fragments: BioFragments,
      index: BioIndex,
      dropcap: BioDropcap,
    }[current] || BioProse;

  return (
    <section className="about" id="about" data-screen-label="ABOUT">
      <div className="about__head mono">
        <span className="strip__label">SOBRE MÍ</span>
      </div>
      <div className="about__body">
        <p className="about__lead serif">
          Una década documentando el pulso de la música y la memoria colectiva
          de América Latina.
        </p>
        <div className="about__cols mono">
          <div>
            <div className="muted">BIO</div>
            <Body />
          </div>
        </div>
      </div>
    </section>
  );
}

function MotionThumb({ v, children }) {
  return (
    <div className="motion__thumb">
      <Img
        src={`https://img.youtube.com/vi/${v.id}/maxresdefault.jpg`}
        alt={v.title}
        aspectRatio="16/9"
        onError={(e) => {
          const img = e.target;
          if (!img.dataset.fallbackTried) {
            img.dataset.fallbackTried = "1";
            img.src = `https://img.youtube.com/vi/${v.id}/hqdefault.jpg`;
          }
        }}
        fallbackLabel={v.title?.toUpperCase() || "VIDEO"}
      />
      {children}
    </div>
  );
}

// VARIANT 1 — Grid (refined existing): 2-col grid + description beneath each card
function MotionGrid({ items, onPlay }) {
  return (
    <div className="motion__grid">
      {items.map((v, i) => (
        <article className="motion__card" key={v.id} onClick={() => onPlay(v)}>
          <MotionThumb v={v}>
            <div className="motion__play">▶ REPRODUCIR</div>
            <span className="motion__dur mono">{v.dur}</span>
          </MotionThumb>
          <div className="motion__meta mono">
            <span>
              {String(i + 1).padStart(2, "0")} · {v.title}
            </span>
            <span className="muted">{v.year}</span>
          </div>
          {v.description && (
            <p className="motion__desc mono">{v.description}</p>
          )}
          {v.role && (
            <div className="motion__credit mono muted">
              {v.role} · {v.location}
            </div>
          )}
        </article>
      ))}
    </div>
  );
}

// VARIANT 2 — Feature: one large "now showing" + a sidebar list of the rest.
function MotionFeature({ items, onPlay }) {
  const [hero, setHero] = useStateS(items[0]);
  React.useEffect(() => {
    setHero(items[0]);
  }, [items]);
  return (
    <div className="motion-feat">
      <article className="motion-feat__hero" onClick={() => onPlay(hero)}>
        <MotionThumb v={hero}>
          <div className="motion-feat__hero-overlay">
            <div className="motion-feat__hero-tags mono">
              {(hero.tags || []).map((t) => (
                <span key={t}>{t}</span>
              ))}
            </div>
            <div className="motion-feat__hero-play mono">
              ▶ REPRODUCIR · {hero.dur}
            </div>
          </div>
          <span className="motion__dur mono">{hero.dur}</span>
        </MotionThumb>
        <div className="motion-feat__hero-body">
          <div className="motion-feat__hero-kicker mono muted">
            EN PANTALLA · {hero.year} · {hero.location}
          </div>
          <h3 className="motion-feat__hero-title serif">{hero.title}</h3>
          <p className="motion-feat__hero-syn serif">{hero.synopsis}</p>
          <div className="motion-feat__hero-credit mono muted">{hero.role}</div>
        </div>
      </article>
      <aside className="motion-feat__list">
        <div className="motion-feat__list-label mono muted">
          / TAMBIÉN EN CARTELERA
        </div>
        {items.map((v, i) => {
          const isHero = v.id === hero.id;
          return (
            <button
              key={v.id}
              className={`motion-feat__row ${isHero ? "is-active" : ""}`}
              onClick={() => (isHero ? onPlay(v) : setHero(v))}
            >
              <span className="motion-feat__row-n mono muted">
                {String(i + 1).padStart(2, "0")}
              </span>
              <div className="motion-feat__row-thumb">
                <Img
                  src={`https://img.youtube.com/vi/${v.id}/hqdefault.jpg`}
                  alt={v.title}
                  aspectRatio="16/9"
                  fallbackLabel={v.title}
                />
              </div>
              <div className="motion-feat__row-meta mono">
                <span className="motion-feat__row-title">{v.title}</span>
                <span className="muted">
                  {v.year} · {v.dur}
                </span>
              </div>
              <span className="motion-feat__row-arrow mono">
                {isHero ? "▶" : "→"}
              </span>
            </button>
          );
        })}
      </aside>
    </div>
  );
}

// VARIANT 3 — Index: editorial filmography. Numbered rows, hover reveals thumb.
function MotionIndex({ items, onPlay }) {
  const [hover, setHover] = useStateS(null);
  return (
    <div className="motion-idx">
      <div className="motion-idx__header mono muted">
        <span className="motion-idx__h-n">N°</span>
        <span className="motion-idx__h-title">TÍTULO</span>
        <span className="motion-idx__h-year">AÑO</span>
        <span className="motion-idx__h-loc">LOCACIÓN</span>
        <span className="motion-idx__h-dur">DUR.</span>
        <span className="motion-idx__h-role">CRÉDITO</span>
      </div>
      {items.map((v, i) => (
        <article
          key={v.id}
          className="motion-idx__row"
          onClick={() => onPlay(v)}
          onMouseEnter={() => setHover(v)}
          onMouseLeave={() => setHover((h) => (h && h.id === v.id ? null : h))}
        >
          <span className="motion-idx__n mono muted">
            {String(i + 1).padStart(2, "0")}
          </span>
          <div className="motion-idx__title">
            <h3 className="serif">{v.title}</h3>
            <p className="mono motion-idx__desc">{v.description}</p>
          </div>
          <span className="motion-idx__year mono">{v.year}</span>
          <span className="motion-idx__loc mono muted">{v.location}</span>
          <span className="motion-idx__dur mono">{v.dur}</span>
          <span className="motion-idx__role mono muted">{v.role}</span>
          <span className="motion-idx__play mono">▶</span>
        </article>
      ))}
      {hover && (
        <div className="motion-idx__preview" key={hover.id}>
          <Img
            src={`https://img.youtube.com/vi/${hover.id}/maxresdefault.jpg`}
            alt={hover.title}
            aspectRatio="16/9"
            fallbackLabel={hover.title}
          />
          <span className="mono">{hover.title}</span>
        </div>
      )}
    </div>
  );
}

// VARIANT 4 — Reel: horizontal cinemascope strip with description block per item.
function MotionReel({ items, onPlay }) {
  const [idx, setIdx] = useStateS(0);
  const v = items[idx] || items[0];
  return (
    <div className="motion-reel">
      <div className="motion-reel__stage" onClick={() => onPlay(v)}>
        <MotionThumb v={v}>
          <div className="motion-reel__stage-overlay">
            <div className="motion-reel__stage-play mono">▶ REPRODUCIR</div>
          </div>
          <span className="motion__dur mono">{v.dur}</span>
        </MotionThumb>
      </div>
      <div className="motion-reel__info">
        <div className="motion-reel__info-head mono muted">
          <span>
            FILM N° {String(idx + 1).padStart(2, "0")} /{" "}
            {String(items.length).padStart(2, "0")}
          </span>
          <span>
            {v.year} · {v.location}
          </span>
        </div>
        <h3 className="motion-reel__title serif">{v.title}</h3>
        <p className="motion-reel__syn mono">{v.synopsis}</p>
        <div className="motion-reel__tags mono">
          {(v.tags || []).map((t) => (
            <span key={t}>{t}</span>
          ))}
        </div>
        <div className="motion-reel__credit mono muted">{v.role}</div>
      </div>
      <div className="motion-reel__strip">
        {items.map((it, i) => (
          <button
            key={it.id}
            className={`motion-reel__cell ${i === idx ? "is-active" : ""}`}
            onClick={() => setIdx(i)}
          >
            <div className="motion-reel__cell-thumb">
              <Img
                src={`https://img.youtube.com/vi/${it.id}/hqdefault.jpg`}
                alt={it.title}
                aspectRatio="16/9"
                fallbackLabel={it.title}
              />
            </div>
            <div className="motion-reel__cell-meta mono">
              <span className="muted">{String(i + 1).padStart(2, "0")}</span>
              <span>{it.title}</span>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

// VARIANT 5 — Editorial stack: full-width rows, image alternates left/right.
// Inspired by editorial "Minimal / Building future" layout with serif title,
// label kicker, body text, outline CTA and a small accent rule.
function MotionStack({ items, onPlay }) {
  return (
    <div className="motion-stk">
      {items.map((v, i) => {
        const reverse = i % 2 === 1;
        return (
          <article
            key={v.id}
            className={`motion-stk__row ${reverse ? "is-reverse" : ""}`}
          >
            <div className="motion-stk__media" onClick={() => onPlay(v)}>
              <MotionThumb v={v}>
                <div className="motion-stk__media-overlay">
                  <span className="motion-stk__media-play mono">
                    ▶ REPRODUCIR
                  </span>
                </div>
                <span className="motion__dur mono">{v.dur}</span>
              </MotionThumb>
              <span className="motion-stk__media-bar" aria-hidden="true" />
            </div>
            <div className="motion-stk__body">
              <div className="motion-stk__index mono muted">
                FILM N° {String(i + 1).padStart(2, "0")} — {v.year} ·{" "}
                {v.location}
              </div>
              <h3 className="motion-stk__title serif">{v.title}</h3>
              <div className="motion-stk__kicker mono">
                {(v.tags && v.tags[0]) || "PIEZA AUDIOVISUAL"}
              </div>
              <span className="motion-stk__rule" aria-hidden="true" />
              <p className="motion-stk__desc mono">{v.description}</p>
              <div className="motion-stk__credit mono muted">{v.role}</div>
            </div>
          </article>
        );
      })}
    </div>
  );
}

const MOTION_VARIANT_NAME = {
  GRID: "grid",
  FEATURE: "feature",
  INDEX: "index",
  REEL: "reel",
  STACK: "stack",
};
const MOTION_VARIANTS = [
  { id: MOTION_VARIANT_NAME.GRID, label: "GRID" },
  { id: MOTION_VARIANT_NAME.FEATURE, label: "EN PANTALLA" },
  { id: MOTION_VARIANT_NAME.INDEX, label: "ÍNDICE" },
  { id: MOTION_VARIANT_NAME.REEL, label: "ROLLO" },
  { id: MOTION_VARIANT_NAME.STACK, label: "EDITORIAL" },
];
const DEFAULT_MOTION_VARIANT = MOTION_VARIANT_NAME.STACK;

function Motion({ items }) {
  const [active, setActive] = useStateS(null);
  const [variant, setVariant] = useStateS(() => {
    return (
      (typeof document !== "undefined" &&
        document.documentElement.dataset.motionLayout) ||
      DEFAULT_MOTION_VARIANT
    );
  });

  // sync from data attr (in case Tweaks change it)
  React.useEffect(() => {
    const obs = new MutationObserver(() => {
      const v =
        document.documentElement.dataset.motionLayout || DEFAULT_MOTION_VARIANT;
      setVariant(v);
    });
    obs.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ["data-motion-layout"],
    });
    return () => obs.disconnect();
  }, []);

  const Body =
    variant === "feature"
      ? MotionFeature
      : variant === "index"
        ? MotionIndex
        : variant === "reel"
          ? MotionReel
          : variant === "stack"
            ? MotionStack
            : MotionGrid;

  const setVariantPersist = (v) => {
    document.documentElement.dataset.motionLayout = v;
    setVariant(v);
    if (window.parent) {
      window.parent.postMessage(
        { type: "__edit_mode_set_keys", edits: { motionLayout: v } },
        "*",
      );
    }
  };

  return (
    <section
      className={`motion motion--${variant}`}
      id="motion"
      data-screen-label="MOTION"
    >
      <header className="strip__head motion__head">
        <div className="strip__meta mono">
          <span className="strip__label">CINE / VIDEO</span>
          <span className="muted">— {items.length} PIEZAS</span>
        </div>
        <div className="motion__switch mono" role="tablist" aria-label="Layout">
          {MOTION_VARIANTS.map((mv) => (
            <button
              key={mv.id}
              role="tab"
              aria-selected={variant === mv.id}
              className={variant === mv.id ? "is-active" : ""}
              onClick={() => setVariantPersist(mv.id)}
            >
              {mv.label}
            </button>
          ))}
        </div>
      </header>

      <Body items={items} onPlay={setActive} />

      {/* {active && (
        <div className="motion__player" onClick={() => setActive(null)}>
          <div
            className="motion__player-inner"
            onClick={(e) => e.stopPropagation()}
          >
            <iframe
              src={`https://www.youtube.com/embed/${active.id}?autoplay=1`}
              title={active.title}
              allow="autoplay; encrypted-media"
              allowFullScreen
            />
            <div className="motion__player-meta mono">
              <span>{active.title}</span>
              <span className="muted">
                {active.year} · {active.dur} · {active.role}
              </span>
            </div>
            <button className="lightbox__close" onClick={() => setActive(null)}>
              CERRAR ✕
            </button>
          </div>
        </div>
      )} */}
    </section>
  );
}

Motion.variants = MOTION_VARIANTS;
Motion.defaultVariant = DEFAULT_MOTION_VARIANT;

function Services() {
  const items = [
    {
      n: "01",
      t: "DOCUMENTAL",
      d: "Reportaje fotográfico y audiovisual de largo aliento.",
    },
    {
      n: "02",
      t: "CONCIERTO & GIRA",
      d: "Cobertura de tour para artistas y sellos.",
    },
    {
      n: "03",
      t: "RETRATO EDITORIAL",
      d: "Revistas, campañas y portadas discográficas.",
    },
  ];
  return (
    <section className="services" id="services" data-screen-label="SERVICES">
      <header className="strip__head">
        <div className="strip__meta mono">
          <span className="strip__label">SERVICIOS</span>
        </div>
        <a className="mono link" href="#contact">
          ESCRIBIR →
        </a>
      </header>
      <div className="services__list">
        {items.map((it) => (
          <article className="services__row" key={it.n}>
            <span className="mono muted services__n">{it.n}</span>
            <h3 className="services__t serif">{it.t}</h3>
            <p className="services__d mono">{it.d}</p>
            <span className="services__arrow mono">→</span>
          </article>
        ))}
      </div>
    </section>
  );
}

function Shop({ items }) {
  return (
    <section className="shop" id="shop" data-screen-label="SHOP">
      <header className="strip__head">
        <div className="strip__meta mono">
          <span className="strip__label">TIENDA · EDICIÓN LIMITADA</span>
        </div>
      </header>
      <div className="shop__grid">
        {items.map((p, i) => (
          <article className="shop__card" key={i}>
            <div className="shop__img">
              <Img
                src={p.src}
                alt={p.title}
                aspectRatio="3/4"
                fallbackLabel={p.title?.toUpperCase()}
              />
            </div>
            <div className="shop__meta mono">
              <div className="shop__row">
                <span>
                  {String(i + 1).padStart(2, "0")} · {p.title}
                </span>
                <span>{p.price}</span>
              </div>
              <div className="shop__row muted">
                <span>
                  {p.edition} · {p.size}
                </span>
                <a href="#" className="link">
                  AÑADIR →
                </a>
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="footer" id="footer" data-screen-label="footer">
      {/* <div className="footer__head mono">
        <span className="strip__label">CONTACTO</span>
      </div>
      <div className="footer__grid">
        <h2 className="footer__big serif">
          ¿Un proyecto en mente?<br/>
          <em>Conversemos.</em>
        </h2>
        <div className="footer__cols mono">
          <div>
            <div className="muted">DIRECTO</div>
            <p><a className="link" href="mailto:mariapaulalopez360@gmail.com">mariapaulalopez360@gmail.com</a></p>
          </div>
          <div>
            <div className="muted">SOCIAL</div>
            <p>
              <a className="link" href="https://instagram.com/mapa.lol" target="_blank" rel="noopener">INSTAGRAM ↗</a><br/>
              <a className="link" href="https://youtube.com/@mapalopez" target="_blank" rel="noopener">YOUTUBE ↗</a><br/>
              <a className="link" href="whatsapp://send?phone=33781137985" target="_blank" rel="noopener">WHATSAPP ↗</a>
            </p>
          </div>
        </div>
      </div> */}
      <div className="footer__bottom mono muted">
        <span>© 2016–2026 MAPA LÓPEZ</span>
        <span>SITE v1.0 · CDMX</span>
      </div>
    </footer>
  );
}

function Kiosco() {
  const links = [
    {
      n: "01",
      platform: "INSTAGRAM",
      handle: "@mapa.lol",
      desc: "Archivo visual en curso. Fotografía, making-of y destellos del proceso creativo.",
      href: "https://instagram.com/mapa.lol",
      cta: "SEGUIR ↗",
    },
    {
      n: "02",
      platform: "YOUTUBE",
      handle: "@mapalopez",
      desc: "Canal de video. Documentales, piezas audiovisuales y reels de concierto.",
      href: "https://youtube.com/@mapalopez",
      cta: "SUSCRIBIR ↗",
    },
    {
      n: "03",
      platform: "WHATSAPP",
      handle: "+33 7 81 13 79 85",
      desc: "Consultas rápidas, presupuestos y coordinación de proyectos.",
      href: "whatsapp://send?phone=33781137985",
      cta: "ESCRIBIR ↗",
    },
    {
      n: "04",
      platform: "E-MAIL",
      handle: "mariapaulalopez360\n@gmail.com",
      desc: "Para propuestas formales, colaboraciones y proyectos de largo aliento.",
      href: "mailto:mariapaulalopez360@gmail.com",
      cta: "ENVIAR →",
      featured: true,
    },
  ];

  const small = links.filter((l) => !l.featured);
  const featured = links.find((l) => l.featured);

  return (
    <section className="kiosco" id="kiosco" data-screen-label="KIOSCO">
      <header className="strip__head kiosco__head">
        <div className="strip__meta mono">
          <span className="strip__label">KIOSCO</span>
        </div>
      </header>

      <div className="kiosco__spread">
        {/* LEFT — small grid + captions */}
        <div className="kiosco__left">
          <div className="kiosco__grid">
            {small.map((l) => (
              <a
                key={l.n}
                href={l.href}
                className="kiosco__card"
                target={l.href.startsWith("http") ? "_blank" : undefined}
                rel="noopener noreferrer"
              >
                <div className="kiosco__card-inner">
                  {/* <span className="kiosco__card-n mono muted">{l.n}</span> */}
                  <span className="kiosco__card-platform mono">
                    {l.platform}
                  </span>
                  <span className="kiosco__card-handle serif">{l.handle}</span>
                  <span className="kiosco__card-cta mono">{l.cta}</span>
                </div>
              </a>
            ))}
          </div>

          {/* Captions below grid */}
          {/* <div className="kiosco__captions mono">
            {small.map((l) => (
              <p key={l.n} className="kiosco__caption">
                <span className="kiosco__caption-n muted">{l.n}.</span>
                {" "}{l.desc}
              </p>
            ))}
          </div> */}
        </div>

        {/* RIGHT — featured large card */}
        {featured && (
          <a href={featured.href} className="kiosco__featured">
            <div className="kiosco__featured-inner">
              {/* <span className="kiosco__featured-n mono muted">{featured.n}</span> */}
              <span className="kiosco__featured-platform mono">
                {featured.platform}
              </span>
              <span className="kiosco__featured-handle serif">
                {featured.handle}
              </span>
              <p className="kiosco__featured-desc mono">{featured.desc}</p>
              <span className="kiosco__featured-cta mono">{featured.cta}</span>
            </div>
          </a>
        )}
      </div>

      {/* Bottom credits strip */}
      {/* <div className="kiosco__foot mono muted">
        <span>MAPA LÓPEZ — CANALES OFICIALES</span>
        <span>CDMX · PARIS</span>
      </div> */}
    </section>
  );
}

window.About = About;
window.Motion = Motion;
window.Services = Services;
window.Shop = Shop;
window.Footer = Footer;
window.Kiosco = Kiosco;
