/* ARKHAM — Project Viewer: a chaptered "Original" walkthrough of a project */
const { useState: vS, useEffect: vE, useContext: vC } = React;

function sceneBg(p, shift = 0) {
  const h = p.hue + shift;
  return { background: `linear-gradient(150deg, hsl(${h} ${p.sat}% ${p.dark1 + 4}%), hsl(${h} ${Math.max(p.sat - 6, 3)}% ${p.dark2}%))` };
}

function chaptersFor(p) {
  const foto = p.credits["Fotografía"] || "—";
  const ch = [
    { kind: "title", name: "Portada", mediaTag: "Cinemagraph · toma principal", shift: 0 },
    { kind: "split", name: "01 · El sueño", chapter: "01 — El sueño", h: "Concepto", body: p.desc, mediaTag: "Bocetos y croquis de concepto", shift: -12 }
  ];
  if (p.hasClient) ch.push({ kind: "interview", name: "La conversación", mediaTag: "Entrevista con el cliente", capName: "En palabras del cliente", capRole: `${p.tipo} · ${p.title}`, shift: 12 });
  if (p.hasObra) ch.push({ kind: "split", name: "La obra", chapter: "— La obra", h: "Supervisión de obra", body: "El registro del proceso: bitácora, visitas a obra y los detalles que solo se aprecian mientras se construye.", mediaTag: "Bitácora de construcción", wip: p.progress, shift: -6 });
  ch.push({ kind: "gallery", name: "El resultado", chapter: "— El resultado", h: "Fotografía", body: `Fotografía · ${foto}`, shift: 7 });
  ch.push({ kind: "credits", name: "Ficha técnica", shift: 0 });
  return ch;
}

function ProjectViewer({ id }) {
  const ctx = vC(AppCtx);
  const p = window.ARKHAM.byId[id];
  const chapters = chaptersFor(p);
  const [i, setI] = vS(0);

  const go = (d) => {
    const n = i + d;
    if (n < 0) return;
    if (n >= chapters.length) { ctx.triggerIdle(); return; }
    setI(n);
  };

  vE(() => {
    const onKey = (e) => {
      if (e.key === "Escape") ctx.stop();
      else if (e.key === "ArrowRight") go(1);
      else if (e.key === "ArrowLeft") go(-1);
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [i]);

  const renderScene = (c) => {
    if (c.kind === "title") return (
      <>
        <div className="vs-original"><img className="iso" src="assets/arkham-iso-white.png" alt="" /><span className="tag">Original</span></div>
        <div className="vs-title-wrap">
          <div className="vs-kicker">{p.genres[0]}</div>
          <div className={"vs-bigtitle " + p.titleClass} style={{ fontSize: p.titleClass === "pt-script" ? 104 : 82 }}>
            {p.title}{p.sub && <span className="poster-sub" style={{ fontSize: 16 }}>{p.sub}</span>}
          </div>
          <div className="vs-meta">{p.tipo} · {p.year} · {p.rating}</div>
        </div>
      </>
    );
    if (c.kind === "split") return (
      <div className="vs-split-text">
        <div className="vs-chapter">{c.chapter}</div>
        <h2 className="vs-h">{c.h}</h2>
        <p className="vs-body">{c.body}</p>
        {c.wip != null && (
          <div className="vs-wip">
            <div className="vs-wip-bar"><span style={{ width: c.wip + "%" }} /></div>
            <span className="lbl">{c.wip}% en proceso</span>
          </div>
        )}
      </div>
    );
    if (c.kind === "interview") return (
      <>
        <div className="vs-interview">
          <button className="vs-play-big" onClick={() => ctx.toast("Reproduciendo entrevista…")}><Icon.Play s={34} /></button>
        </div>
        <div className="vs-caption">
          <div className="name">{c.capName}</div>
          <div className="role">{c.capRole}</div>
        </div>
      </>
    );
    if (c.kind === "gallery") {
      const tiles = [0, 1, 2, 3, 4];
      return (
        <div className="vs-gallery-wrap">
          <div className="vs-gallery-head">
            <div className="vs-chapter">{c.chapter}</div>
            <h2 className="vs-h">{c.h}</h2>
            <p className="vs-body">{c.body}</p>
          </div>
          <div className="vs-gallery-grid">
            {tiles.map((t, k) => (
              <div className={"vs-tile" + (k === 0 ? " big" : "")} key={k}>
                <div style={{ position: "absolute", inset: 0, ...sceneBg(p, (k - 2) * 9) }} />
                <div className="poster-tex" />
                <div className="vs-ph-tag">foto {k + 1}</div>
              </div>
            ))}
          </div>
        </div>
      );
    }
    if (c.kind === "credits") return (
      <div className="vs-credits-wrap">
        <div className="vs-credits-inner">
          <div className="vs-credits-title">Ficha técnica</div>
          <div className="vs-credits-list">
            {Object.entries(p.credits).map(([k, v]) => (
              <div className="vs-credit-row" key={k}><div className="k">{k}</div><div className="v">{v}</div></div>
            ))}
            <div className="vs-credit-row"><div className="k">Tipo</div><div className="v">{p.tipo}</div></div>
          </div>
          <div className="vs-credits-end">
            <button className="btn btn-play" onClick={() => setI(0)}><Icon.Replay s={20} /> Ver de nuevo</button>
            <button className="btn btn-info" onClick={() => { ctx.stop(); ctx.go("home"); }}>Volver al inicio</button>
          </div>
        </div>
      </div>
    );
  };

  const cur = chapters[i];
  return (
    <div className="viewer">
      {chapters.map((c, idx) => (
        <div className={"vs" + (idx === i ? " active" : "")} key={idx} aria-hidden={idx !== i}>
          <div className="vs-bg" style={sceneBg(p, c.shift)} />
          {(c.kind === "title" || c.kind === "split" || c.kind === "interview") && <div className="vs-ph-tag">{c.mediaTag}</div>}
          <div className={"vs-scrim" + (c.kind === "split" ? " left" : "")} />
          <div className="vs-content">{renderScene(c)}</div>
        </div>
      ))}

      <div className="viewer-top">
        <button className="viewer-back" onClick={ctx.stop}><Icon.Back s={28} /> Volver</button>
        <span className="viewer-proj">{p.title}</span>
        <span className="viewer-count">{i + 1} / {chapters.length}</span>
      </div>

      <button className="viewer-arrow left" onClick={() => go(-1)} disabled={i === 0} aria-label="anterior"><Icon.ChevL s={26} /></button>
      <button className="viewer-arrow right" onClick={() => go(1)} aria-label="siguiente"><Icon.ChevR s={26} /></button>

      <div className="viewer-rail">
        <div className="viewer-rail-name">{cur.name}</div>
        <div className="viewer-segs">
          {chapters.map((c, idx) => (
            <button key={idx} className={"viewer-seg" + (idx === i ? " active" : idx < i ? " done" : "")}
              onClick={() => setI(idx)} aria-label={c.name}>
              {idx === i && <span />}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ProjectViewer });
