const { KinoTape, tapeAdvance, MicroText, Frame, Timecode, CameraStatus, Button, Tag } = window.DASKINODesignSystem_5a312e;

/** Width of the page column, minus gutters — so the seam word can be fitted to it. */
function useColumn() {
  const ref = React.useRef(null);
  const [w, setW] = React.useState(1200);
  React.useEffect(() => {
    const read = () => ref.current && setW(ref.current.getBoundingClientRect().width);
    read();
    window.addEventListener("resize", read);
    return () => window.removeEventListener("resize", read);
  }, []);
  return [ref, w];
}

/**
 * The studio signature under the frame. ONE material, one ground: isolante on
 * paper. Set at a fixed cap and scaled to the column so it spans it edge to
 * edge — the scale does the work, not a trick.
 */
const CAP = 180;
function Masthead({ text, width }) {
  const inner = React.useRef(null);
  const [nat, setNat] = React.useState(null);
  React.useEffect(() => {
    const el = inner.current;
    if (!el || typeof ResizeObserver === "undefined") return;
    const ro = new ResizeObserver(() => setNat({ w: el.offsetWidth, h: el.offsetHeight }));
    ro.observe(el);
    setNat({ w: el.offsetWidth, h: el.offsetHeight });
    return () => ro.disconnect();
  }, [text]);
  const k = nat && nat.w ? width / nat.w : 1;
  return (
    <div style={{ width, height: nat ? nat.h * k : undefined, overflow: "hidden", pointerEvents: "none" }}>
      <div ref={inner} style={{ display: "inline-block", transform: `scale(${k})`, transformOrigin: "left top", visibility: nat ? "visible" : "hidden" }}>
        <KinoTape cut="isolante" cap={CAP} text={text} style={{ display: "block" }} />
      </div>
    </div>
  );
}

