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

/* A CAMADA EDITORIAL.
   O v1 falava numa voz só: mono, tracked, em caixa alta — a voz do aparelho.
   Funciona para um rótulo e trabalha contra qualquer coisa que se leia de fato.
   Aqui entra a segunda voz. A serif é a matéria; o mono continua sendo o
   aparelho em volta dela (folio, rubrica, ficha técnica, crédito). A regra é
   dura e vale para o site inteiro: se é para LER, é serif. Se é para
   IDENTIFICAR, é mono. Nada no meio. */
const ED = "var(--font-editorial)";
const MONO = "var(--font-mono)";

/* Três pesos de régua e cada um quer dizer uma coisa: fina separa itens da
   mesma família, grossa abre uma seção, dupla é masthead — só aparece duas
   vezes na página inteira. */
function EdRule({ weight = "hair", style }) {
  const c = "var(--rule-strong)";
  if (weight === "double") return <div style={{ borderTop: "2.5px solid " + c, borderBottom: "1px solid " + c, height: 4, ...style }} />;
  if (weight === "thick") return <div style={{ borderTop: "2px solid " + c, ...style }} />;
  return <div style={{ borderTop: "1px solid var(--rule)", ...style }} />;
}

/* Rubrica: o mono no seu lugar certo. Número opcional à esquerda, como a
   numeração de seção de uma revista. */
function EdKicker({ children, n, tone = "dim", right }) {
  return (
    <div style={{ display: "flex", alignItems: "baseline", justifyContent: right ? "space-between" : "flex-start", gap: 12, minWidth: 0 }}>
      <span style={{ display: "flex", alignItems: "baseline", gap: 12, minWidth: 0 }}>
        {n != null && <MicroText size="xs" tone="ghost">{String(n).padStart(2, "0")}</MicroText>}
        <MicroText size="xs" tone={tone}>{children}</MicroText>
      </span>
      {right}
    </div>
  );
}

/* Manchete. `level` escolhe o corpo; a serif é sempre apertada e nunca tracked
   — é o oposto do mono, e essa oposição é o ponto. */
const HEADS = { banner: "clamp(40px,7.2vw,104px)", lg: "clamp(32px,5vw,76px)", md: "clamp(26px,3.4vw,52px)", sm: "clamp(21px,2.2vw,34px)", xs: "clamp(18px,1.7vw,25px)" };
function EdHead({ children, level = "md", weight = 400, italic, as = "h2", measure, style }) {
  return React.createElement(as, {
    style: {
      margin: 0, fontFamily: ED, fontOpticalSizing: "auto", fontSize: HEADS[level] || HEADS.md,
      fontWeight: weight, fontStyle: italic ? "italic" : "normal",
      lineHeight: level === "banner" || level === "lg" ? 0.98 : 1.11,
      letterSpacing: "var(--tr-editorial)", textWrap: "balance",
      maxWidth: measure ? "var(--measure-" + measure + ")" : undefined, ...style
    }
  }, children);
}

/* O olho da matéria: a linha que vem sob a manchete e explica. Itálico, um
   corpo acima do texto, cinza. */
function EdDek({ children, measure = "narrow", style }) {
  return <p style={{ margin: 0, fontFamily: ED, fontSize: "clamp(17px,1.5vw,22px)", fontStyle: "italic", fontWeight: 300, lineHeight: 1.42, letterSpacing: "var(--tr-editorial)", color: "var(--text-secondary)", maxWidth: "var(--measure-" + measure + ")", textWrap: "pretty", ...style }}>{children}</p>;
}

/* Corpo de texto. Justificado com hifenização, como se compõe uma coluna
   estreita de verdade — sem isso a serif abre rios. */
function EdBody({ children, size = 16, measure, dim, style }) {
  return <p style={{ margin: 0, fontFamily: ED, fontSize: size, fontWeight: 300, lineHeight: 1.58, letterSpacing: "var(--tr-editorial)", color: dim ? "var(--text-secondary)" : "var(--text-primary)", maxWidth: measure ? "var(--measure-" + measure + ")" : undefined, textAlign: "justify", hyphens: "auto", ...style }}>{children}</p>;
}

