const { useState, useEffect, useRef } = React;

const GHOST_URL = "https://blog.intuition2action.net";
const GHOST_KEY = "1f723e541a1d5b048b7185acd0";
const POSTS_PER_PAGE = 15;

async function fetchGhostPosts(opts) {
  var filter = (opts && opts.filter) || "";
  var page   = (opts && opts.page)   || 1;
  var filterStr = "";
  if (filter) {
    var tags = filter.split(",").map(function(t) { return t.trim(); }).filter(Boolean);
    filterStr = "&filter=" + tags.map(function(t) { return "tag:" + t; }).join(",");
  }
  var url = GHOST_URL + "/ghost/api/content/posts/?key=" + GHOST_KEY +
    "&limit=" + POSTS_PER_PAGE + "&page=" + page +
    "&include=tags&fields=id,title,slug,excerpt,published_at,url,reading_time,feature_image,html" + filterStr;
  var res = await fetch(url);
  if (!res.ok) throw new Error("Ghost API error: " + res.status);
  return res.json();
}

async function fetchAllPosts() {
  var url = GHOST_URL + "/ghost/api/content/posts/?key=" + GHOST_KEY +
    "&limit=all&include=tags&fields=id,title,slug,excerpt,published_at,url,reading_time,feature_image,html";
  var res = await fetch(url);
  if (!res.ok) throw new Error("Ghost API error: " + res.status);
  return res.json();
}

// ──────────────────────── Parse source links from post HTML ────────────────────────
function parseSourceLinks(html) {
  if (!html) return null;
  var lower = html.toLowerCase();
  if (lower.indexOf("originally published on") === -1 &&
      lower.indexOf("originally-published-on") === -1) return null;

  var links = { x: null, linkedin: null, substack: null };
  var found = false;

  // Extract all hrefs from the HTML
  var hrefRe = /href=["']([^"']+)["']/gi;
  var match;
  while ((match = hrefRe.exec(html)) !== null) {
    var href = match[1];
    if (/x\.com\/vedakonduru\/status/i.test(href) && !links.x) {
      links.x = href; found = true;
    } else if (/linkedin\.com\/posts\//i.test(href) && !links.linkedin) {
      links.linkedin = href; found = true;
    } else if (/substack\.com/i.test(href) && !links.substack) {
      links.substack = href; found = true;
    }
  }
  return found ? links : null;
}

function detectSource(tags) {
  if (!tags || !tags.length) return "native";
  var slugs = tags.map(function(t) { return t.slug; });
  if (slugs.indexOf("linkedin-article") !== -1 || slugs.indexOf("linkedin-post") !== -1) return "linkedin";
  if (slugs.indexOf("x-article") !== -1) return "x";
  if (slugs.indexOf("newsletter") !== -1) return "substack";
  return "native";
}

function cleanExcerpt(raw, maxLen) {
  if (!raw) return "";
  maxLen = maxLen || 180;
  var text = raw
    .replace(/Originally published on [A-Za-z ()]+/g, "")
    .replace(/^\s*[\u00b7\u2022\-\.]\s*/, "")
    .replace(/^(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{1,2},\s+\d{4}\s*/i, "")
    .trim();
  // Truncate at first social handle — strips embedded Bluesky/X post noise
  var handleIdx = text.search(/@[A-Za-z0-9_]+\./);
  if (handleIdx > 20) text = text.slice(0, handleIdx).trim().replace(/[.,\s]+$/, "") + "\u2026";
  if (text.length <= maxLen) return text;
  var cut = text.slice(0, maxLen);
  var lastSpace = cut.lastIndexOf(" ");
  return (lastSpace > 0 ? cut.slice(0, lastSpace) : cut) + "\u2026";
}

// ──────────────────────── Search icon ────────────────────────
function SearchIcon({ size, color }) {
  size = size || 18;
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color || "currentColor"}
      strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
      <circle cx="11" cy="11" r="7" />
      <line x1="21" y1="21" x2="16.65" y2="16.65" />
    </svg>
  );
}

// ──────────────────────── Compass Logo SVG ────────────────────────
function CompassMark({ size }) {
  size = size || 32;
  return (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width={size} height={size}
      role="img" aria-label="i2A compass mark" style={{ flexShrink: 0, borderRadius: 8 }}>
      <rect width="512" height="512" rx="112" fill="#17274C"/>
      <g transform="translate(76 76) scale(3.0)">
        <g fill="#FFFFFF" opacity="0.30">
          <path d="M60 60 L56.46 56.46 L76.97 43.03 L63.54 63.54 Z"/>
          <path d="M60 60 L63.54 56.46 L76.97 76.97 L56.46 63.54 Z"/>
          <path d="M60 60 L63.54 63.54 L43.03 76.97 L56.46 56.46 Z"/>
          <path d="M60 60 L56.46 63.54 L43.03 43.03 L63.54 56.46 Z"/>
        </g>
        <g fill="#FFFFFF">
          <path d="M60 60 L53 60 L60 18 L67 60 Z"/>
          <path d="M60 60 L67 60 L60 102 L53 60 Z"/>
          <path d="M60 60 L60 67 L18 60 L60 53 Z"/>
        </g>
        <path d="M60 60 L60 53 L98 60 L60 67 Z" fill="#F0742A"/>
        <path d="M96 52 L111 60 L96 68 Z" fill="#F0742A"/>
        <circle cx="60" cy="60" r="9" fill="#17274C"/>
        <circle cx="60" cy="60" r="9.8" fill="none" stroke="#FBF8F2" strokeWidth="1.4" opacity="0.55"/>
        <circle cx="60" cy="60" r="6" fill="#F0742A"/>
      </g>
    </svg>
  );
}

// ──────────────────────── Helpers ────────────────────────
function useIsMobile() {
  var [mobile, setMobile] = useState(window.innerWidth <= 768);
  useEffect(function() {
    function onResize() { setMobile(window.innerWidth <= 768); }
    window.addEventListener("resize", onResize);
    return function() { window.removeEventListener("resize", onResize); };
  }, []);
  return mobile;
}

