function HeroSection() {
  const ACCENT = "#6EE7F4";
  const INK = "#EDE9E0";
  const { shown } = window.useRotatingStatus(4200);

  const manifestCommands = [
    { key: "results", desc: "competition results", go: "#results" },
    { key: "work", desc: "experience and internships", go: "#work" },
    { key: "projects", desc: "things I've built", go: "#projects" },
    { key: "research", desc: "published work and notes", go: "#research" },
    { key: "skills", desc: "tools and experience map", go: "#skills" },
    { key: "about", desc: "short personal overview", go: "#about" },
    { key: "contact", desc: "email, links, and resume", go: "#contact" },
  ];

  const jump = (id) => {
    const target = document.querySelector(id);
    if (!target) return;

    const targetTop = target.getBoundingClientRect().top + window.scrollY;
    const terminalJumpOffset = 10;

    window.scrollTo({
      top: Math.max(0, targetTop - terminalJumpOffset),
      behavior: "smooth",
    });
  };
  const terminalCommands = React.useMemo(() => ([
    { key: "home", desc: "top of the page", run: () => jump("#hero"), category: "go" },
    ...manifestCommands.map((command) => ({
      key: command.key,
      desc: command.desc,
      run: () => jump(command.go),
      category: "go",
    })),
    { key: "open chat", desc: "show the chat window", run: () => window.dispatchEvent(new Event("open-docked-chat")), category: "open" },
    { key: "close chat", desc: "hide the chat window", run: () => window.dispatchEvent(new Event("close-docked-chat")), category: "change" },
    { key: "resume", desc: "open the resume PDF", run: () => window.openSiteLink("/downloads/Cosmopoulos-Trading.pdf"), category: "open" },
    { key: "research paper", desc: "open the published paper", run: () => window.openSiteLink("/assets/papers/election_microstructure.pdf"), category: "open" },
    { key: "email", desc: "write an email", run: () => window.openSiteLink("mailto:bcosm@umich.edu", { sameTab: true }), category: "open" },
    { key: "copy email", desc: "copy the email address", run: () => window.copySiteEmailAddress(), category: "open" },
    { key: "github", desc: "open GitHub", run: () => window.openSiteLink("https://github.com/bcosm"), category: "open" },
    { key: "linkedin", desc: "open LinkedIn", run: () => window.openSiteLink("https://www.linkedin.com/in/baz-cosmopoulos/"), category: "open" },
    { key: "light mode", desc: "switch to the light look", run: () => window.setSiteTheme("light"), category: "change" },
    { key: "dark mode", desc: "switch to the dark look", run: () => window.setSiteTheme("dark"), category: "change" },
  ]), []);

  return (
    <section
      id="hero"
      style={{
        minHeight: "calc(100vh - 54px)",
        padding: "40px 0 80px",
        position: "relative",
        display: "flex",
        flexDirection: "column",
        justifyContent: "flex-start",
      }}
    >
      <div
        aria-hidden
        style={{
          position: "absolute",
          inset: "0 -200px",
          pointerEvents: "none",
          backgroundImage: "linear-gradient(rgba(237,233,224,0.035) 1px, transparent 1px), linear-gradient(90deg, rgba(237,233,224,0.035) 1px, transparent 1px)",
          backgroundSize: "64px 64px",
          maskImage: "radial-gradient(ellipse 80% 55% at 50% 40%, black, transparent)",
          WebkitMaskImage: "radial-gradient(ellipse 80% 55% at 50% 40%, black, transparent)",
        }}
      />

      <div
        data-hero-top="true"
        style={{
          position: "relative",
          display: "flex",
          alignItems: "flex-end",
          justifyContent: "space-between",
          gap: 40,
          flexWrap: "wrap",
        }}
      >
        <div style={{ minWidth: 0, flex: 1 }}>
          <h1
            style={{
              fontFamily: "'Instrument Serif', Georgia, serif",
              fontWeight: 400,
              fontSize: "clamp(68px, 9.5vw, 128px)",
              lineHeight: 0.92,
              letterSpacing: "-0.035em",
              color: INK,
              margin: 0,
            }}
          >
            Baz
            <br />
            Cosmopoulos
          </h1>
          <div
            style={{
              marginTop: 16,
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              fontSize: 11,
              letterSpacing: "0.14em",
              color: "rgba(237,233,224,0.55)",
              textTransform: "uppercase",
            }}
          >
            Michigan '27 · Financial Math + Data Science · CS minor
          </div>
        </div>
        <div
          data-hero-copy="true"
          style={{
            maxWidth: 380,
            fontFamily: "'Instrument Serif', Georgia, serif",
            fontStyle: "italic",
            fontSize: 22,
            lineHeight: 1.35,
            color: "rgba(237,233,224,0.78)",
          }}
        >
          Just a chill guy who likes trading and coding. Scroll or use the terminal to get around, or just ask the chatbot below (it knows an unsettling amount of info about me).
        </div>
      </div>

      <div
        style={{
          position: "relative",
          marginTop: 52,
          display: "flex",
          alignItems: "center",
          gap: 14,
          padding: "12px 18px",
          background: "rgba(110,231,244,0.04)",
          border: "1px solid rgba(110,231,244,0.14)",
          borderRadius: 4,
          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
          fontSize: 13,
          color: "rgba(237,233,224,0.9)",
        }}
      >
        <span style={{ width: 6, height: 6, borderRadius: 999, background: ACCENT, boxShadow: `0 0 10px ${ACCENT}`, flexShrink: 0 }} />
        <span style={{ color: "rgba(237,233,224,0.5)", letterSpacing: "0.2em", fontSize: 10 }}>NOW</span>
        <span style={{ color: INK }}>{shown}<window.Caret color={ACCENT} /></span>
      </div>

      <div
        data-hero-layout="true"
        style={{
          position: "relative",
          marginTop: 28,
          display: "grid",
          gridTemplateColumns: "1.05fr 1fr",
          gap: 22,
          minHeight: 420,
        }}
      >
        <div
          style={{
            background: "rgba(237,233,224,0.025)",
            border: "1px solid rgba(237,233,224,0.1)",
            borderRadius: 6,
            overflow: "hidden",
            display: "flex",
            flexDirection: "column",
          }}
        >
          <div style={{ padding: "0 6px 14px" }}>
            <ManifestTerminal commands={terminalCommands} />
            <div style={{ height: 8 }} />
            {manifestCommands.map((command) => (
              <button
                key={command.key}
                data-manifest-button="true"
                onClick={() => jump(command.go)}
                style={{
                  width: "100%",
                  display: "flex",
                  alignItems: "baseline",
                  justifyContent: "space-between",
                  padding: "14px 18px",
                  borderRadius: 6,
                  background: "transparent",
                  border: "none",
                  borderLeft: "2px solid transparent",
                  cursor: "pointer",
                  textAlign: "left",
                  transition: "all 140ms ease",
                }}
                onMouseEnter={(event) => {
                  event.currentTarget.style.background = "rgba(110,231,244,0.08)";
                  event.currentTarget.style.borderLeftColor = ACCENT;
                  const key = event.currentTarget.querySelector("[data-key]");
                  const go = event.currentTarget.querySelector("[data-go]");
                  if (key) key.style.color = ACCENT;
                  if (go) go.style.opacity = 1;
                }}
                onMouseLeave={(event) => {
                  event.currentTarget.style.background = "transparent";
                  event.currentTarget.style.borderLeftColor = "transparent";
                  const key = event.currentTarget.querySelector("[data-key]");
                  const go = event.currentTarget.querySelector("[data-go]");
                  if (key) key.style.color = INK;
                  if (go) go.style.opacity = 0;
                }}
              >
                <span style={{ display: "flex", alignItems: "baseline", gap: 18 }}>
                  <span
                    data-key
                    style={{
                      fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                      fontSize: 17,
                      color: INK,
                      minWidth: 104,
                      transition: "color 140ms ease",
                    }}
                  >
                    {command.key}
                  </span>
                  <span
                    style={{
                      fontFamily: "'Instrument Serif', Georgia, serif",
                      fontStyle: "italic",
                      fontSize: 19,
                      color: "rgba(237,233,224,0.7)",
                    }}
                  >
                    {command.desc}
                  </span>
                </span>
                <span
                  data-go
                  style={{
                    fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                    fontSize: 10,
                    color: "rgba(237,233,224,0.5)",
                    letterSpacing: "0.18em",
                    opacity: 0,
                    transition: "opacity 140ms ease",
                  }}
                >
                  open -
                </span>
              </button>
            ))}
          </div>
        </div>

        <div
          style={{
            background: "rgba(237,233,224,0.025)",
            border: "1px solid rgba(237,233,224,0.1)",
            borderRadius: 6,
            overflow: "hidden",
            display: "flex",
            flexDirection: "column",
            height: 420,
          }}
        >
          <div
            style={{
              padding: "10px 16px",
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              fontSize: 10,
              letterSpacing: "0.24em",
              textTransform: "uppercase",
              color: "rgba(237,233,224,0.45)",
              display: "flex",
              justifyContent: "space-between",
              borderBottom: "1px solid rgba(237,233,224,0.06)",
              flexShrink: 0,
            }}
          >
            <span>Chat</span>
            <span style={{ color: "rgba(237,233,224,0.55)" }}>live</span>
          </div>
          <div style={{ flex: 1, minHeight: 0, overflow: "hidden", padding: "6px 14px 14px" }}>
            <ChatPanel accent={ACCENT} tone="dark" />
          </div>
        </div>
      </div>
    </section>
  );
}