/* Capitular. Três linhas de altura, encostada na primeira linha do bloco. */
function EdDropCap({ children, size = 16, style }) {
  const t = String(children || "");
  return (
    <p style={{ margin: 0, fontFamily: ED, fontSize: size, fontWeight: 300, lineHeight: 1.58, letterSpacing: "var(--tr-editorial)", textAlign: "justify", hyphens: "auto", ...style }}>
      <span style={{ float: "left", fontFamily: ED, fontSize: "3.05em", fontWeight: 500, lineHeight: 0.79, paddingRight: "0.055em", marginTop: "0.045em" }}>{t.slice(0, 1)}</span>
      {t.slice(1)}
    </p>
  );
}

/* Legenda de foto: itálico pequeno à esquerda, crédito em mono à direita. É o
   par que faz uma imagem parecer publicada em vez de colada. */
function EdCaption({ children, credit, style }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 24, paddingTop: 9, flexWrap: "wrap", ...style }}>
      <span style={{ fontFamily: ED, fontSize: 13.5, fontStyle: "italic", fontWeight: 300, lineHeight: 1.45, letterSpacing: "var(--tr-editorial)", color: "var(--text-secondary)", maxWidth: "58ch", textWrap: "pretty" }}>{children}</span>
      {credit && <MicroText size="xs" tone="ghost">{credit}</MicroText>}
    </div>
  );
}

/* Cabeça de seção: régua grossa, rubrica, contagem. Abre cada bloco da página. */
function EdSection({ label, count, right, children, style }) {
  return (
    <div style={{ marginBottom: "clamp(22px,2.6vw,36px)", ...style }}>
      <EdRule weight="thick" style={{ marginBottom: 11 }} />
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 24, flexWrap: "wrap" }}>
        <MicroText size="sm" weight={600}>{label}</MicroText>
        {right || (count != null && <MicroText size="xs" tone="ghost">{String(count).padStart(2, "0")}</MicroText>)}
      </div>
      {children}
    </div>
  );
}

/* A barra de folio — cabeçalho de página impressa. Aparece no topo da home e no
   topo de cada ficha, e é o que dá à navegação a sensação de estar dentro de
   uma edição numerada em vez de um site. */
function EdFolio({ left, mid, right, style }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 20, paddingBottom: 9, flexWrap: "wrap", ...style }}>
      <MicroText size="xs" weight={600}>{left}</MicroText>
      {mid && <MicroText size="xs" tone="ghost">{mid}</MicroText>}
      <MicroText size="xs" tone="dim">{right}</MicroText>
    </div>
  );
}

/* Grade de colunas com filete vertical entre elas. O filete é o que faz a
   página parecer composta e não empilhada — e some no mobile, onde uma coluna
   só não tem vizinho de quem se separar. */
function EdCols({ children, cols = 3, gap = "clamp(20px,2.4vw,38px)", min = 190, style }) {
  const kids = React.Children.toArray(children);
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(" + min + "px,1fr))", gap, alignItems: "start", ...style }}>
      {kids.map((k, i) => (
        <div key={i} className={i > 0 ? "ed-col" : undefined} style={{ minWidth: 0, paddingLeft: i > 0 ? "var(--ed-col-pad,0px)" : 0, borderLeft: i > 0 ? "var(--ed-col-rule,none)" : "none" }}>{k}</div>
      ))}
    </div>
  );
}

/* A ficha técnica: pares rótulo/valor em mono, separados por filete. É o
   aparelho fazendo o que sabe — e liberando a serif de ter que dar dados. */
function EdSpecs({ items, style }) {
  const list = items.filter(([, v]) => v);
  return (
    <dl style={{ margin: 0, display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,150px),1fr))", gap: 0, ...style }}>
      {list.map(([k, v], i) => (
        <div key={k} style={{ minWidth: 0, borderTop: "1px solid var(--rule)", padding: "10px 16px 12px 0", display: "flex", flexDirection: "column", gap: 6 }}>
          <MicroText size="xs" tone="ghost">{k}</MicroText>
          <MicroText size="sm" weight={600} style={{ whiteSpace: "normal", lineHeight: 1.4, textWrap: "pretty" }}>{v}</MicroText>
        </div>
      ))}
    </dl>
  );
}