function fmtDate(iso) {
  return new Date(iso).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

// ──────────────────────── Source Badge ────────────────────────
function SrcBadge({ source, href }) {
  var chips = {
    linkedin: { label: "IN \u00b7 LINKEDIN", bg: "#ECF1FB", color: "#2A5BB8", border: "#C5D3F0" },
    x:        { label: "X \u00b7 POST",      bg: "#F4F4F2", color: "#17274C", border: "#E0E0DC" },
    substack: { label: "S \u00b7 SUBSTACK",  bg: "#FBE4D2", color: "#E0651C", border: "#F0C8A8" },
  };
  var chip = chips[source];
  if (!chip) return null;
  var style = { fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.12em",
    padding: "2px 8px", borderRadius: 2, display: "inline-flex", alignItems: "center",
    background: chip.bg, color: chip.color, border: "1px solid " + chip.border,
    textDecoration: "none", cursor: href ? "pointer" : "default" };
  if (href) {
    return (
      <a href={href} target="_blank" rel="noreferrer"
        onClick={function(e) { e.stopPropagation(); }}
        style={style}>{chip.label}</a>
    );
  }
  return (
    <span onClick={function(e) { e.stopPropagation(); }}
      style={style}>{chip.label}</span>
  );
}

// ──────────────────────── Source Links Row ────────────────────────
function SourceLinksRow({ sourceLinks, source }) {
  // sourceLinks = { x: url|null, linkedin: url|null, substack: url|null } or null
  // source = tag-detected source ('x', 'linkedin', 'substack', 'native')

  var badges = [];

  if (sourceLinks) {
    // Use parsed links from post HTML — most accurate, fully clickable
    if (sourceLinks.x)        badges.push(<SrcBadge key="x"        source="x"        href={sourceLinks.x} />);
    if (sourceLinks.linkedin) badges.push(<SrcBadge key="linkedin"  source="linkedin" href={sourceLinks.linkedin} />);
    if (sourceLinks.substack) badges.push(<SrcBadge key="substack"  source="substack" href={sourceLinks.substack} />);
  } else if (source && source !== "native") {
    // Fallback: show tag-detected badge without a link
    badges.push(<SrcBadge key={source} source={source} href={null} />);
  }

  if (!badges.length) return null;

  return (
    <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 10 }}>
      {badges}
    </div>
  );
}

// ──────────────────────── Subscribe Form ────────────────────────
function SubscribeForm() {
  var [firstName, setFirstName] = useState("");
  var [lastName,  setLastName]  = useState("");
  var [email,   setEmail]   = useState("");
  var [status,  setStatus]  = useState("idle");
  var [message, setMessage] = useState("");

  var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

  async function handleJoin(e) {
    e.preventDefault();
    if (!EMAIL_RE.test(email.trim())) {
      setStatus("error");
      setMessage("Please enter a valid email address.");
      return;
    }
    setStatus("loading");
    try {
      const res = await fetch("/api/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: email, firstName: firstName, lastName: lastName })
      });
      const data = await res.json().catch(function() { return {}; });
      if (res.ok && data.success) {
        setStatus("success");
        if (data.alreadySubscribed) {
          setMessage("Looks like you're already subscribed \u2014 thanks for being here!");
        } else {
          setMessage("You are in! Welcome aboard.");
        }
        setEmail(""); setFirstName(""); setLastName("");
      } else {
        setStatus("error");
        setMessage("Something went wrong. Please try again.");
      }
    } catch (err) {
      setStatus("error");
      setMessage("Something went wrong. Please try again.");
    }
  }

  if (status === "success") {
    return (
      <div style={{ fontFamily: "var(--serif)", fontSize: 14, color: "var(--ink-2)", lineHeight: 1.5, padding: "10px 0" }}>
        {message}
      </div>
    );
  }

  var fieldStyle = { fontSize: 13, padding: "8px 10px", border: "1px solid var(--rule)",
    borderRadius: 3, background: "var(--paper)", fontFamily: "var(--sans)", color: "var(--ink)",
    outline: "none" };

  return (
    <div>
      <div style={{ fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.08em",
        textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 4 }}>
        Name (optional)
      </div>
      <div className="subscribe-row" style={{ display: "flex", gap: 6, marginBottom: 6 }}>
        <input type="text" placeholder="First name" value={firstName}
          onChange={function(e) { setFirstName(e.target.value); setStatus("idle"); }}
          style={{ ...fieldStyle, flex: 1, minWidth: 0 }}
          disabled={status === "loading"} />
        <input type="text" placeholder="Last name" value={lastName}
          onChange={function(e) { setLastName(e.target.value); setStatus("idle"); }}
          style={{ ...fieldStyle, flex: 1, minWidth: 0 }}
          disabled={status === "loading"} />
      </div>
      <div className="subscribe-row" style={{ display: "flex", gap: 6 }}>
        <input type="email" placeholder="your@email" value={email}
          onChange={function(e) { setEmail(e.target.value); setStatus("idle"); }}
          onKeyDown={function(e) { if (e.key === "Enter") handleJoin(e); }}
          style={{ ...fieldStyle, flex: 1 }}
          disabled={status === "loading"} />
        <button onClick={handleJoin} disabled={status === "loading"}
          style={{ background: "var(--ink)", color: "var(--paper)", border: 0,
            padding: "8px 14px", borderRadius: 3, fontFamily: "var(--sans)",
            fontSize: 13, cursor: status === "loading" ? "default" : "pointer",
            opacity: status === "loading" ? 0.7 : 1 }}>
          Join
        </button>
      </div>
      {status === "error" && (
        <p style={{ fontFamily: "var(--mono)", fontSize: 10.5, color: "var(--accent)", marginTop: 6, letterSpacing: "0.04em" }}>
          {message}
        </p>
      )}
      {status === "idle" && (
        <p style={{ fontFamily: "var(--mono)", fontSize: 10.5, color: "var(--ink-3)", marginTop: 8, letterSpacing: "0.04em" }}>
          One letter a fortnight. No noise.
        </p>
      )}
    </div>
  );
}

// ──────────────────────── Nav items ────────────────────────
var NAV_ITEMS = [
  { name: "writing",  label: "Writing"  },
  { name: "about",    label: "About"    },
];

// ──────────────────────── App ────────────────────────
function App() {
  var [route, setRoute] = useState({ name: "writing" });
  function go(r) { setRoute(r); window.scrollTo({ top: 0, behavior: "smooth" }); }
  return (
    <div>
      <Header route={route} go={go} />
      <main>
        {route.name === "writing"  && <WritingPage go={go} />}
        {route.name === "reading"  && <ReadingPage />}
        {route.name === "projects" && <ProjectsPage />}
        {route.name === "about"    && <AboutPage go={go} />}
        {route.name === "post"     && <PostPage post={route.post} go={go} />}
        {route.name === "search"   && <SearchPage go={go} />}
      </main>
      <Footer go={go} />
    </div>
  );
}

