const { MicroText, Timecode, CameraStatus, Button, Tag, KinoTape } = window.DASKINODesignSystem_5a312e;
const { EdRule, EdKicker, EdHead, EdDek, EdBody, EdDropCap, EdCaption, EdSection, EdIndexRow } = window;

function useCol() {
  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];
}

/* Um trabalho selecionado no fundo preto: a imagem, a palavra na fita por
   cima, a entrega embaixo. É a feição do site antigo — e a que funciona. */
function TapeCard({ f, n, go, big }) {
  const [h, setH] = React.useState(false);
  const wrap = React.useRef(null);
  const [w, setW] = React.useState(0);
  React.useEffect(() => {
    const el = wrap.current;
    if (!el) return;
    const read = () => setW(el.clientWidth);
    read();
    const ro = new ResizeObserver(read);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);
  const cap = w ? Math.max(14, Math.min(big ? 62 : 34, (w - 24) / (0.42 * f.word.length))) : 20;
  return (
    <button onClick={() => go("projeto", f.slug)} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      className={f.uf}
      style={{ background: "none", border: "none", padding: 0, cursor: "pointer", textAlign: "left", display: "flex", flexDirection: "column", gap: 12, color: "var(--kino-white)", width: "100%", gridColumn: big ? "span 2" : "auto" }}>
      <span ref={wrap} style={{ display: "block", position: "relative", width: "100%" }}>
        <window.Shot src={f.cover} idx={n} ratio={big ? "16:9" : "4:3"} overlay={h ? 0.24 : 0.42}>
          <span style={{ position: "absolute", left: 0, bottom: 0 }}>
            <KinoTape ground="dark" cap={cap} text={f.word} />
          </span>
        </window.Shot>
      </span>
      <span style={{ display: "flex", justifyContent: "space-between", gap: 14, alignItems: "baseline", borderTop: "1px solid var(--rule)", paddingTop: 10 }}>
        <MicroText size="xs" tone={h ? undefined : "dim"} style={{ whiteSpace: "normal", lineHeight: 1.4, textWrap: "pretty" }}>{f.entrega}</MicroText>
        <MicroText size="xs" tone="ghost">{f.cat}</MicroText>
      </span>
    </button>
  );
}

function V2Home({ go }) {
  const [ref, w] = useCol();
  const gut = Math.min(56, Math.max(20, w * 0.04));
  const pad = `0 ${gut}px`;
  /* A ordem vem do peso que a produtora deu a cada trabalho no deck — quatro
     ocupam três páginas ou mais. A informação organiza a página; não aparece
     nela. */
  const sel = window.LEAD;
  const tese = window.SOBRE.slice(1);

  return (
    <div ref={ref}>

      {/* ABERTURA. A primeira linha do manifesto é a manchete, e a imagem vem
          logo abaixo sem nada escrito por cima nem por baixo. */}
      <div className="kino-paper" style={{ background: "var(--kino-paper)", color: "var(--text-primary)" }}>
        <section style={{ padding: `clamp(34px,4.4vw,64px) ${gut}px 0` }} data-screen-label="Abertura">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,300px),1fr))", gap: "clamp(18px,2.6vw,44px)", alignItems: "end", marginBottom: "clamp(26px,3.2vw,46px)" }}>
            <EdHead level="banner" as="h1" weight={450} measure="narrow">{window.SOBRE[0]}</EdHead>
            <div style={{ display: "flex", flexDirection: "column", gap: 16, paddingBottom: 6 }}>
              <EdDek measure="narrow">Uma produtora audiovisual que nasceu antes dos filmes — e continua existindo para ajudar outras narrativas a encontrarem o seu lugar.</EdDek>
              <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: pad, marginBottom: "clamp(20px,2.4vw,32px)" }}>
          <div style={{ background: "var(--kino-black)" }}>
            <window.Shot src={window.ABERTURA_CHAIN} idx={0} ratio="21:9" overlay={0} />
          </div>
        </section>

        {/* A assinatura em fita, preservada do modelo antigo. */}
        <section style={{ padding: pad, marginBottom: "clamp(52px,6.5vw,100px)" }}>
          <window.Masthead text="DAS KINO" width={Math.max(320, w - gut * 2)} />
        </section>

        {/* A TESE. Nove parágrafos compostos como uma coluna de verdade:
            capitular, filete entre colunas, texto justificado com hifenização. */}
        <section style={{ padding: pad, marginBottom: "clamp(56px,7vw,110px)" }} data-screen-label="Manifesto">
          <EdSection label="O RITUAL DE FILMAR" right={<MicroText size="xs" tone="ghost">MANIFESTO</MicroText>} />
          <div style={{ columnWidth: 260, columnGap: "clamp(24px,2.6vw,40px)", columnRule: "1px solid var(--rule)" }}>
            <EdDropCap size={15.5} style={{ marginBottom: "0.85em" }}>{tese[0]}</EdDropCap>
            {tese.slice(1).map((p, i) => (
              <p key={i} style={{ margin: "0 0 0.85em", fontFamily: window.ED, fontSize: 15.5, fontWeight: 300, lineHeight: 1.58, letterSpacing: "var(--tr-editorial)", textAlign: "justify", hyphens: "auto" }}>{p}</p>
            ))}
          </div>
        </section>
      </div>

      {/* SELECIONADOS — fora do escopo de papel, então os tokens voltam ao
          preto sem precisar redeclarar cor nenhuma. O corte de fundo entre
          claro e escuro é o gesto que dá ritmo à página. */}
      <div style={{ background: "var(--kino-black)", color: "var(--kino-white)", padding: `clamp(48px,6vw,88px) 0` }} data-screen-label="Selecionados">
        <section style={{ padding: pad }}>
          <EdSection label="SELECIONADOS" right={
            <button onClick={() => go("trabalhos")} style={{ background: "none", border: "none", padding: 0, cursor: "pointer", fontFamily: window.MONO, fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--kino-white)", borderBottom: "1px solid var(--rule-strong)" }}>Ver o arquivo</button>
          } />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,250px),1fr))", gap: "clamp(24px,3vw,44px)" }}>
            {sel.map((f, i) => <TapeCard key={f.slug} f={f} n={i} go={go} big={i === 0} />)}
          </div>
        </section>
      </div>

      {/* TODOS OS TRABALHOS — o índice, de volta ao papel. */}
      <div className="kino-paper" style={{ background: "var(--kino-paper)", color: "var(--text-primary)" }}>
        <section style={{ padding: `clamp(56px,7vw,100px) ${gut}px clamp(56px,7vw,110px)` }} data-screen-label="Trabalhos">
          <EdSection label="TRABALHOS" count={window.FILMS.length} />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,400px),1fr))", gap: "0 clamp(26px,3vw,52px)" }}>
            {window.FILMS.map((f, i) => <EdIndexRow key={f.slug} f={f} n={i + 1} go={go} dense />)}
          </div>
          <EdRule />
        </section>

        {/* FECHO. */}
        <section style={{ padding: `0 ${gut}px clamp(64px,8vw,116px)` }}>
          <EdRule weight="double" style={{ marginBottom: "clamp(22px,2.6vw,36px)" }} />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,280px),1fr))", gap: "clamp(22px,3vw,48px)", alignItems: "end" }}>
            <EdHead level="md" weight={400} italic measure="narrow">Um bom filme às vezes não é um filme.</EdHead>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap", justifyContent: "flex-end" }}>
              <Button onClick={() => go("trabalhos")}>Ver trabalhos</Button>
              <Button variant="ghost" onClick={() => go("contato")}>Briefing</Button>
            </div>
          </div>
        </section>
      </div>
    </div>
  );
}

Object.assign(window, { V2Home, TapeCard });
