// experience-shell.jsx — app-shell pieces that sit ABOVE either experience.
//
// ProfileMenu is the circular avatar in the top-right of both the Policy
// Owner and Producer Co-pilot experiences. Clicking it opens a small
// overlay with one action — "Switch Helm experience" — which returns the
// user to the experience selector. (More profile actions can be added here
// later.) The switch is performed via a global callback the RootApp
// registers on window, so deeply-nested headers in either experience can
// trigger it without prop-drilling.
//
// This lives in a file we own (not one of the Claude Design handoff files)
// so future design re-syncs of the experience screens don't clobber it.

const { useState: useShellState, useRef: useShellRef, useEffect: useShellEffect, useLayoutEffect: useShellLayoutEffect } = React;

const SwitchIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--helm-dark-green)"
    strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M16 3l4 4-4 4" />
    <path d="M20 7H9a5 5 0 0 0-5 5" />
    <path d="M8 21l-4-4 4-4" />
    <path d="M4 17h11a5 5 0 0 0 5-5" />
  </svg>
);

const ProfileMenu = ({
  initials = "—",
  bg = "var(--helm-dark-green)",
  fg = "var(--helm-white)",
  size = 36,
  name,
  subtitle,
  style,
}) => {
  const [open, setOpen] = useShellState(false);
  const btnRef = useShellRef(null);
  const [pos, setPos] = useShellState(null);

  // Anchor the popover to the avatar via fixed coordinates and render it in
  // a portal on <body>, so it floats above either experience's chrome
  // regardless of stacking contexts (e.g. the PO chat panel, which would
  // otherwise paint over a popover trapped inside the sticky nav).
  useShellLayoutEffect(() => {
    if (!open || !btnRef.current) return;
    const r = btnRef.current.getBoundingClientRect();
    setPos({ top: r.bottom + 10, right: Math.max(8, window.innerWidth - r.right) });
  }, [open]);

  // Close on scroll/resize so the floating popover never detaches from the avatar.
  useShellEffect(() => {
    if (!open) return;
    const close = () => setOpen(false);
    window.addEventListener("scroll", close, true);
    window.addEventListener("resize", close);
    return () => {
      window.removeEventListener("scroll", close, true);
      window.removeEventListener("resize", close);
    };
  }, [open]);

  const switchExperience = () => {
    setOpen(false);
    if (typeof window.__helmSwitchExperience === "function") {
      window.__helmSwitchExperience();
    }
  };
  return (
    <div style={{ position: "relative", flexShrink: 0, ...style }}>
      <button
        ref={btnRef}
        type="button"
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="menu"
        aria-expanded={open}
        title={name ? `${name} — account` : "Account"}
        style={{
          width: size, height: size, borderRadius: "50%",
          background: bg, color: fg,
          display: "grid", placeItems: "center", border: "none",
          cursor: "pointer", padding: 0, lineHeight: 1,
          fontFamily: "var(--font-sans)", fontWeight: 600,
          fontSize: Math.round(size * 0.36),
          boxShadow: open ? "0 0 0 3px rgba(0,29,0,0.12)" : "none",
          transition: "box-shadow 120ms ease",
        }}
      >
        {initials}
      </button>

      {open && pos && ReactDOM.createPortal(
        <>
          {/* click-away backdrop */}
          <div
            onClick={() => setOpen(false)}
            style={{ position: "fixed", inset: 0, zIndex: 100000, background: "transparent" }}
          />
          <div
            role="menu"
            style={{
              position: "fixed", top: pos.top, right: pos.right, zIndex: 100001,
              minWidth: 248, background: "var(--helm-white)",
              border: "1px solid var(--helm-dark-green)", borderRadius: 16,
              boxShadow: "4px 6px 0 0 var(--helm-dark-green)",
              padding: 8, fontFamily: "var(--font-sans)",
              animation: "helmProfileIn 140ms ease both",
            }}
          >
            <style>{`@keyframes helmProfileIn { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: translateY(0); } }`}</style>

            {(name || subtitle) && (
              <>
                <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "8px 10px 10px" }}>
                  <div style={{
                    width: 34, height: 34, borderRadius: "50%", background: bg, color: fg,
                    display: "grid", placeItems: "center", fontWeight: 600, fontSize: 13, flexShrink: 0,
                  }}>{initials}</div>
                  <div style={{ minWidth: 0 }}>
                    {name && <div style={{ fontWeight: 700, fontSize: 14, color: "var(--helm-dark-green)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</div>}
                    {subtitle && <div style={{ fontSize: 12, color: "var(--helm-dark-grey)", whiteSpace: "nowrap" }}>{subtitle}</div>}
                  </div>
                </div>
                <div style={{ height: 1, background: "var(--helm-dark-ecru)", margin: "0 4px 6px" }} />
              </>
            )}

            <button
              role="menuitem"
              type="button"
              onClick={switchExperience}
              style={{
                display: "flex", alignItems: "center", gap: 11, width: "100%",
                padding: "10px", borderRadius: 10, border: "none", background: "transparent",
                cursor: "pointer", textAlign: "left", color: "var(--helm-dark-green)",
                fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 14,
                transition: "background 120ms ease",
              }}
              onMouseEnter={(e) => (e.currentTarget.style.background = "var(--helm-ecru)")}
              onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
            >
              <span style={{
                width: 30, height: 30, borderRadius: 9, background: "var(--helm-lemon)",
                display: "grid", placeItems: "center", flexShrink: 0,
              }}>
                <SwitchIcon />
              </span>
              Switch Helm experience
            </button>
          </div>
        </>,
        document.body
      )}
    </div>
  );
};

Object.assign(window, { ProfileMenu });