// ──────────────────────── Header ────────────────────────
function Header({ route, go }) {
  var isMobile = useIsMobile();
  var [menuOpen, setMenuOpen] = useState(false);
  var menuRef = useRef(null);

  useEffect(function() {
    function handleClick(e) {
      if (menuRef.current && !menuRef.current.contains(e.target)) setMenuOpen(false);
    }
    document.addEventListener("mousedown", handleClick);
    return function() { document.removeEventListener("mousedown", handleClick); };
  }, []);

  function navTo(name) { go({ name: name }); setMenuOpen(false); }
  var activeRoute = route.name === "post" ? "writing" : route.name;

  return (
    <header style={{ borderBottom: "1px solid var(--rule)", background: "var(--paper)",
      position: "sticky", top: 0, zIndex: 100 }}>
      <div className="container" style={{ display: "flex", alignItems: "center",
        justifyContent: "space-between", paddingTop: isMobile ? 14 : 18, paddingBottom: isMobile ? 14 : 18 }}>

        {/* Logo */}
        <div onClick={() => navTo("writing")} style={{ cursor: "pointer", display: "flex", alignItems: "center", gap: 10 }}>
          <CompassMark size={isMobile ? 24 : 28} />
          <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
            <span style={{ fontFamily: "var(--serif)", fontWeight: 500, fontSize: isMobile ? 20 : 24,
              letterSpacing: "-0.02em", color: "var(--ink)" }}>Veda Konduru</span>
            {!isMobile && (
              <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.14em",
                textTransform: "uppercase", color: "var(--ink-3)" }}>The Mind Explorer</span>
            )}
          </div>
        </div>

        {/* Desktop nav */}
        {!isMobile && (
          <nav style={{ display: "flex", gap: 26, fontFamily: "var(--sans)", fontSize: 14, alignItems: "center" }}>
            {NAV_ITEMS.map(function(item) {
              var active = activeRoute === item.name;
              return (
                <button key={item.name} onClick={() => navTo(item.name)} style={{
                  background: "none", border: 0, padding: "0 0 2px", fontFamily: "inherit", fontSize: "inherit",
                  color: active ? "var(--ink)" : "var(--ink-2)",
                  borderBottom: active ? "1px solid var(--ink)" : "1px solid transparent",
                  cursor: "pointer", transition: "color 0.15s" }}>
                  {item.label}
                </button>
              );
            })}
            <button onClick={() => navTo("search")} aria-label="Search" style={{
              background: "none", border: 0, padding: "2px 0 0", cursor: "pointer",
              color: activeRoute === "search" ? "var(--accent)" : "var(--ink-2)",
              display: "flex", alignItems: "center" }}>
              <SearchIcon size={18} />
            </button>
          </nav>
        )}

        {/* Mobile: search + hamburger */}
        {isMobile && (
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <button onClick={() => navTo("search")} aria-label="Search" style={{
              background: "none", border: "1px solid var(--rule)", borderRadius: 6,
              padding: "7px 9px", cursor: "pointer",
              color: activeRoute === "search" ? "var(--accent)" : "var(--ink-2)",
              display: "flex", alignItems: "center" }}>
              <SearchIcon size={16} />
            </button>
            <div ref={menuRef} style={{ position: "relative" }}>
            <button onClick={() => setMenuOpen(!menuOpen)} style={{
              background: "none", border: "1px solid var(--rule)", borderRadius: 6,
              padding: "6px 10px", cursor: "pointer", fontFamily: "var(--sans)", fontSize: 13,
              color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 6 }}>
              {menuOpen ? "\u2715" : "\u2630"} Menu
            </button>
            {menuOpen && (
              <div style={{ position: "absolute", right: 0, top: "calc(100% + 8px)",
                background: "var(--paper)", border: "1px solid var(--rule)", borderRadius: 8,
                padding: "8px 0", minWidth: 180, boxShadow: "0 4px 20px rgba(0,0,0,0.08)", zIndex: 200 }}>
                {NAV_ITEMS.map(function(item) {
                  var active = activeRoute === item.name;
                  return (
                    <button key={item.name} onClick={() => navTo(item.name)} style={{
                      display: "block", width: "100%", textAlign: "left", padding: "10px 18px",
                      background: "none", border: 0, fontFamily: "var(--sans)", fontSize: 14,
                      color: active ? "var(--accent)" : "var(--ink-2)",
                      fontWeight: active ? 500 : 400, cursor: "pointer",
                      borderLeft: active ? "2px solid var(--accent)" : "2px solid transparent" }}>
                      {item.label}
                    </button>
                  );
                })}
              </div>
            )}
            </div>
          </div>
        )}
      </div>
    </header>
  );
}

// ──────────────────────── Skeleton ────────────────────────
function SkeletonCard() {
  var shimmer = { background: "linear-gradient(90deg,var(--rule-2) 25%,var(--paper-2) 50%,var(--rule-2) 75%)",
    backgroundSize: "200% 100%", animation: "shimmer 1.4s infinite", borderRadius: 3 };
  return (
    <div style={{ padding: "26px 0", borderBottom: "1px solid var(--rule-2)" }}>
      <div style={{ ...shimmer, height: 10, width: 200, marginBottom: 14 }} />
      <div style={{ ...shimmer, height: 26, width: "70%", marginBottom: 12 }} />
      <div style={{ ...shimmer, height: 16, width: "90%", marginBottom: 6 }} />
      <div style={{ ...shimmer, height: 16, width: "60%" }} />
    </div>
  );
}

