// Kinō desktop chrome — vertical spine, Roman numerals, marginalia
// Renders only on >=1100px viewports. Hidden on tablet/mobile.

const { useEffect, useState, useRef } = React;

// ---------- Vertical spine (left rail) ----------
function Spine({ accent }) {
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      setProgress(max > 0 ? Math.min(1, Math.max(0, h.scrollTop / max)) : 0);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <aside
      aria-hidden
      className="kino-spine"
      style={{
        position: "fixed", left: 0, top: 0, bottom: 0, width: 72,
        zIndex: 2, pointerEvents: "none",
        display: "flex", flexDirection: "column",
        alignItems: "center", justifyContent: "space-between",
        padding: "32px 0 32px",
      }}
    >
      {/* Top spacer (was glyph; removed for cleaner spine) */}
      <div style={{ height: 28 }} />

      {/* Middle: vertical wordmark */}
      <div style={{
        writingMode: "vertical-rl", transform: "rotate(180deg)",
        fontFamily: '"Cormorant Garamond", serif', fontWeight: 400,
        fontSize: 13, letterSpacing: "0.46em", textTransform: "uppercase",
        color: "rgba(28,37,33,0.55)",
      }}>
        KINŌ — A QUIETER BEGINNING
      </div>

      {/* Bottom: progress macron + index */}
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
        <div style={{
          width: 1, height: 120, background: "rgba(28,37,33,0.18)", position: "relative",
        }}>
          <div style={{
            position: "absolute", left: -1, top: 0, width: 3, height: `${progress * 100}%`,
            background: accent, transition: "height 120ms linear", borderRadius: 3,
          }} />
        </div>
        <div style={{
          fontFamily: '"Cormorant Garamond", serif', fontStyle: "italic",
          fontSize: 11, letterSpacing: "0.18em",
          color: "rgba(28,37,33,0.55)",
        }}>
          {String(Math.round(progress * 100)).padStart(2, "0")}
        </div>
      </div>
    </aside>
  );
}

// ---------- Right rail: marginalia + Roman section markers ----------
// Pinned absolutely to the page, anchored by data-margin-anchor attributes.
function Marginalia({ accent }) {
  const [items, setItems] = useState([]);

  useEffect(() => {
    const recalc = () => {
      const anchors = document.querySelectorAll("[data-margin-anchor]");
      const out = [];
      anchors.forEach((el) => {
        const rect = el.getBoundingClientRect();
        const top = rect.top + window.scrollY;
        out.push({
          top,
          numeral: el.getAttribute("data-numeral"),
          note: el.getAttribute("data-note"),
          kicker: el.getAttribute("data-kicker"),
          dark: el.getAttribute("data-dark") === "true",
        });
      });
      setItems(out);
    };
    recalc();
    const ro = new ResizeObserver(recalc);
    ro.observe(document.body);
    window.addEventListener("resize", recalc);
    // also recalc after fonts load
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(recalc);
    const t = setTimeout(recalc, 600);
    return () => {
      ro.disconnect();
      window.removeEventListener("resize", recalc);
      clearTimeout(t);
    };
  }, []);

  return (
    <aside
      aria-hidden
      className="kino-margin"
      style={{
        position: "absolute", top: 0, right: 0, width: 0,
        zIndex: 2, pointerEvents: "none",
      }}
    >
      {items.map((it, i) => (
        <div key={i} style={{
          position: "absolute", top: it.top, right: -260, width: 220,
          display: "flex", flexDirection: "column", gap: 10,
        }}>
          {it.numeral && (
            <div style={{
              fontFamily: '"Cormorant Garamond", serif', fontWeight: 400,
              fontSize: 96, lineHeight: 0.9,
              color: "transparent",
              WebkitTextStroke: `1px ${it.dark ? "rgba(247,244,237,0.32)" : "rgba(28,37,33,0.22)"}`,
              letterSpacing: "0.02em",
              marginBottom: 6,
            }}>
              {it.numeral}
            </div>
          )}
          {it.kicker && (
            <div style={{
              fontFamily: "Inter, sans-serif", fontSize: 10, fontWeight: 500,
              letterSpacing: "0.32em", textTransform: "uppercase",
              color: it.dark ? "rgba(247,244,237,0.55)" : "rgba(28,37,33,0.5)",
              display: "flex", alignItems: "center", gap: 10,
            }}>
              <span style={{
                width: 14, height: 1,
                background: accent, opacity: 0.9,
              }} />
              {it.kicker}
            </div>
          )}
          {it.note && (
            <div style={{
              fontFamily: '"Cormorant Garamond", serif', fontStyle: "italic",
              fontWeight: 400, fontSize: 14, lineHeight: 1.45,
              color: it.dark ? "rgba(247,244,237,0.65)" : "rgba(28,37,33,0.55)",
              letterSpacing: "0.005em",
              maxWidth: 200,
            }}>
              {it.note}
            </div>
          )}
        </div>
      ))}
    </aside>
  );
}

// ---------- Left-margin pull-quotes (sparse, paired with right marginalia) ----------
function LeftMargin({ accent }) {
  const [items, setItems] = useState([]);

  useEffect(() => {
    const recalc = () => {
      const anchors = document.querySelectorAll("[data-left-anchor]");
      const out = [];
      anchors.forEach((el) => {
        const rect = el.getBoundingClientRect();
        const top = rect.top + window.scrollY;
        out.push({
          top,
          fragment: el.getAttribute("data-fragment"),
          dark: el.getAttribute("data-dark") === "true",
          offset: parseInt(el.getAttribute("data-left-offset") || "0", 10),
        });
      });
      setItems(out);
    };
    recalc();
    const ro = new ResizeObserver(recalc);
    ro.observe(document.body);
    window.addEventListener("resize", recalc);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(recalc);
    const t = setTimeout(recalc, 600);
    return () => {
      ro.disconnect();
      window.removeEventListener("resize", recalc);
      clearTimeout(t);
    };
  }, []);

  return (
    <aside
      aria-hidden
      className="kino-leftmargin"
      style={{
        position: "absolute", top: 0, left: 0, width: 0,
        zIndex: 2, pointerEvents: "none",
      }}
    >
      {items.map((it, i) => (
        <div key={i} style={{
          position: "absolute", top: it.top + (it.offset || 0), left: -240, width: 200,
          display: "flex", alignItems: "flex-start", gap: 12,
        }}>
          <span style={{
            display: "inline-block", width: 18, height: 1,
            background: accent, opacity: 0.9, marginTop: 12,
          }} />
          <div style={{
            fontFamily: '"Cormorant Garamond", serif', fontStyle: "italic",
            fontWeight: 400, fontSize: 13, lineHeight: 1.5,
            color: it.dark ? "rgba(247,244,237,0.6)" : "rgba(28,37,33,0.5)",
            letterSpacing: "0.01em",
          }}>
            {it.fragment}
          </div>
        </div>
      ))}
    </aside>
  );
}

// ---------- Standalone scroll progress bar (always visible) ----------
function ScrollProgress({ accent }) {
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      setProgress(max > 0 ? Math.min(1, Math.max(0, h.scrollTop / max)) : 0);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <div
      aria-hidden
      style={{
        position: "fixed", top: 0, left: 0, right: 0, height: 2,
        zIndex: 100, pointerEvents: "none",
        background: "rgba(28,37,33,0.08)",
      }}
    >
      <div style={{
        height: "100%", width: `${progress * 100}%`,
        background: accent,
        transition: "width 100ms linear",
        borderRadius: "0 2px 2px 0",
      }} />
    </div>
  );
}

Object.assign(window, { Spine, Marginalia, LeftMargin, ScrollProgress });
