/* DevLog — single combined section (section 03).
 *
 * Replaces the old "git history" + "blog cards" split. Left panel is a
 * terminal that types out one post at a time (date + tag header, title,
 * excerpt, "read full post →" link), then cycles to the next. Right panel
 * lists every post as a quick link, plus the current tool stack below.
 *
 * Source: `assets/data/blog-posts.json`, baked by
 * `scripts/bake-blog-posts.cjs` from the RTD site's `content/blog/` folder.
 */

const POSTS_FALLBACK = [
  {
    slug: "fallback",
    date: "—",
    title: "blog posts not yet baked",
    tag: "craft",
    excerpt: "run scripts/bake-blog-posts.cjs to pull posts from the RTD site folder.",
    url: "#",
    read: "—",
  },
];

const TOOLS = ["Godot 4.4", "Aseprite", "GitHub", "Notion", "Cursor", "Claude Code"];

const POST_TAG_COLOR = {
  design:   "var(--ss-mint)",
  craft:    "var(--ss-pink)",
  personal: "var(--ss-pink)",
};

function composeBlock(post) {
  const tag = (post.tag || "log").toLowerCase();
  const date = post.date || "—";
  // Lowercase title in the terminal, brand voice. Excerpt as-authored.
  return [
    `─ ${date}  ·  ${tag}`,
    "",
    `> ${(post.title || "").toLowerCase()}`,
    "",
    post.excerpt || "",
  ].join("\n");
}

function DevLog({ speed = 26 }) {
  const [posts, setPosts] = React.useState(POSTS_FALLBACK);
  const [cursor, setCursor] = React.useState(0);
  const [typed, setTyped] = React.useState("");
  const [phase, setPhase] = React.useState("type"); // type | done
  const [cursorOn, setCursorOn] = React.useState(true);

  // Load real posts
  React.useEffect(() => {
    fetch("assets/data/blog-posts.json")
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (data && Array.isArray(data.posts) && data.posts.length) {
          setPosts(data.posts);
          setCursor(0);
        }
      })
      .catch(() => {});
  }, []);

  // Type out the active post, then pause + advance
  React.useEffect(() => {
    if (!posts.length) return;
    const post = posts[cursor];
    if (!post) return;
    const full = composeBlock(post);
    let alive = true;
    let charIdx = 0;
    let advanceTimer;

    setPhase("type");
    setTyped("");

    const tickInterval = setInterval(() => {
      if (!alive) return;
      charIdx += 2;
      if (charIdx >= full.length) {
        setTyped(full);
        setPhase("done");
        clearInterval(tickInterval);
        advanceTimer = setTimeout(() => {
          if (alive) setCursor(c => (c + 1) % posts.length);
        }, 5500);
      } else {
        setTyped(full.slice(0, charIdx));
      }
    }, 1000 / speed);

    return () => {
      alive = false;
      clearInterval(tickInterval);
      clearTimeout(advanceTimer);
    };
  }, [cursor, posts, speed]);

  // Blinking cursor
  React.useEffect(() => {
    const id = setInterval(() => setCursorOn(c => !c), 500);
    return () => clearInterval(id);
  }, []);

  const currentPost = posts[cursor] || posts[0];

  return (
    <section id="log" style={{ marginBottom: 64 }}>
      <div className="section-head">
        <span className="num">03</span>
        <span className="label">dev log</span>
        <span className="rule" style={{
          height: 0, borderBottom: "1px dashed color-mix(in oklab, var(--ss-mulberry) 35%, transparent)"
        }}/>
        <span className="label" style={{ color: "var(--ss-mulberry)" }}>
          writing from the workshop
        </span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 24 }} className="log-grid">
        {/* Left: typing terminal — whole card is a link to the current post.
            Same-tab nav now that posts live on this site. */}
        <a href={currentPost ? currentPost.url : "#"}
           style={{
             textDecoration: "none",
             color: "inherit",
             display: "block",
           }}>
          <div className="terminal-bar">
            <span className="dot dot-pink"/><span className="dot"/><span className="dot dot-mint"/>
            <span style={{ marginLeft: 8 }}>~/skipstone/log · cat *.md</span>
            <span style={{ marginLeft: "auto", opacity: 0.7 }}>tty.alex@kapiti</span>
          </div>
          <div className="terminal" style={{ minHeight: 340 }}>
            <div style={{ color: "var(--ss-bone)", opacity: 0.55, marginBottom: 10 }}>
              # post {cursor + 1} of {posts.length}
            </div>
            <pre style={{
              margin: 0,
              padding: 0,
              fontFamily: "inherit",
              fontSize: "inherit",
              lineHeight: "inherit",
              whiteSpace: "pre-wrap",
              wordBreak: "break-word",
              color: "var(--ss-bone)",
              background: "transparent",
            }}>{typed}<span style={{ color: "var(--ss-mint)", opacity: cursorOn ? 1 : 0 }}>▮</span></pre>
            {phase === "done" && (
              <div style={{
                marginTop: 16,
                color: "var(--ss-mint)",
                fontFamily: "inherit",
              }}>
                → read full post
              </div>
            )}
          </div>
        </a>

        {/* Right: all posts list + tools */}
        <aside style={{
          border: "1.5px solid var(--ss-mulberry)",
          background: "var(--ss-bone-warm)",
          boxShadow: "2px 2px 0 var(--ss-mulberry)",
          padding: "18px 20px",
          display: "flex",
          flexDirection: "column",
          gap: 14,
        }}>
          <div>
            <div className="eyebrow pixel-text" style={{ marginBottom: 10 }}>
              all posts
            </div>
            <ol style={{ listStyle: "none", padding: 0, margin: 0 }}>
              {posts.map((p, i) => (
                <PostLink key={p.slug || p.date}
                          post={p}
                          active={i === cursor}/>
              ))}
            </ol>
          </div>

          <hr style={{
            border: 0,
            borderTop: "1px dashed color-mix(in oklab, var(--ss-mulberry) 35%, transparent)",
            margin: "4px 0",
          }}/>

          <div>
            <div className="eyebrow pixel-text" style={{ marginBottom: 8 }}>
              tools i'm using
            </div>
            <ToolList/>
          </div>
        </aside>
      </div>
    </section>
  );
}