// ──────────────────────── Writing Page ────────────────────────
function WritingPage({ go }) {
  var isMobile = useIsMobile();

  var SOURCE_FILTERS = [
    { id: "all",      label: "All writing",   ghost: "" },
    { id: "native",   label: "Written here",  ghost: "" },
    { id: "linkedin", label: "From LinkedIn", ghost: "linkedin-article,linkedin-post" },
    { id: "x",        label: "From X",        ghost: "x-article" },
    { id: "substack", label: "From Substack", ghost: "newsletter" },
  ];

  var NAV_TAGS = [
    { id: "all",           label: "All essays",                    ghost: "" },
    { id: "mental-models", label: "Mental Models & Frameworks",    ghost: "mental-models" },
    { id: "social-impact", label: "Real-Life Topics for Social Impact", ghost: "social-impact" },
    { id: "self-mastery",  label: "Self-Mastery",                  ghost: "self-mastery" },
    { id: "technology",    label: "Technology",                    ghost: "technology" },
    { id: "conversations",  label: "Conversations",                 ghost: "conversations" },
  ];

  var [activeTag,    setActiveTag]    = useState("all");
  var [activeSource, setActiveSource] = useState("all");
  var [posts,        setPosts]        = useState([]);
  var [loading,      setLoading]      = useState(true);
  var [error,        setError]        = useState(null);
  var [page,         setPage]         = useState(1);
  var [hasMore,      setHasMore]      = useState(false);
  var [loadingMore,  setLoadingMore]  = useState(false);

  var currentTag = NAV_TAGS.find(function(t) { return t.id === activeTag; }) || NAV_TAGS[0];
  var currentSrc = SOURCE_FILTERS.find(function(f) { return f.id === activeSource; }) || SOURCE_FILTERS[0];

  async function load(tagGhost, srcId, srcGhost, pageNum, append) {
    try {
      append ? setLoadingMore(true) : setLoading(true);
      var filter = tagGhost || srcGhost || "";
      var data = await fetchGhostPosts({ filter: filter, page: pageNum });
      var mapped = (data.posts || []).map(function(p) {
        return Object.assign({}, p, {
          source: detectSource(p.tags),
          date: new Date(p.published_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }),
          excerpt: cleanExcerpt(p.excerpt),
          minutes: p.reading_time,
          sourceLinks: parseSourceLinks(p.html),
        });
      });
      // Deduplicate by ID
      var seen = {};
      mapped = mapped.filter(function(p) {
        if (seen[p.id]) return false;
        seen[p.id] = true;
        return true;
      });
      var out = srcId === "native" ? mapped.filter(function(p) { return p.source === "native"; }) : mapped;
      setPosts(function(prev) { return append ? prev.concat(out) : out; });
      var pg = data.meta && data.meta.pagination;
      setHasMore(pg ? pg.page < pg.pages : false);
      setError(null);
    } catch(e) { setError(e.message); }
    finally { setLoading(false); setLoadingMore(false); }
  }

  useEffect(function() {
    setPage(1); setPosts([]);
    load(currentTag.ghost, currentSrc.id, currentSrc.ghost, 1, false);
  }, [activeTag, activeSource]);

  function loadMore() { var n = page + 1; setPage(n); load(currentTag.ghost, currentSrc.id, currentSrc.ghost, n, true); }

  return (
    <div className="container" style={{ padding: isMobile ? "32px 0 60px" : "56px 0 80px" }}>
      <div className="home-grid" style={{ display: isMobile ? "block" : "grid",
        gridTemplateColumns: "280px 1fr", gap: 56 }}>

        {/* Sidebar */}
        <aside className="home-sidebar" style={ isMobile
          ? { marginBottom: 32, paddingBottom: 24, borderBottom: "1px solid var(--rule)" }
          : { position: "sticky", top: 90, alignSelf: "start" }}>

          <p style={{ fontFamily: "var(--serif)", fontSize: 16, lineHeight: 1.65,
            color: "var(--ink-2)", margin: 0 }}>
            Former AI architect. Twenty years building systems for machines, now apprenticing to the one between my ears.
          </p>
          <a href="#" onClick={function(e) { e.preventDefault(); go({ name: "about" }); }}
            style={{ fontFamily: "var(--sans)", fontSize: 14, color: "var(--accent)",
              display: "inline-block", marginTop: 10, textDecoration: "none" }}>
            Read more about me &rarr;
          </a>

          <hr style={{ border: 0, borderTop: "1px solid var(--rule)", margin: "24px 0" }} />

          <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
            textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 12 }}>Topics</div>
          <div style={{ display: "flex", flexDirection: isMobile ? "row" : "column",
            flexWrap: "wrap", gap: isMobile ? 8 : 0 }}>
            {NAV_TAGS.map(function(t) {
              var active = activeTag === t.id;
              // Show NEW badge for Conversations if latest post is within 7 days
              var showNew = false;
              if (t.id === "conversations" && posts.length > 0) {
                var convPosts = posts.filter(function(p) { return p.tags && p.tags.some(function(tag) { return tag.slug === "conversations"; }); });
                if (convPosts.length > 0) {
                  var latest = new Date(convPosts[0].published_at);
                  var diff = (new Date() - latest) / (1000 * 60 * 60 * 24);
                  showNew = diff <= 7;
                }
              }
              return (
                <button key={t.id} onClick={function() { setActiveTag(t.id); setActiveSource("all"); }}
                  style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
                    padding: "7px 0", background: "none", border: 0, textAlign: "left",
                    fontFamily: "var(--sans)", fontSize: 14, width: "100%",
                    color: active ? "var(--ink)" : "var(--ink-2)",
                    fontWeight: active ? 500 : 400, cursor: "pointer",
                    borderLeft: isMobile ? "none" : (active ? "2px solid var(--accent)" : "2px solid transparent"),
                    paddingLeft: isMobile ? 0 : 8 }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
                    {t.label}
                    {showNew && (
                      <span style={{ fontFamily: "var(--mono)", fontSize: 14, fontWeight: 600,
                        color: "var(--accent)", lineHeight: 1 }}>*</span>
                    )}
                  </span>
                </button>
              );
            })}
          </div>

          <hr style={{ border: 0, borderTop: "1px solid var(--rule)", margin: "24px 0" }} />
          <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
            textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 12 }}>Newsletter</div>
          <SubscribeForm />
        </aside>

        {/* Main feed */}
        <section>
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between",
            marginBottom: 10, flexWrap: "wrap", gap: 8 }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
              textTransform: "uppercase", color: "var(--ink-3)" }}>
              Latest{!loading && (" \u00b7 " + posts.length + (hasMore ? "+" : "") + " essays")}
            </div>
            {!isMobile && (
              <div style={{ display: "flex", gap: 6 }}>
                {SOURCE_FILTERS.map(function(f) {
                  var active = activeSource === f.id;
                  return (
                    <button key={f.id} onClick={function() { setActiveSource(f.id); }}
                      style={{ fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.08em",
                        textTransform: "uppercase", padding: "3px 10px", borderRadius: 100,
                        border: "1px solid " + (active ? "var(--ink)" : "var(--rule)"),
                        background: active ? "var(--ink)" : "none",
                        color: active ? "var(--paper)" : "var(--ink-3)",
                        cursor: "pointer" }}>
                      {f.label}
                    </button>
                  );
                })}
              </div>
            )}
          </div>
          <hr style={{ border: 0, borderTop: "2px solid var(--ink)", marginBottom: 0 }} />

          {loading && [1,2,3,4].map(function(i) { return <SkeletonCard key={i} />; })}
          {error && (
            <div style={{ padding: "40px 0", fontFamily: "var(--serif)", color: "var(--ink-3)" }}>
              <p style={{ fontStyle: "italic" }}>Couldn't reach the blog right now.</p>
              <p style={{ fontSize: 13, fontFamily: "var(--mono)" }}>{error}</p>
            </div>
          )}
          {!loading && !error && posts.length === 0 && (
            <div style={{ padding: "40px 0", fontFamily: "var(--serif)", fontStyle: "italic",
              color: "var(--ink-3)" }}>Nothing here yet — but it's brewing.</div>
          )}
          {!loading && posts.map(function(p) { return <PostCard key={p.id} post={p} go={go} />; })}
          {hasMore && !loading && (
            <div style={{ textAlign: "center", paddingTop: 32 }}>
              <button onClick={loadMore} disabled={loadingMore} style={{
                background: "none", border: "1px solid var(--rule)", color: "var(--ink-2)",
                fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.08em",
                textTransform: "uppercase", padding: "10px 24px", borderRadius: 3, cursor: "pointer" }}>
                {loadingMore ? "Loading..." : "Load more"}
              </button>
            </div>
          )}
        </section>
      </div>
    </div>
  );
}