function ManifestTerminal({ commands }) {
  const [value, setValue] = React.useState("");
  const [activeIndex, setActiveIndex] = React.useState(0);
  const [message, setMessage] = React.useState("");
  const inputRef = React.useRef(null);

  const query = value.trim().replace(/^\//, "").toLowerCase();
  const showingCommands = value.trim().startsWith("/") || query.length > 0;
  const results = React.useMemo(() => {
    if (!query) return commands;
    return commands.filter((command) => (
      command.key.includes(query) || command.desc.toLowerCase().includes(query)
    ));
  }, [commands, query]);

  React.useEffect(() => {
    setActiveIndex(0);
  }, [query]);

  const runCommand = (command) => {
    if (!command) {
      setMessage("No matching command.");
      return;
    }
    setValue("");
    const result = command.run?.();
    if (result && typeof result.then === "function") {
      result
        .then((nextMessage) => {
          setMessage(typeof nextMessage === "string" ? nextMessage : `${command.key} - ${command.desc}`);
        })
        .catch(() => {
          setMessage("Couldn't complete that command.");
        });
      return;
    }
    setMessage(typeof result === "string" ? result : `${command.key} - ${command.desc}`);
  };

  const submit = (event) => {
    event.preventDefault();
    const trimmed = value.trim();
    if (!trimmed || trimmed === "/") {
      setValue("/");
      inputRef.current?.focus();
      return;
    }
    runCommand(results[activeIndex] || commands.find((command) => command.key === query));
  };

  const handleKeyDown = (event) => {
    if (event.key === "ArrowDown" && results.length) {
      event.preventDefault();
      setActiveIndex((index) => Math.min(results.length - 1, index + 1));
    } else if (event.key === "ArrowUp" && results.length) {
      event.preventDefault();
      setActiveIndex((index) => Math.max(0, index - 1));
    } else if (event.key === "Escape") {
      setValue("");
    }
  };

  return (
    <div style={{
      margin: "0 -6px 8px",
      border: "none",
      borderBottom: "1px solid rgba(237,233,224,0.1)",
      borderRadius: 0,
      background: "rgba(10,10,11,0.5)",
      overflow: "hidden",
    }}>
      <form
        onSubmit={submit}
        style={{
          display: "grid",
          gridTemplateColumns: "auto 1fr auto",
          alignItems: "center",
          gap: 10,
          padding: "11px 12px",
        }}
      >
        <span style={{
          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
          fontSize: 14,
          color: "#6EE7F4",
        }}>
          &gt;
        </span>
        <input
          ref={inputRef}
          value={value}
          onChange={(event) => setValue(event.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="type / to browse commands..."
          style={{
            minWidth: 0,
            border: "none",
            outline: "none",
            background: "transparent",
            color: "#EDE9E0",
            fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            fontSize: 13,
          }}
        />
        <button
          type="submit"
          aria-label="Run command"
          style={{
            width: 28,
            height: 28,
            borderRadius: 5,
            border: "1px solid rgba(237,233,224,0.14)",
            background: "transparent",
            color: "rgba(237,233,224,0.62)",
            cursor: "pointer",
            lineHeight: 1,
          }}
        >
          ↵
        </button>
      </form>

      {showingCommands && (
        <div style={{
          borderTop: "1px solid rgba(237,233,224,0.07)",
          padding: "6px",
          maxHeight: 182,
          overflowY: "auto",
        }}>
          {results.map((command, index) => {
            const active = index === activeIndex;
            return (
              <button
                key={command.key}
                type="button"
                onMouseEnter={() => setActiveIndex(index)}
                onClick={() => runCommand(command)}
                style={{
                  width: "100%",
                  display: "grid",
                  gridTemplateColumns: "122px 1fr auto",
                  alignItems: "baseline",
                  gap: 10,
                  padding: "8px 10px",
                  border: "none",
                  borderLeft: active ? "2px solid #6EE7F4" : "2px solid transparent",
                  borderRadius: 5,
                  background: active ? "rgba(110,231,244,0.08)" : "transparent",
                  color: "#EDE9E0",
                  cursor: "pointer",
                  textAlign: "left",
                }}
              >
                <span style={{
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 13,
                  color: active ? "#6EE7F4" : "#EDE9E0",
                }}>
                  /{command.key}
                </span>
                <span style={{
                  fontFamily: "'Instrument Serif', Georgia, serif",
                  fontStyle: "italic",
                  fontSize: 15,
                  color: "rgba(237,233,224,0.68)",
                }}>
                  {command.desc}
                </span>
                <span style={{
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 9,
                  letterSpacing: "0.12em",
                  textTransform: "uppercase",
                  color: "rgba(237,233,224,0.38)",
                }}>
                  {command.category}
                </span>
              </button>
            );
          })}
          {!results.length && (
            <div style={{
              padding: "8px 10px",
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              fontSize: 11,
              color: "rgba(237,233,224,0.45)",
            }}>
              no matching commands
            </div>
          )}
        </div>
      )}

      {message && !showingCommands && (
        <div style={{
          borderTop: "1px solid rgba(237,233,224,0.07)",
          padding: "7px 12px 9px",
          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
          fontSize: 10,
          color: "rgba(237,233,224,0.48)",
        }}>
          {message}
        </div>
      )}
    </div>
  );
}

window.HeroSection = HeroSection;