/** The paper caption card on the still — slate, headline, one line under it. */
function Slate({ kicker, title, body, onClick }) {
  const head = <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: "0.02em", marginBottom: 8, textWrap: "pretty" }}>{title}</div>;
  return (
    <div className="kino-paper" style={{ background: "var(--kino-paper)", padding: "18px 22px 20px", width: "min(420px,72vw)", pointerEvents: "auto" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
        <span style={{ width: 9, height: 9, background: "var(--kino-black)", display: "block" }} />
        <MicroText size="xs" tone="dim">{kicker}</MicroText>
      </div>
      {onClick
        ? <button onClick={onClick} style={{ background: "none", border: "none", padding: 0, cursor: "pointer", display: "block", textAlign: "left", font: "inherit", color: "inherit" }}>{head}</button>
        : head}
      <p style={{ margin: 0, fontSize: 12, lineHeight: 1.6, letterSpacing: "0.01em", color: "var(--text-secondary)", textAlign: "justify" }}>{body}</p>
    </div>
  );
}

function SiteHome({ go }) {
  const [ref, w] = useColumn();
  const gut = Math.min(56, Math.max(20, w * 0.04));
  /* Os três projetos que têm mídia de verdade vinda do deck: cinco fotos de
     câmera, cinco GIFs e um GIF. O resto do arquivo espera as suas fotos. */
  const selected = ["entre-pontos","faca-por-voce","ippuc"].map(s => window.FILMS.find(f => f.slug === s)).filter(Boolean);
  return (
    <div ref={ref} className="kino-paper" style={{ background: "var(--kino-paper)", color: "var(--text-primary)" }}>

      <section style={{ padding: `0 ${gut}px`, marginBottom: "clamp(60px,8vw,110px)", display: "flex", flexDirection: "column", gap: "clamp(12px,1.4vw,20px)" }} data-screen-label="Hero">
        <div style={{ position: "relative", background: "var(--kino-black)" }}>
          <window.Shot src={window.ABERTURA} idx={0} ratio="4:3" overlay={0.18} />
          <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", justifyContent: "space-between", padding: "clamp(16px,2vw,28px)", pointerEvents: "none" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 20 }}>
              <Timecode value="00:00:00:00" running size={11} />
              <CameraStatus size={11} />
            </div>
            <Slate kicker="REEL 26 / ABERTURA" title={window.SOBRE[0]} body={window.SOBRE[1]} onClick={() => go("estudio")} />
          </div>
        </div>
        <Masthead text="DAS KINO" width={Math.max(320, w - gut * 2)} />
      </section>

      <section style={{ padding: `0 ${gut}px`, display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,300px),1fr))", gap: "clamp(30px,5vw,70px)", alignItems: "start", marginBottom: "clamp(60px,8vw,120px)" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ width: 9, height: 9, background: "var(--kino-black)", display: "block" }} />
            <MicroText size="sm" weight={600}>O RITUAL DE FILMAR</MicroText>
          </div>
          <p style={{ margin: 0, fontSize: "clamp(19px,2vw,25px)", fontWeight: 400, lineHeight: 1.45, letterSpacing: "0.01em", textAlign: "justify" }}>
            Nossa base é o audiovisual, mas não o nosso limite. Transformamos identidade, cultura e estratégia em manifestações visuais.
          </p>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 26, alignItems: "start" }}>
          <p style={{ margin: 0, fontSize: 11.5, lineHeight: 1.75, letterSpacing: "0.02em", color: "var(--text-secondary)", textAlign: "justify" }}>
            A DAS KINO nasceu da crença de que filme é prática diária, não declaração. Cada peça é feita para se mover com o cliente — pela campanha, pela estação, pelo território.
          </p>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <MicroText size="xs" tone="dim">O QUE FAZEMOS</MicroText>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>
              {["Filme","Documental","Fotografia","Animação","Design","Motion","Estratégia"].map(t => <Tag key={t}>{t}</Tag>)}
            </div>
          </div>
        </div>
      </section>

      <section style={{ padding: `0 ${gut}px`, display: "grid", gridTemplateColumns: "1.35fr 1fr", gap: "clamp(18px,2.4vw,34px)", alignItems: "end", marginBottom: "clamp(70px,9vw,140px)" }}>
        <window.Shot src={window.FILMS[0].cover} idx={1} ratio="4:5" overlay={0.12} />
        <div style={{ display: "flex", flexDirection: "column", gap: "clamp(18px,2.4vw,34px)" }}>
          <window.Shot src={window.FILMS[3].cover} idx={2} ratio="1:1" overlay={0.12} style={{ width: "78%" }} />
          <div style={{ display: "flex", flexDirection: "column", gap: 12, paddingLeft: "22%" }}>
            <MicroText size="xs" tone="dim">ENTRE O DOCUMENTAL E A PUBLICIDADE</MicroText>
            <p style={{ margin: 0, fontSize: 11.5, lineHeight: 1.75, letterSpacing: "0.02em", color: "var(--text-secondary)", textAlign: "justify" }}>
              Filmamos onde a coisa acontece: mercado, porto, casa, estrada. O belo no feio, o novo no óbvio, o caos na ordem.
            </p>
          </div>
        </div>
      </section>

      <section style={{ padding: `0 ${gut}px`, marginBottom: "clamp(70px,9vw,130px)" }}>
        <window.Head label="TRABALHO SELECIONADO" right={
          <button onClick={() => go("trabalhos")} style={{ background: "none", border: "none", padding: 0, cursor: "pointer", fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--text-primary)", borderBottom: "1px solid var(--rule-strong)" }}>Todos os projetos</button>
        } />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,280px),1fr))", gap: "34px 24px" }}>
          {selected.map((f, i) => (
            <button key={f.slug} onClick={() => go("projeto", f.slug)} style={{ background: "none", border: "none", padding: 0, cursor: "pointer", textAlign: "left", display: "block", color: "var(--text-primary)" }}>
              <window.Shot src={f.cover} idx={i} overlay={0.42}>
                <div style={{ position: "absolute", left: 0, bottom: 0 }}>
                  <KinoTape ground="dark" cap={Math.max(30, 300 / (0.4 * f.word.length))} text={f.word} />
                </div>
              </window.Shot>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, paddingTop: 12 }}>
                <MicroText size="sm" weight={600}>{f.word}</MicroText>
                <MicroText size="sm" tone="dim">{f.cat}</MicroText>
              </div>
            </button>
          ))}
        </div>
      </section>

      <section style={{ padding: `0 ${gut}px clamp(70px,9vw,120px)`, display: "flex", flexWrap: "wrap", justifyContent: "space-between", alignItems: "flex-end", gap: 24 }}>
        <p style={{ margin: 0, maxWidth: "22ch", fontSize: "clamp(18px,2vw,24px)", lineHeight: 1.4, letterSpacing: "0.01em" }}>Um bom filme às vezes não é um filme.</p>
        <div style={{ display: "flex", gap: 10 }}>
          <Button onClick={() => go("trabalhos")}>Ver trabalhos</Button>
          <Button variant="ghost" onClick={() => go("contato")}>Briefing</Button>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { SiteHome, Masthead });