// ──────────────────────── Conversations Card ────────────────────────
function ConversationsCard({ post }) {
  var [hover, setHover] = useState(false);
  var isMobile = useIsMobile();

  return (
    <article
      onClick={function() { if (post.url) window.open(post.url, "_blank"); }}
      onMouseEnter={function() { setHover(true); }}
      onMouseLeave={function() { setHover(false); }}
      style={{
        margin: "14px 0",
        padding: "18px 20px",
        background: "var(--navy-soft)",
        border: "1px solid #9AAAD0",
        borderRadius: 4,
        cursor: "pointer",
        opacity: hover ? 0.88 : 1,
        transition: "opacity 0.15s",
      }}>
      <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 8,
        fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-3)",
        textTransform: "uppercase", letterSpacing: "0.08em" }}>
        <span>{post.date}</span>
        {post.minutes && <span>&middot; {post.minutes} min</span>}
        <span style={{ color: "var(--accent)" }}>&middot; Conversation</span>
      </div>
      <h2 style={{ fontFamily: "var(--serif)", fontWeight: 400,
        fontSize: isMobile ? 20 : 24, lineHeight: 1.2,
        letterSpacing: "-0.015em", margin: "0 0 10px", color: "var(--ink)" }}>
        {post.title}
      </h2>
      {post.excerpt && (
        <p style={{ fontFamily: "var(--serif)", fontSize: 15, lineHeight: 1.65,
          color: "var(--ink-2)", margin: 0, maxWidth: 560 }}>
          {post.excerpt}
        </p>
      )}
    </article>
  );
}


// ──────────────────────── Post Card ────────────────────────
function PostCard({ post, go }) {
  var isMobile  = useIsMobile();
  var [hover, setHover] = useState(false);
  var allTags   = window.TAGS || [];
  var tagLabel  = (allTags.find(function(t) { return t.id === post.tag; }) || {}).label || "";

  // Check if this is a Conversations post
  var isConversation = post.tags && post.tags.some(function(t) { return t.slug === "conversations"; });
  if (isConversation) {
    return <ConversationsCard post={post} />;
  }

  var isImported = post.source && post.source !== "native";

  if (isImported) {
    var bgMap = { linkedin: "#ECF1FB", x: "#F4F4F2", substack: "#FBE4D2" };
    var borderMap = { linkedin: "#C5D3F0", x: "#E0E0DC", substack: "#F0C8A8" };
    var labelMap  = { linkedin: "imported from LinkedIn", x: "imported from X", substack: "imported from Substack" };
    return (
      <article onClick={function() { if (post.url) window.open(post.url, "_blank"); }}
        onMouseEnter={function() { setHover(true); }} onMouseLeave={function() { setHover(false); }}
        style={{ margin: "16px 0", cursor: "pointer",
          background: bgMap[post.source] || "var(--paper-2)",
          border: "1px solid " + (borderMap[post.source] || "var(--rule)"),
          borderRadius: 4, padding: "16px 18px", opacity: hover ? 0.9 : 1, transition: "opacity 0.15s" }}>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 10,
          alignItems: "center", flexWrap: "wrap", gap: 8 }}>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <div style={{ width: 30, height: 30, borderRadius: 999, background: "var(--ink)", color: "var(--paper)",
              fontFamily: "var(--sans)", fontWeight: 600, fontSize: 11, display: "grid",
              placeItems: "center", flexShrink: 0 }}>VK</div>
            <div>
              <div style={{ fontFamily: "var(--sans)", fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>Veda Konduru</div>
              <div style={{ fontFamily: "var(--sans)", fontSize: 11, color: "var(--ink-3)" }}>
                {post.date} &middot; {labelMap[post.source] || post.source}
              </div>
            </div>
          </div>
          <SrcBadge source={post.source} href={null} />
        </div>
        <h2 style={{ fontFamily: "var(--sans)", fontWeight: 500, fontSize: 17, lineHeight: 1.35,
          margin: "0 0 8px", letterSpacing: "-0.01em", color: "var(--ink)" }}>{post.title}</h2>
        {post.excerpt && (
          <p style={{ fontFamily: "var(--sans)", fontSize: 15, lineHeight: 1.6,
            color: "var(--ink-2)", margin: 0 }}>{post.excerpt}</p>
        )}
        <SourceLinksRow sourceLinks={post.sourceLinks} source={post.source} />
      </article>
    );
  }

  // Native / written-here card
  return (
    <article onClick={function() { window.open(post.url, "_blank"); }}
      onMouseEnter={function() { setHover(true); }} onMouseLeave={function() { setHover(false); }}
      style={{ padding: "26px 0", borderBottom: "1px solid var(--rule-2)",
        cursor: "pointer", opacity: hover ? 0.75 : 1, transition: "opacity 0.15s" }}>
      <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 8,
        fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-3)",
        textTransform: "uppercase", letterSpacing: "0.08em" }}>
        <span>{post.date}</span>
        {post.minutes && <span>&middot; {post.minutes} min</span>}
        {tagLabel && <span>&middot; {tagLabel}</span>}
      </div>
      <h2 style={{ fontFamily: "var(--serif)", fontWeight: 400,
        fontSize: isMobile ? 22 : 28, lineHeight: isMobile ? 1.25 : 1.18,
        letterSpacing: "-0.015em", margin: "0 0 10px", color: "var(--ink)" }}>{post.title}</h2>
      {post.excerpt && (
        <p style={{ fontFamily: "var(--serif)", fontSize: 16, lineHeight: 1.65,
          color: "var(--ink-2)", margin: 0, maxWidth: 560 }}>{post.excerpt}</p>
      )}
      <SourceLinksRow sourceLinks={post.sourceLinks} source={post.source} />
    </article>
  );
}