function PostLink({ post, active }) {
  const [hover, setHover] = React.useState(false);
  const tagColor = POST_TAG_COLOR[post.tag] || "var(--ss-mulberry)";
  return (
    <li style={{
      borderLeft: active
        ? "2px solid var(--ss-mint)"
        : (hover ? "2px solid var(--ss-mulberry)" : "2px solid transparent"),
      paddingLeft: 8,
      marginBottom: 6,
      transition: "border-color 120ms ease",
    }}>
      <a href={post.url}
         onMouseEnter={() => setHover(true)}
         onMouseLeave={() => setHover(false)}
         className="pixel-text"
         style={{
           display: "block",
           textDecoration: "none",
           color: "var(--ss-navy)",
           fontFamily: "basis33, monospace",
           fontSize: 15,
           lineHeight: 1.25,
         }}>
        <div style={{
          fontSize: 11,
          letterSpacing: "0.14em",
          textTransform: "uppercase",
          color: "var(--ss-mulberry)",
          marginBottom: 1,
          display: "flex",
          gap: 8,
          alignItems: "center",
        }}>
          <span>{post.date}</span>
          <span style={{
            width: 5, height: 5,
            background: tagColor,
            display: "inline-block",
          }}/>
          <span style={{ opacity: 0.8 }}>{(post.tag || "").toLowerCase()}</span>
        </div>
        <div style={{
          color: active ? "var(--ss-mulberry)" : "var(--ss-navy)",
          fontWeight: active ? 600 : 400,
        }}>{(post.title || "").toLowerCase()}</div>
      </a>
    </li>
  );
}

function ToolList() {
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }} className="pixel-text">
      {TOOLS.map(t => (
        <span key={t} style={{
          fontFamily: "basis33, monospace",
          fontSize: 13,
          padding: "3px 8px 1px",
          border: "1px solid var(--ss-mulberry)",
          background: "var(--ss-bone)",
          color: "var(--ss-mulberry)",
          letterSpacing: "0.04em",
        }}>{t}</span>
      ))}
    </div>
  );
}

window.DevLog = DevLog;
