// Karavi Studio · Journal (blog index) + Article (single post) — Sanity-driven

/* ── Journal index ─────────────────────────────────────────────────────────── */
const Journal = ({ goto }) => {
  const content = useContent();
  const blog = content?.blog || {};
  const posts = blog.posts || [];
  const [hero, ...rest] = posts;

  return (
    <main>
      <Section style={{ paddingTop: 72, paddingBottom: 8, borderBottom: "1px solid var(--line-soft)" }}>
        <Reveal><Eyebrow>{blog.indexEyebrow || "The Journal"}</Eyebrow></Reveal>
        <Reveal delay={0.1}>
          <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 300, fontSize: "clamp(40px, 6vw, 84px)", lineHeight: 1, letterSpacing: "-0.015em", margin: "10px 0 32px" }}>
            {blog.indexHeadline || "Notes on craft, slowly written."}
          </h1>
        </Reveal>
      </Section>

      {/* Featured (latest) post */}
      {hero && (
        <Section style={{ marginTop: 56 }}>
          <motion.a onClick={() => goto(`article:${hero.slug}`)} role="link" tabIndex={0}
            onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); goto(`article:${hero.slug}`); } }}
            whileHover="hovered" style={{ border: 0, cursor: "pointer", color: "inherit", display: "block" }}>
            <div className="k-split-2col" style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 40, alignItems: "center" }}>
              <motion.div className="k-card-img-wrap" variants={{ hovered: { y: -4, boxShadow: "var(--shadow-md)" }, initial: { y: 0 } }} initial="initial"
                style={{ aspectRatio: "4/3", borderRadius: 18, background: "var(--karavi-bone)", position: "relative" }}>
                <img className="k-card-img" src={cImg(hero.image)} alt={hero.title} loading="lazy"/>
              </motion.div>
              <div>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <Eyebrow>{hero.tag}</Eyebrow>
                  <span style={{ fontSize: 11, color: "var(--fg-3)", letterSpacing: ".05em" }}>{hero.date}</span>
                </div>
                <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 300, fontSize: "clamp(28px, 3.4vw, 44px)", lineHeight: 1.12, margin: "12px 0 14px", color: "var(--fg-display)" }}>{hero.title}</h2>
                <p style={{ fontSize: 16, lineHeight: 1.7, color: "var(--fg-1)", margin: 0, maxWidth: 460 }}>{hero.excerpt}</p>
                <div style={{ marginTop: 20 }}><Button variant="ghost">Read the entry →</Button></div>
              </div>
            </div>
          </motion.a>
        </Section>
      )}

      {/* Grid of the rest */}
      {rest.length > 0 && (
        <Section style={{ marginTop: 80, marginBottom: 32 }}>
          <Stagger className="k-grid-3">
            {rest.map(p => (
              <StaggerItem key={p.slug}>
                <motion.a onClick={() => goto(`article:${p.slug}`)} role="link" tabIndex={0}
                  onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); goto(`article:${p.slug}`); } }}
                  aria-label={`Read: ${p.title}`} whileHover="hovered" transition={{ type: "spring", stiffness: 220, damping: 24 }}
                  style={{ border: 0, cursor: "pointer", color: "inherit", display: "block" }}>
                  <motion.div className="k-card-img-wrap" variants={{ hovered: { y: -4, boxShadow: "var(--shadow-sm)" }, initial: { y: 0, boxShadow: "none" } }} initial="initial"
                    style={{ aspectRatio: "4/3", borderRadius: 14, background: "var(--karavi-bone)", position: "relative" }}>
                    <img className="k-card-img" src={cImg(p.image)} alt={p.title} loading="lazy"/>
                  </motion.div>
                  <div style={{ marginTop: 16, display: "flex", alignItems: "center", gap: 10 }}>
                    <Eyebrow>{p.tag}</Eyebrow>
                    <span style={{ fontSize: 11, color: "var(--fg-3)", letterSpacing: ".05em" }}>{p.date}</span>
                  </div>
                  <div style={{ marginTop: 8, fontFamily: "var(--font-display)", fontSize: 22, lineHeight: 1.2, color: "var(--fg-display)" }}>{p.title}</div>
                  {p.excerpt && <p style={{ marginTop: 8, fontSize: 14, lineHeight: 1.6, color: "var(--fg-2)" }}>{p.excerpt}</p>}
                </motion.a>
              </StaggerItem>
            ))}
          </Stagger>
        </Section>
      )}
    </main>
  );
};
window.Journal = Journal;