// ──────────────────────── Post Page ────────────────────────
function PostPage({ post, go }) {
  var isMobile = useIsMobile();
  var allTags  = window.TAGS || [];
  var tagLabel = (allTags.find(function(t) { return t.id === post.tag; }) || {}).label || "";
  var comments = (window.COMMENTS || {})[post.id] || [];

  return (
    <div className="container" style={{ maxWidth: 700, padding: isMobile ? "32px 0 60px" : "56px 0 80px" }}>
      <button onClick={function() { go({ name: "writing" }); }}
        style={{ background: "none", border: 0, padding: 0, cursor: "pointer",
          fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.08em",
          textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 32,
          display: "flex", alignItems: "center", gap: 6 }}>
        &larr; All writing
      </button>

      <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
        textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 16 }}>
        {post.date}{post.minutes ? " \u00b7 " + post.minutes + " min read" : ""}{tagLabel ? " \u00b7 " + tagLabel : ""}
      </div>

      <h1 style={{ fontFamily: "var(--serif)", fontWeight: 400,
        fontSize: isMobile ? 28 : 40, lineHeight: 1.12,
        letterSpacing: "-0.02em", margin: "0 0 36px", color: "var(--ink)" }}>
        {post.title}
      </h1>

      <hr style={{ border: 0, borderTop: "2px solid var(--ink)", marginBottom: 32 }} />

      <div style={{ fontFamily: "var(--serif)", fontSize: 18, lineHeight: 1.75, color: "var(--ink)" }}>
        {post.body ? post.body.map(function(para, i) {
          return <p key={i} style={{ marginBottom: 24 }}>{para}</p>;
        }) : (
          <p style={{ fontStyle: "italic", color: "var(--ink-3)" }}>Full essay coming soon.</p>
        )}
      </div>

      {comments.length > 0 && (
        <>
          <hr style={{ border: 0, borderTop: "1px solid var(--rule)", margin: "48px 0 28px" }} />
          <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
            textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 20 }}>
            Responses
          </div>
          {comments.map(function(c, i) {
            return (
              <div key={i} style={{ padding: "16px 0", borderBottom: "1px solid var(--rule-2)" }}>
                <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 8 }}>
                  <div style={{ width: 26, height: 26, borderRadius: 999,
                    background: c.author_self ? "var(--accent)" : "var(--ink-2)",
                    color: "white", fontFamily: "var(--sans)", fontWeight: 600,
                    fontSize: 10, display: "grid", placeItems: "center", flexShrink: 0 }}>
                    {c.author.split(" ").map(function(w) { return w[0]; }).join("").slice(0,2)}
                  </div>
                  <span style={{ fontFamily: "var(--sans)", fontSize: 13, fontWeight: 500,
                    color: "var(--ink)" }}>{c.author}</span>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 10.5,
                    color: "var(--ink-3)" }}>{c.when} ago</span>
                </div>
                <p style={{ fontFamily: "var(--serif)", fontSize: 15, lineHeight: 1.65,
                  color: "var(--ink-2)", margin: 0, paddingLeft: 34 }}>{c.text}</p>
              </div>
            );
          })}
        </>
      )}
    </div>
  );
}

// ──────────────────────── Reading Page ────────────────────────
function ReadingPage() {
  var isMobile = useIsMobile();
  var groups = {
    current:   (window.READING || []).filter(function(b) { return b.status === "current"; }),
    rereading: (window.READING || []).filter(function(b) { return b.status === "rereading"; }),
    finished:  (window.READING || []).filter(function(b) { return b.status === "finished"; }),
    queued:    (window.READING || []).filter(function(b) { return b.status === "queued"; }),
  };
  var labelMap = { current: "Currently reading", rereading: "Returning to",
    finished: "Finished & marked up", queued: "Queue" };

  return (
    <div className="container" style={{ maxWidth: 760, padding: isMobile ? "32px 0 60px" : "60px 0 80px" }}>
      <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
        textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 12 }}>Reading list</div>
      <h1 style={{ fontFamily: "var(--serif)", fontWeight: 400,
        fontSize: isMobile ? 30 : 40, lineHeight: 1.12,
        letterSpacing: "-0.02em", margin: "0 0 18px", color: "var(--ink)" }}>
        Books I keep returning to.
      </h1>
      <p style={{ fontFamily: "var(--serif)", fontSize: 17, lineHeight: 1.6,
        color: "var(--ink-2)", maxWidth: 580, margin: "0 0 40px" }}>
        Not a recommendation engine &mdash; a record of which writers have earned a second reading and why.
      </p>

      {["current","rereading","finished","queued"].map(function(k) {
        if (!groups[k].length) return null;
        return (
          <div key={k} style={{ marginBottom: 40 }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
              textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 12 }}>{labelMap[k]}</div>
            <hr style={{ border: 0, borderTop: "2px solid var(--ink)", marginBottom: 0 }} />
            {groups[k].map(function(b, i) {
              return (
                <div key={i} className="reading-row" style={{ padding: "18px 0",
                  borderBottom: "1px solid var(--rule-2)",
                  display: isMobile ? "block" : "grid",
                  gridTemplateColumns: "1fr 1fr", gap: 24, alignItems: "baseline" }}>
                  <div style={{ marginBottom: isMobile ? 6 : 0 }}>
                    <div style={{ fontFamily: "var(--serif)", fontStyle: "italic",
                      fontSize: 18, lineHeight: 1.3, color: "var(--ink)" }}>{b.title}</div>
                    <div style={{ fontFamily: "var(--sans)", fontSize: 13,
                      color: "var(--ink-3)", marginTop: 3 }}>{b.author}</div>
                  </div>
                  <div style={{ fontFamily: "var(--serif)", fontSize: 15,
                    lineHeight: 1.55, color: "var(--ink-2)" }}>{b.note}</div>
                </div>
              );
            })}
          </div>
        );
      })}
    </div>
  );
}

