function Chrome() {
  const [now, setNow] = React.useState(() => new Date());
  const [paletteOpen, setPaletteOpen] = React.useState(false);

  React.useEffect(() => {
    const timer = setInterval(() => setNow(new Date()), 30_000);
    return () => clearInterval(timer);
  }, []);

  React.useEffect(() => {
    const handleKeyDown = (event) => {
      if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
        event.preventDefault();
        setPaletteOpen((open) => !open);
      }
      if (event.key === "Escape") setPaletteOpen(false);
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, []);

  const hhmm = now.toTimeString().slice(0, 5);

  return (
    <>
      <header style={{
        position: "fixed",
        top: 16,
        right: 22,
        zIndex: 40,
        display: "flex",
        alignItems: "center",
        gap: 10,
        fontFamily: "'JetBrains Mono', ui-monospace, monospace",
        fontSize: 10,
        letterSpacing: "0.22em",
        textTransform: "uppercase",
        color: "rgba(237,233,224,0.5)",
      }}>
        <span>local time · {hhmm}</span>
        <button
          onClick={() => setPaletteOpen(true)}
          style={{
            background: "rgba(10,10,11,0.7)",
            backdropFilter: "blur(8px)",
            border: "1px solid rgba(237,233,224,0.15)",
            color: "rgba(237,233,224,0.72)",
            padding: "5px 11px",
            borderRadius: 4,
            fontFamily: "inherit",
            fontSize: 10,
            letterSpacing: "0.18em",
            cursor: "pointer",
            textTransform: "uppercase",
            transition: "all 160ms ease",
          }}
          onMouseEnter={(event) => {
            event.currentTarget.style.color = "#6EE7F4";
            event.currentTarget.style.borderColor = "rgba(110,231,244,0.4)";
          }}
          onMouseLeave={(event) => {
            event.currentTarget.style.color = "rgba(237,233,224,0.72)";
            event.currentTarget.style.borderColor = "rgba(237,233,224,0.15)";
          }}
        >
          &#8984; K
        </button>
      </header>
      {paletteOpen && <CommandPalette onClose={() => setPaletteOpen(false)} />}
    </>
  );
}

function CommandPalette({ onClose }) {
  const [query, setQuery] = React.useState("");
  const [selectedIndex, setSelectedIndex] = React.useState(0);

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

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

    window.scrollTo({
      top: Math.max(0, targetTop - terminalJumpOffset),
      behavior: "smooth",
    });
  };

  const items = [
    { key: "home", desc: "top of the page", run: () => jump("#hero"), category: "go" },
    { key: "results", desc: "competition results", run: () => jump("#results"), category: "go" },
    { key: "work", desc: "experience and internships", run: () => jump("#work"), category: "go" },
    { key: "projects", desc: "things I've built", run: () => jump("#projects"), category: "go" },
    { key: "research", desc: "published work and notes", run: () => jump("#research"), category: "go" },
    { key: "skills", desc: "tools and experience map", run: () => jump("#skills"), category: "go" },
    { key: "about", desc: "short personal overview", run: () => jump("#about"), category: "go" },
    { key: "contact", desc: "email, links, and resume", run: () => jump("#contact"), 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" },
  ];

  const results = React.useMemo(() => {
    const needle = query.trim().toLowerCase();
    if (!needle) return items;
    return items.filter((item) => item.key.includes(needle) || item.desc.toLowerCase().includes(needle));
  }, [items, query]);

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

  const run = (item) => {
    item.run?.();
    onClose();
  };

  const handleKeyDown = (event) => {
    if (event.key === "ArrowDown") {
      event.preventDefault();
      setSelectedIndex((index) => Math.min(results.length - 1, index + 1));
    } else if (event.key === "ArrowUp") {
      event.preventDefault();
      setSelectedIndex((index) => Math.max(0, index - 1));
    } else if (event.key === "Enter") {
      event.preventDefault();
      const item = results[selectedIndex];
      if (item) run(item);
    } else if (event.key === "Escape") {
      onClose();
    }
  };

  return (
    <div
      onMouseDown={onClose}
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 60,
        background: "rgba(4,4,6,0.62)",
        backdropFilter: "blur(6px)",
        display: "grid",
        placeItems: "start center",
        paddingTop: "12vh",
        animation: "bazFadeIn 180ms ease-out",
      }}
    >
      <div
        onMouseDown={(event) => event.stopPropagation()}
        style={{
          width: "min(620px, 92vw)",
          background: "#101012",
          border: "1px solid rgba(237,233,224,0.12)",
          borderRadius: 8,
          overflow: "hidden",
          boxShadow: "0 30px 80px rgba(0,0,0,0.5)",
        }}
      >
        <div style={{
          display: "flex",
          alignItems: "center",
          gap: 12,
          padding: "14px 18px",
          borderBottom: "1px solid rgba(237,233,224,0.08)",
        }}>
          <span style={{
            fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            fontSize: 14,
            color: "#6EE7F4",
          }}>
            &gt;
          </span>
          <input
            autoFocus
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="jump anywhere..."
            style={{
              flex: 1,
              background: "transparent",
              border: "none",
              outline: "none",
              color: "#EDE9E0",
              fontSize: 17,
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            }}
          />
          <span style={{
            fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            fontSize: 10,
            color: "rgba(237,233,224,0.4)",
            border: "1px solid rgba(237,233,224,0.15)",
            padding: "2px 6px",
            borderRadius: 4,
            letterSpacing: "0.1em",
          }}>
            esc
          </span>
        </div>

        <div style={{ maxHeight: "50vh", overflowY: "auto", padding: "8px 6px" }}>
          {["go", "open", "change"].map((category) => {
            const group = results.filter((item) => item.category === category);
            if (!group.length) return null;

            return (
              <div key={category} style={{ marginBottom: 6 }}>
                <div style={{
                  padding: "6px 14px",
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 10,
                  letterSpacing: "0.22em",
                  textTransform: "uppercase",
                  color: "rgba(237,233,224,0.35)",
                }}>
                  {category}
                </div>
                {group.map((item) => {
                  const index = results.indexOf(item);
                  const active = index === selectedIndex;
                  return (
                    <div
                      key={item.key}
                      onMouseEnter={() => setSelectedIndex(index)}
                      onClick={() => run(item)}
                      style={{
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "space-between",
                        padding: "10px 14px",
                        borderRadius: 6,
                        background: active ? "rgba(110,231,244,0.08)" : "transparent",
                        cursor: "pointer",
                        borderLeft: active ? "2px solid #6EE7F4" : "2px solid transparent",
                      }}
                    >
                      <div style={{ display: "flex", alignItems: "baseline", gap: 14 }}>
                        <span style={{
                          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                          fontSize: 14,
                          color: active ? "#6EE7F4" : "#EDE9E0",
                          minWidth: 118,
                        }}>
                          {item.key}
                        </span>
                        <span style={{
                          fontFamily: "'Instrument Serif', Georgia, serif",
                          fontStyle: "italic",
                          fontSize: 15,
                          color: "rgba(237,233,224,0.7)",
                        }}>
                          {item.desc}
                        </span>
                      </div>
                      {active && (
                        <span style={{
                          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                          fontSize: 10,
                          color: "rgba(237,233,224,0.5)",
                          letterSpacing: "0.15em",
                        }}>
                          {item.category === "go" ? "jump ->" : item.category === "open" ? "open ->" : "set ->"}
                        </span>
                      )}
                    </div>
                  );
                })}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function DockedChat({ open, onToggle }) {
  return (
    <div style={{
      position: "fixed",
      bottom: 22,
      right: 22,
      zIndex: 50,
      display: "flex",
      flexDirection: "column",
      alignItems: "flex-end",
    }}>
      {open && (
        <div
          data-docked-chat-panel="true"
          style={{
            width: 380,
            height: 520,
            marginBottom: 10,
            background: "rgba(16,16,18,0.96)",
            backdropFilter: "blur(14px)",
            border: "1px solid rgba(237,233,224,0.12)",
            borderRadius: 12,
            overflow: "hidden",
            display: "flex",
            flexDirection: "column",
            boxShadow: "0 30px 80px rgba(0,0,0,0.55)",
            animation: "bazSlideUp 220ms cubic-bezier(0.2, 0.8, 0.2, 1)",
          }}
        >
          <div style={{
            padding: "10px 16px",
            borderBottom: "1px solid rgba(237,233,224,0.08)",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            fontSize: 10,
            letterSpacing: "0.22em",
            textTransform: "uppercase",
            color: "rgba(237,233,224,0.5)",
          }}>
            <span>ask baz · live</span>
            <button
              onClick={onToggle}
              style={{
                background: "transparent",
                border: "none",
                color: "rgba(237,233,224,0.55)",
                cursor: "pointer",
                fontSize: 16,
                lineHeight: 1,
                padding: 2,
              }}
            >
              &times;
            </button>
          </div>
          <div style={{ flex: 1, minHeight: 0, padding: "4px 14px 12px" }}>
            <ChatPanel accent="#6EE7F4" tone="dark" compact />
          </div>
        </div>
      )}
      <button
        onClick={onToggle}
        style={{
          padding: "12px 18px",
          background: open ? "rgba(237,233,224,0.05)" : "#6EE7F4",
          color: open ? "#EDE9E0" : "#0A0A0B",
          border: open ? "1px solid rgba(237,233,224,0.15)" : "none",
          borderRadius: 999,
          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
          fontSize: 11,
          letterSpacing: "0.18em",
          textTransform: "uppercase",
          fontWeight: 600,
          cursor: "pointer",
          boxShadow: open ? "none" : "0 10px 30px rgba(110,231,244,0.28)",
          display: "flex",
          alignItems: "center",
          gap: 10,
          transition: "all 180ms ease",
          animation: open ? "none" : "bazPulseGlow 3s ease-in-out infinite",
        }}
      >
        <span style={{
          width: 7,
          height: 7,
          borderRadius: 999,
          background: open ? "#6EE7F4" : "#0A0A0B",
          boxShadow: open ? "0 0 10px #6EE7F4" : "none",
        }} />
        {open ? "minimize" : "ask me anything"}
      </button>
    </div>
  );
}

Object.assign(window, { Chrome, CommandPalette, DockedChat });