/* ── Article (single post) ─────────────────────────────────────────────────── */
const Article = ({ slug, goto }) => {
  const content = useContent();
  const posts = content?.blog?.posts || [];
  const post = posts.find(p => p.slug === slug);
  const heroRef = React.useRef(null);
  const { scrollYProgress } = useScroll({ target: heroRef, offset: ["start start", "end start"] });
  const heroBgY = useTransform(scrollYProgress, [0, 1], ["0%", "18%"]);

  if (!post) {
    return (
      <main>
        <Section style={{ paddingTop: 120, paddingBottom: 120, textAlign: "center" }}>
          <Eyebrow style={{ justifyContent: "center", display: "flex" }}>Not found</Eyebrow>
          <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 300, fontSize: "clamp(32px,4vw,52px)", margin: "12px 0 28px" }}>This entry has moved.</h1>
          <Button onClick={() => goto("journal")} magnetic>Back to the journal →</Button>
        </Section>
      </main>
    );
  }

  // Body may be an array of strings (defaults) or Sanity portable text blocks.
  const paragraphs = Array.isArray(post.body)
    ? post.body.map(b => (typeof b === "string" ? b : (b.children || []).map(ch => ch.text).join(""))).filter(Boolean)
    : [];

  return (
    <main>
      {/* Hero */}
      <Section bleed>
        <div ref={heroRef} style={{ position: "relative", minHeight: "62vh", overflow: "hidden" }}>
          <motion.div style={{ position: "absolute", inset: "-8% 0", background: `url(${cImg(post.image)}) center/cover no-repeat`, y: heroBgY }}/>
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, transparent 30%, var(--overlay-warm))" }}/>
          <motion.div initial={{ opacity: 0, y: 28 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.85, ease: [0.22, 0.61, 0.36, 1], delay: 0.15 }}
            className="k-hero-text" style={{ position: "absolute", left: 0, right: 0, bottom: 0, color: "var(--karavi-cream)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
              <Eyebrow color="var(--cream-70)">{post.tag}</Eyebrow>
              <span style={{ fontSize: 11, color: "var(--cream-65)", letterSpacing: ".05em" }}>{post.date}</span>
            </div>
            <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 300, fontSize: "clamp(34px, 5.2vw, 76px)", lineHeight: 1.02, letterSpacing: "-0.02em", margin: 0, maxWidth: 900, color: "var(--karavi-cream)" }}>
              {post.title}
            </h1>
          </motion.div>
        </div>
      </Section>

      {/* Body */}
      <Section style={{ maxWidth: 720, marginTop: 72 }}>
        {post.excerpt && (
          <Reveal>
            <p style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontWeight: 400, fontSize: "clamp(20px, 2.6vw, 30px)", lineHeight: 1.45, color: "var(--fg-display)", margin: "0 0 28px" }}>
              {post.excerpt}
            </p>
          </Reveal>
        )}
        {paragraphs.map((para, i) => (
          <Reveal key={i} delay={0.05 * i}>
            <p style={{ fontSize: 17, lineHeight: 1.78, color: "var(--fg-1)", marginTop: i === 0 ? 0 : 20 }}>{para}</p>
          </Reveal>
        ))}
      </Section>

      <Section style={{ marginTop: 80, marginBottom: 40, textAlign: "center" }}>
        <KilimDivider/>
        <Reveal delay={0.1}>
          <div style={{ marginTop: 40 }}><Button variant="ghost" onClick={() => goto("journal")}>← All journal entries</Button></div>
        </Reveal>
      </Section>
    </main>
  );
};
window.Article = Article;

/* ── Generic content page (About / Sustainability / Craftsmanship) ─────────── */
const ContentPage = ({ slug, goto }) => {
  const content = useContent();
  const p = (content?.pages || {})[slug];
  const heroRef = React.useRef(null);
  const { scrollYProgress } = useScroll({ target: heroRef, offset: ["start start", "end start"] });
  const heroBgY = useTransform(scrollYProgress, [0, 1], ["0%", "18%"]);

  if (!p) {
    return (
      <main>
        <Section style={{ paddingTop: 120, paddingBottom: 120, textAlign: "center" }}>
          <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 300, fontSize: "clamp(32px,4vw,52px)", margin: "12px 0 28px" }}>Page not found.</h1>
          <Button onClick={() => goto("home")} magnetic>Back home →</Button>
        </Section>
      </main>
    );
  }

  return (
    <main>
      <Section bleed>
        <div ref={heroRef} style={{ position: "relative", minHeight: "58vh", overflow: "hidden" }}>
          <motion.div style={{ position: "absolute", inset: "-8% 0", background: `url(${cImg(p.heroImage)}) center/cover no-repeat`, y: heroBgY }}/>
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, transparent 28%, var(--overlay-warm))" }}/>
          <motion.div initial={{ opacity: 0, y: 28 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.85, ease: [0.22, 0.61, 0.36, 1], delay: 0.15 }}
            className="k-hero-text" style={{ position: "absolute", left: 0, right: 0, bottom: 0, color: "var(--karavi-cream)" }}>
            <Eyebrow color="var(--cream-70)" style={{ marginBottom: 14 }}>{p.eyebrow}</Eyebrow>
            <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 300, fontSize: "clamp(40px, 6.5vw, 92px)", lineHeight: 1, letterSpacing: "-0.02em", margin: 0, color: "var(--karavi-cream)" }}>{p.title}</h1>
          </motion.div>
        </div>
      </Section>

      <Section style={{ maxWidth: 760, marginTop: 88 }}>
        <Reveal>
          <p style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontWeight: 400, fontSize: "clamp(22px, 2.8vw, 34px)", lineHeight: 1.42, color: "var(--fg-display)", margin: 0 }}>
            {p.intro}
          </p>
        </Reveal>
      </Section>

      <Section style={{ marginTop: 72, marginBottom: 32 }}>
        <Stagger className="k-grid-2" style={{ gap: 48, rowGap: 56 }} staggerChildren={0.1}>
          {(p.blocks || []).map((b, i) => (
            <StaggerItem key={i}>
              <div>
                <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 400, fontSize: "clamp(22px, 2.6vw, 30px)", margin: 0, color: "var(--fg-display)" }}>{b.heading}</h3>
                <p style={{ marginTop: 12, fontSize: 15, lineHeight: 1.72, color: "var(--fg-1)" }}>{b.body}</p>
              </div>
            </StaggerItem>
          ))}
        </Stagger>
      </Section>

      <Section style={{ marginTop: 56, marginBottom: 40, textAlign: "center" }}>
        <KilimDivider/>
        <Reveal delay={0.1}>
          <div style={{ marginTop: 40 }}><Button onClick={() => goto("shop")} magnetic>Shop the studio →</Button></div>
        </Reveal>
      </Section>
    </main>
  );
};
window.ContentPage = ContentPage;