// ──────────────────────── Projects Page ────────────────────────
function ProjectsPage() {
  var isMobile = useIsMobile();
  return (
    <div className="container" style={{ maxWidth: 760, padding: isMobile ? "32px 0 60px" : "60px 0 80px" }}>
      <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
        textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 12 }}>Projects</div>
      <h1 style={{ fontFamily: "var(--serif)", fontWeight: 400,
        fontSize: isMobile ? 30 : 40, lineHeight: 1.12,
        letterSpacing: "-0.02em", margin: "0 0 18px", color: "var(--ink)" }}>
        Things I've shaped, or am still shaping.
      </h1>
      <p style={{ fontFamily: "var(--serif)", fontSize: 17, lineHeight: 1.6,
        color: "var(--ink-2)", maxWidth: 580, margin: "0 0 40px" }}>
        Not a portfolio. A short list of work I'd still defend.
      </p>
      <hr style={{ border: 0, borderTop: "2px solid var(--ink)", marginBottom: 0 }} />
      {(window.PROJECTS || []).map(function(p, i) {
        return (
          <div key={i} style={{ padding: "26px 0", borderBottom: "1px solid var(--rule-2)" }}>
            <div style={{ display: "flex", justifyContent: "space-between",
              flexDirection: isMobile ? "column" : "row", gap: isMobile ? 4 : 0,
              alignItems: isMobile ? "flex-start" : "baseline", marginBottom: 10 }}>
              <h2 style={{ fontFamily: "var(--serif)", fontWeight: 400,
                fontSize: 22, margin: 0, color: "var(--ink)" }}>{p.title}</h2>
              <span style={{ fontFamily: "var(--mono)", fontSize: 10.5, color: "var(--ink-3)",
                letterSpacing: "0.06em", textTransform: "uppercase" }}>{p.role}</span>
            </div>
            <p style={{ fontFamily: "var(--serif)", fontSize: 16, lineHeight: 1.55,
              color: "var(--ink-2)", margin: 0 }}>{p.what}</p>
          </div>
        );
      })}
    </div>
  );
}

// ──────────────────────── About Page ────────────────────────
function AboutPage({ go }) {
  var isMobile = useIsMobile();
  return (
    <div className="container" style={{ maxWidth: 700, padding: isMobile ? "32px 0 60px" : "60px 0 80px" }}>
      <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
        textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 12 }}>About</div>
      <h1 style={{ fontFamily: "var(--serif)", fontWeight: 400,
        fontSize: isMobile ? 30 : 40, lineHeight: 1.12,
        letterSpacing: "-0.02em", margin: "0 0 32px", color: "var(--ink)" }}>
        An artificial intelligence architect, <em>now</em> turned the Mind Explorer.
      </h1>
      <div style={{ fontFamily: "var(--serif)", fontSize: 18, lineHeight: 1.7, color: "var(--ink)" }}>
        <p>I'm Veda Konduru — a former AI tech founder, data scientist, and technology product architect. Twenty-plus years across research, product, and the kind of late-night decisions that quietly shape companies.</p>
        <p>Inspired by some events in my life, I set off on a quest to explore the role of natural intelligence — the human mind's underpinnings — in an age of artificial ones. The last few years have been the most consequential of my career, even though almost none of it has been on a resume.</p>
        <p>This site is the slow public record of that exploration. Essays, frameworks, field notes from rooms I sit in — and an open invitation to anyone walking a similar road.</p>
      </div>

      <hr style={{ border: 0, borderTop: "1px solid var(--rule)", margin: "40px 0 28px" }} />
      <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
        textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 14 }}>Selected timeline</div>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 16 }}>
        {[
          ["2025 –",      "Mind Explorer — this site, plus small-group practice circles"],
          ["2019 – 2024", "Founder, Vidya — AI tutor for under-resourced classrooms"],
          ["2016 – 2019", "Co-founder, Ground Truth Lab — applied ML consultancy"],
          ["2008 – 2016", "Principal architect roles across health-tech and ed-tech"],
          ["2003 – 2008", "Research engineer, NLP and early recommender systems"],
        ].map(function(item, i) {
          return (
            <li key={i} style={{ display: isMobile ? "block" : "grid",
              gridTemplateColumns: "150px 1fr", gap: 16,
              fontFamily: "var(--serif)", fontSize: 16, lineHeight: 1.55, color: "var(--ink)" }}>
              <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-3)",
                letterSpacing: "0.06em", textTransform: "uppercase",
                display: "block", marginBottom: isMobile ? 2 : 0 }}>{item[0]}</span>
              <span>{item[1]}</span>
            </li>
          );
        })}
      </ul>

      <hr style={{ border: 0, borderTop: "1px solid var(--rule)", margin: "40px 0 28px" }} />
      <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
        textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 14 }}>Elsewhere</div>
      <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
        {[
          { label: "LinkedIn", href: "https://linkedin.com/in/vedak" },
          { label: "X",        href: "https://x.com/vedakonduru"     },
        ].map(function(item) {
          return (
            <a key={item.label} href={item.href} target="_blank" rel="noreferrer"
              style={{ fontFamily: "var(--sans)", fontSize: 13, padding: "8px 16px",
                border: "1px solid var(--rule)", borderRadius: 100,
                color: "var(--ink-2)", textDecoration: "none" }}>{item.label}</a>
          );
        })}
      </div>
    </div>
  );
}