/* Uma linha de índice. Número discreto, título em serif, entrega em mono. Sem
   fólio e sem indicador de peso: a página de origem no deck organiza o site por
   dentro, mas não é assunto de quem visita. */
function EdIndexRow({ f, n, go, dense }) {
  const [h, setH] = React.useState(false);
  return (
    <button onClick={() => go("projeto", f.slug)} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      className={f.uf}
      style={{ background: h ? "var(--state-hover)" : "none", border: "none", borderTop: "1px solid var(--rule)", padding: dense ? "14px 0" : "clamp(16px,1.8vw,24px) 0", cursor: "pointer", textAlign: "left", width: "100%", display: "grid", gridTemplateColumns: "2.2em minmax(0,1fr) minmax(0,0.85fr)", gap: "6px clamp(12px,1.6vw,26px)", alignItems: "baseline", color: "var(--text-primary)", transition: "background var(--dur-fast) var(--ease-mech)" }}>
      <MicroText size="xs" tone="ghost">{String(n).padStart(2, "0")}</MicroText>
      <span style={{ minWidth: 0, display: "flex", alignItems: "baseline", gap: 10, flexWrap: "wrap" }}>
        <EdHead as="span" level={dense ? "xs" : "sm"} weight={h ? 500 : 400} style={{ transition: "font-weight var(--dur-fast)" }}>{f.title}</EdHead>
        {f.subtitle && <span style={{ fontFamily: ED, fontSize: 13, fontStyle: "italic", fontWeight: 300, color: "var(--text-secondary)", letterSpacing: "var(--tr-editorial)" }}>{f.subtitle}</span>}
      </span>
      <MicroText size="xs" tone={h ? "dim" : "ghost"} style={{ whiteSpace: "normal", lineHeight: 1.42, textWrap: "pretty" }}>{f.entrega}</MicroText>
    </button>
  );
}

/* A linha do ARQUIVO, no fundo preto: barra de acento territorial e o título na
   fita — a feição do site antigo, que é a que funciona. A fita é rasterizada
   num cap fixo, então quem cabe só se sabe MEDINDO: o wrapper informa a largura
   real e o cap sai dela. Títulos de 39 caracteres e de 4 convivem na mesma
   coluna sem constante chutada. */
function EdTapeRow({ f, go }) {
  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(11, Math.min(34, (w - 2) / (0.42 * f.word.length))) : 20;
  return (
    <button onClick={() => go("projeto", f.slug)} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      className={f.uf}
      style={{ background: h ? "var(--state-hover)" : "none", border: "none", borderTop: "1px solid var(--rule)", padding: "clamp(16px,2vw,26px) 0", cursor: "pointer", textAlign: "left", width: "100%", display: "grid", gridTemplateColumns: "minmax(0,1.5fr) minmax(0,1.15fr) minmax(0,0.85fr)", gap: "20px clamp(14px,2vw,28px)", alignItems: "center", transition: "background var(--dur-fast) var(--ease-mech)" }}>
      <span style={{ display: "flex", alignItems: "center", gap: 16, minWidth: 0 }}>
        <i style={{ width: 6, height: 40, background: "var(--ink-accent)", display: "block", flex: "0 0 auto", transform: h ? "scaleY(1.18)" : "none", transition: "transform var(--dur-fast) var(--ease-mech)" }} />
        <span ref={wrap} style={{ minWidth: 0, flex: 1, overflow: "hidden" }}>
          <KinoTape ground="dark" cap={cap} text={f.word} />
        </span>
      </span>
      <MicroText size="sm" tone="dim" style={{ whiteSpace: "normal", display: "block", lineHeight: 1.45, textWrap: "pretty" }}>{f.entrega}</MicroText>
      <MicroText size="sm" tone={h ? undefined : "ghost"} style={{ whiteSpace: "normal", display: "block", lineHeight: 1.45, textWrap: "pretty" }}>{f.cat}</MicroText>
    </button>
  );
}

Object.assign(window, { ED, MONO, EdRule, EdKicker, EdHead, EdDek, EdBody, EdDropCap, EdCaption, EdSection, EdFolio, EdCols, EdSpecs, EdIndexRow, EdTapeRow, HEADS });
