// Header.jsx — шапка с навигацией. Прозрачная поверх фото, кремовая при скролле.
// Десктоп: только графический знак (без текста). Мобайл: двухлинейный бургер справа
// + полноэкранное меню, раскрывающееся сверху вниз и закрывающееся по клику на пункт.
const NAV = ["О миссии", "Служение", "Где мы служим", "Медиа", "Подписка", "Новости", "Контакты"];

function HeaderRadioPlayer({ radio, overPhoto, compact = false }) {
  if (!radio) return null;
  const active = radio.playing || radio.loading;
  const fg = overPhoto ? "var(--cream)" : "var(--ink)";
  const border = overPhoto ? "rgba(243,238,218,.42)" : "rgba(1,65,56,.16)";
  const bg = active
    ? (overPhoto ? "rgba(243,238,218,.16)" : "rgba(211,97,60,.10)")
    : (overPhoto ? "rgba(243,238,218,.08)" : "rgba(1,65,56,.06)");
  const status = radio.playing ? "Прямой эфир" : radio.loading ? "Подключаем" : "Радио";
  const playerWidth = active ? 156 : 144;

  return (
    <div className={compact ? "header-radio-mobile" : "kit-header-radio"} style={{
      width: compact ? "100%" : playerWidth,
      display: "inline-flex", alignItems: "center", gap: 8,
      boxSizing: "border-box",
      padding: compact ? "10px 12px" : "6px 10px 6px 7px",
      borderRadius: 999, border: "1px solid " + border, background: bg,
      color: fg, transition: "all .22s ease",
      backdropFilter: overPhoto ? "blur(8px)" : "none", WebkitBackdropFilter: overPhoto ? "blur(8px)" : "none",
    }}>
      <button type="button" onClick={radio.toggle}
        aria-label={active ? "Остановить радио" : "Слушать радио"}
        style={{ width: compact ? 38 : 30, height: compact ? 38 : 30, borderRadius: 999, border: "none",
          background: active ? "var(--terracotta)" : (overPhoto ? "rgba(243,238,218,.14)" : "rgba(1,65,56,.08)"),
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          cursor: "pointer", color: "var(--cream)", flex: "none" }}>
        <Icon name={active ? "pause" : "radio"} size={compact ? 18 : 15} color={active || overPhoto ? "var(--cream)" : "var(--terracotta)"} strokeWidth={2} />
      </button>
      <span style={{ display: "inline-flex", flexDirection: "column", gap: 1, minWidth: compact ? 0 : 74 }}>
        <span style={{ fontFamily: "var(--font-ui)", fontSize: compact ? 14.5 : 12.5, fontWeight: 700,
          lineHeight: 1.05, whiteSpace: "nowrap", color: fg }}>
          {active ? "Радио" : "Слушать"}
        </span>
        <span style={{ fontFamily: "var(--font-ui)", fontSize: compact ? 12.5 : 11.5,
          lineHeight: 1.1, whiteSpace: "nowrap", color: overPhoto ? "rgba(243,238,218,.78)" : "var(--stone)" }}>
          {status}
        </span>
      </span>
      {active && !compact && (
        <span aria-hidden="true" style={{ width: 7, height: 7, minWidth: 7, minHeight: 7, flex: "0 0 7px",
          borderRadius: "50%", display: "inline-block",
          background: "var(--terracotta-bright)", boxShadow: "0 0 0 4px rgba(224,112,63,.18)",
          animation: "radioPulse 1.8s ease-in-out infinite" }} />
      )}
    </div>
  );
}