// ──────────────────────── Search Page ────────────────────────
function SearchPage({ go }) {
  var isMobile = useIsMobile();
  var [query, setQuery]       = useState("");
  var [source, setSource]     = useState("all");
  var [fromDate, setFromDate] = useState("");
  var [toDate, setToDate]     = useState("");
  var [allPosts, setAllPosts] = useState([]);
  var [loading, setLoading]   = useState(true);
  var [error, setError]       = useState(null);
  var [bounds, setBounds]     = useState({ from: "", to: "" });
  var inputRef = useRef(null);

  var SEARCH_SOURCES = [
    { id: "all",      label: "All" },
    { id: "native",   label: "Written here" },
    { id: "linkedin", label: "LinkedIn" },
    { id: "x",        label: "X" },
    { id: "substack", label: "Substack" },
  ];

  function todayISO() { return new Date().toISOString().slice(0, 10); }

  useEffect(function() {
    (async function() {
      try {
        setLoading(true);
        var data = await fetchAllPosts();
        var mapped = (data.posts || []).map(function(p) {
          return Object.assign({}, p, {
            source: detectSource(p.tags),
            date: fmtDate(p.published_at),
            excerpt: cleanExcerpt(p.excerpt),
            minutes: p.reading_time,
            sourceLinks: parseSourceLinks(p.html),
          });
        });
        setAllPosts(mapped);
        var oldest = mapped.reduce(function(min, p) {
          var d = (p.published_at || "").slice(0, 10);
          return (d && (!min || d < min)) ? d : min;
        }, "");
        var to = todayISO();
        var ytd = new Date().getFullYear() + "-01-01";
        setBounds({ from: oldest, to: to });
        setFromDate(ytd);
        setToDate(to);
        setError(null);
      } catch(e) { setError(e.message); }
      finally { setLoading(false); }
    })();
    if (inputRef.current) inputRef.current.focus();
  }, []);

  function matchesSource(p) {
    if (source === "all") return true;
    return p.source === source;
  }

  var q = query.trim().toLowerCase();
  var results = allPosts.filter(function(p) {
    if (q) {
      var hay = (p.title + " " + (p.excerpt || "")).toLowerCase();
      if (hay.indexOf(q) === -1) return false;
    }
    if (!matchesSource(p)) return false;
    if (fromDate && new Date(p.published_at) < new Date(fromDate)) return false;
    if (toDate) {
      var t = new Date(toDate); t.setHours(23, 59, 59, 999);
      if (new Date(p.published_at) > t) return false;
    }
    return true;
  });

  var hasFilters = q || source !== "all" || fromDate !== (new Date().getFullYear() + "-01-01") || toDate !== bounds.to;
  function clearAll() { setQuery(""); setSource("all"); setFromDate(new Date().getFullYear() + "-01-01"); setToDate(bounds.to); if (inputRef.current) inputRef.current.focus(); }

  var dateInputStyle = {
    fontFamily: "var(--sans)", fontSize: 13, padding: "8px 10px",
    border: "1px solid var(--rule)", borderRadius: 3, background: "var(--paper)",
    color: "var(--ink)", width: isMobile ? "100%" : "auto"
  };

  return (
    <div className="container" style={{ maxWidth: 820, padding: isMobile ? "32px 0 60px" : "56px 0 80px" }}>
      <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
        textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 12 }}>Search</div>

      {/* text input */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, border: "1.5px solid var(--ink)",
        borderRadius: 6, padding: isMobile ? "9px 12px" : "10px 14px", marginBottom: 18 }}>
        <SearchIcon size={17} color="var(--ink-2)" />
        <input ref={inputRef} type="text" value={query} placeholder="Search every article…"
          onChange={function(e) { setQuery(e.target.value); }}
          style={{ border: 0, padding: 0, fontFamily: "var(--serif)", fontSize: isMobile ? 16 : 18,
            background: "transparent", width: "100%", color: "var(--ink)", outline: "none" }} />
        {query && (
          <button onClick={function() { setQuery(""); if (inputRef.current) inputRef.current.focus(); }}
            aria-label="Clear" style={{ background: "none", border: 0, cursor: "pointer",
              color: "var(--ink-3)", fontSize: 18, lineHeight: 1, padding: 0 }}>&times;</button>
        )}
      </div>

      {/* filters: source + date range */}
      <div style={{ display: "flex", flexWrap: "wrap", gap: isMobile ? 16 : 28, alignItems: "flex-end",
        paddingBottom: 22, borderBottom: "1px solid var(--rule)", marginBottom: 8 }}>
        <div>
          <div className="filter-label">Source</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {SEARCH_SOURCES.map(function(f) {
              var active = source === f.id;
              return (
                <button key={f.id} onClick={function() { setSource(f.id); }}
                  style={{ fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.08em",
                    textTransform: "uppercase", padding: "4px 11px", borderRadius: 100,
                    border: "1px solid " + (active ? "var(--ink)" : "var(--rule)"),
                    background: active ? "var(--ink)" : "none",
                    color: active ? "var(--paper)" : "var(--ink-3)", cursor: "pointer" }}>
                  {f.label}
                </button>
              );
            })}
          </div>
        </div>
        <div>
          <div className="filter-label">From</div>
          <input type="date" value={fromDate} min={bounds.from || undefined} max={toDate || bounds.to || undefined}
            onChange={function(e) { setFromDate(e.target.value); }} style={dateInputStyle} />
        </div>
        <div>
          <div className="filter-label">To</div>
          <input type="date" value={toDate} min={fromDate || bounds.from || undefined} max={bounds.to || undefined}
            onChange={function(e) { setToDate(e.target.value); }} style={dateInputStyle} />
        </div>
        {hasFilters && (
          <button onClick={clearAll} style={{ background: "none", border: 0, color: "var(--accent)",
            fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.06em", textTransform: "uppercase",
            cursor: "pointer", padding: "0 0 9px" }}>Clear all</button>
        )}
      </div>

      {/* results */}
      <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em",
        textTransform: "uppercase", color: "var(--ink-3)", margin: "22px 0 0", minHeight: 14 }}>
        {loading ? "Loading the archive…" :
          error ? "" :
          hasFilters ? (results.length + (results.length === 1 ? " result" : " results")) :
          (allPosts.length + " articles · type to search")}
      </div>
      <hr style={{ border: 0, borderTop: "2px solid var(--ink)", marginBottom: 0 }} />

      {loading && [1,2,3].map(function(i) { return <SkeletonCard key={i} />; })}
      {error && (
        <div style={{ padding: "40px 0", fontFamily: "var(--serif)", color: "var(--ink-3)" }}>
          <p style={{ fontStyle: "italic" }}>Couldn't reach the blog right now.</p>
          <p style={{ fontSize: 13, fontFamily: "var(--mono)" }}>{error}</p>
        </div>
      )}
      {!loading && !error && hasFilters && results.length === 0 && (
        <div style={{ padding: "48px 0", textAlign: "center", color: "var(--ink-3)",
          fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 18 }}>
          No articles match{q ? " “" + query + "”" : ""}. Try a broader search.
        </div>
      )}
      {!loading && !error && results.map(function(p) { return <PostCard key={p.id} post={p} go={go} />; })}
    </div>
  );
}

// ──────────────────────── Footer ────────────────────────
function Footer({ go }) {
  var isMobile = useIsMobile();
  return (
    <footer style={{ borderTop: "1px solid var(--rule)", padding: "32px 0", marginTop: 40 }}>
      <div className="container" style={{ display: "flex", justifyContent: "space-between",
        flexDirection: isMobile ? "column" : "row", gap: isMobile ? 16 : 0,
        alignItems: isMobile ? "flex-start" : "baseline",
        fontFamily: "var(--sans)", fontSize: 12.5, color: "var(--ink-3)" }}>
        <span>&copy; Veda Konduru &middot; {new Date().getFullYear()} &middot; intuition2action.net</span>
        <div style={{ display: "flex", gap: 20 }}>
          <button onClick={() => go({ name: "about" })} style={{ background: "none", border: 0,
            color: "inherit", fontFamily: "inherit", fontSize: "inherit", padding: 0, cursor: "pointer" }}>
            Colophon
          </button>
        </div>
      </div>
    </footer>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