function Header({ active, onNav, scrolled, onPhoto, forceSolid, newsHidden = true, radio }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [isMobile, setIsMobile] = React.useState(() => window.innerWidth <= 720);
  const navItems = React.useMemo(
    () => NAV.filter((item) => !(newsHidden && item === "Новости")),
    [newsHidden]
  );

  React.useEffect(() => {
    const mq = window.matchMedia("(max-width: 720px)");
    const sync = () => setIsMobile(mq.matches);
    sync();
    mq.addEventListener("change", sync);
    return () => mq.removeEventListener("change", sync);
  }, []);

  const overPhoto = !forceSolid && !scrolled && (onPhoto || (isMobile && active !== "Главная"));
  const fg = overPhoto ? "var(--cream)" : "var(--ink)";
  const logoColor = overPhoto ? "var(--cream)" : "var(--terracotta)";
  const activeColor = overPhoto ? "var(--cream)" : "var(--terracotta)";
  const hoverColor = overPhoto ? "#fff" : "var(--terracotta)";
  const mutedOpacity = overPhoto ? 0.92 : 0.85;
  const showHeaderRadio = !(active === "Главная" && !scrolled);
  const headerRadioSlotWidth = showHeaderRadio ? ((radio && (radio.playing || radio.loading)) ? 164 : 152) : 0;

  const go = (item) => { onNav(item); setMenuOpen(false); };

  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 1100,
      background: overPhoto ? "transparent" : "rgba(243,238,218,.86)",
      backdropFilter: overPhoto ? "none" : "blur(14px)",
      WebkitBackdropFilter: overPhoto ? "none" : "blur(14px)",
      borderBottom: "1px solid " + (overPhoto ? "transparent" : "var(--line)"),
      transition: "all .3s cubic-bezier(.22,1,.36,1)",
    }}>
      <style>{`
        @keyframes menuDown { from { transform: translateY(-100%); } to { transform: translateY(0); } }
        @keyframes radioPulse { 0%, 100% { box-shadow: 0 0 0 4px rgba(224,112,63,.18); } 50% { box-shadow: 0 0 0 7px rgba(224,112,63,.08); } }
      `}</style>
      <div style={{ width: "100%", boxSizing: "border-box", padding: "14px clamp(24px, 5vw, 64px)",
        display: "flex", alignItems: "center", gap: 28 }}>
        {/* Только знак, без текста */}
        <div onClick={() => onNav("Главная")} style={{ cursor: "pointer", display: "flex",
          alignItems: "center" }} aria-label="На главную">
          <Logomark color={logoColor} width={52} />
        </div>

        <nav style={{ display: "flex", gap: 4, marginLeft: "auto", flexWrap: "nowrap" }} className="kit-nav">
          {navItems.map((item) => {
            const on = active === item;
            return (
              <button key={item} onClick={() => onNav(item)} style={{
                fontFamily: "var(--font-ui)", fontWeight: on ? 600 : 500, fontSize: 14.5,
                color: on ? activeColor : fg,
                background: "transparent", border: "none", cursor: "pointer", padding: "8px 12px",
                borderRadius: 8, opacity: on ? 1 : mutedOpacity,
                textShadow: overPhoto ? "0 1px 18px rgba(0,0,0,.42)" : "none",
                transition: "color .28s cubic-bezier(.22,1,.36,1), opacity .28s ease, text-shadow .28s ease",
                whiteSpace: "nowrap",
              }}
              onMouseEnter={(e) => { e.currentTarget.style.opacity = 1; e.currentTarget.style.color = hoverColor; }}
              onMouseLeave={(e) => { if (!on) { e.currentTarget.style.opacity = mutedOpacity; e.currentTarget.style.color = fg; } }}>
                {item}
              </button>
            );
          })}
        </nav>

        <div className="kit-header-radio-slot" style={{
          display: "inline-flex",
          width: headerRadioSlotWidth,
          marginLeft: showHeaderRadio ? 0 : -28,
          overflow: "hidden",
          opacity: showHeaderRadio ? 1 : 0,
          transform: showHeaderRadio ? "translateX(0) scale(1)" : "translateX(12px) scale(.96)",
          transformOrigin: "right center",
          pointerEvents: showHeaderRadio ? "auto" : "none",
          transition: "width .34s cubic-bezier(.22,1,.36,1), margin-left .34s cubic-bezier(.22,1,.36,1), opacity .24s ease .06s, transform .34s cubic-bezier(.22,1,.36,1)",
        }}>
          <HeaderRadioPlayer radio={radio} overPhoto={overPhoto} />
        </div>

        <div className="kit-cta">
          <Button variant="primary" size="sm"
            icon="heart" onClick={() => onNav("Поддержать")}>Поддержать</Button>
        </div>

        {/* Бургер из двух линий, прижат вправо */}
        <button className="kit-burger" aria-label="Меню" onClick={() => setMenuOpen(true)} style={{
          display: "none", marginLeft: "auto", background: "transparent", border: "none",
          cursor: "pointer", padding: 8, width: 44, height: 44, alignItems: "center", justifyContent: "center",
        }}>
          <span style={{ display: "flex", flexDirection: "column", gap: 7, width: 26 }}>
            <span style={{ height: 2.5, borderRadius: 2, background: fg, transition: "background .28s cubic-bezier(.22,1,.36,1)" }} />
            <span style={{ height: 2.5, borderRadius: 2, background: fg, transition: "background .28s cubic-bezier(.22,1,.36,1)" }} />
          </span>
        </button>
      </div>

      {/* Полноэкранное мобильное меню — портал в body, чтобы backdrop-filter шапки
          не превращал её в контейнер для position:fixed (из-за этого меню «обрезалось») */}
      {menuOpen && ReactDOM.createPortal(
        <div style={{ position: "fixed", inset: 0, zIndex: 2000, background: "var(--cream)",
          display: "flex", flexDirection: "column", animation: "menuDown .32s cubic-bezier(.22,1,.36,1)" }}>
          <style>{`@keyframes menuDown { from { transform: translateY(-100%); } to { transform: translateY(0); } }`}</style>
          <div style={{ display: "flex", alignItems: "center", padding: "14px 24px",
            borderBottom: "1px solid var(--line)" }}>
            <div onClick={() => go("Главная")} style={{ cursor: "pointer", display: "flex", alignItems: "center" }}>
              <Logomark color="var(--terracotta)" width={48} />
            </div>
            <button aria-label="Закрыть" onClick={() => setMenuOpen(false)} style={{
              marginLeft: "auto", background: "transparent", border: "none", cursor: "pointer",
              width: 44, height: 44, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink)",
            }}><Icon name="x" size={28} color="var(--ink)" /></button>
          </div>

          <nav style={{ flex: 1, display: "flex", flexDirection: "column", padding: "12px 0", overflowY: "auto" }}>
            {navItems.map((item) => (
              <button key={item} onClick={() => go(item)} style={{
                display: "flex", alignItems: "center", justifyContent: "space-between",
                width: "100%", textAlign: "left", padding: "18px 28px",
                fontFamily: "var(--font-display)", fontSize: 24, fontWeight: 600, letterSpacing: "-.01em",
                color: active === item ? "var(--terracotta)" : "var(--ink)",
                background: "transparent", border: "none", borderBottom: "1px solid var(--line)", cursor: "pointer",
              }}>
                {item}
                <Icon name="arrow-right" size={20} color={active === item ? "var(--terracotta)" : "var(--stone-soft)"} />
              </button>
            ))}
          </nav>

          <div style={{ padding: "20px 28px 28px" }}>
            <Button variant="primary" size="lg" icon="heart"
              style={{ width: "100%", justifyContent: "center" }}
              onClick={() => go("Поддержать")}>Поддержать служение</Button>
          </div>
        </div>,
        document.body
      )}
    </header>
  );
}

Object.assign(window, { Header, HeaderRadioPlayer, NAV });
