// Hero.jsx — полноэкранный первый экран: фуллбид фото гор, контент слева у края,
// текст прямо поверх изображения (без карточки). Высота — ровно во весь экран:
// отрицательный отступ под прозрачную шапку измеряется автоматически.
function RadioPlayer({ radio }) {
  const [hover, setHover] = React.useState(false);
  const playing = radio && radio.playing;
  const loading = radio && radio.loading;
  const errored = radio && radio.errored;
  const expanded = radio && radio.expanded;
  const effectiveVolume = radio ? radio.effectiveVolume : 1;
  const muted = radio ? radio.muted : false;
  const volume = radio ? radio.volume : 1;

  const statusText = errored
    ? "Не удалось подключиться"
    : playing
      ? "Прямой эфир"
      : loading
        ? "Подключаем эфир"
        : "Радио миссии";

  return (
    <div className="hero-radio-wrap" style={{ width: 392, display: "inline-flex", alignItems: "center", gap: 10, flex: "0 0 392px" }}>
      <div className={`hero-radio-pill${expanded ? " is-expanded" : ""}`} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{
          width: expanded ? 392 : 216, minHeight: 64, padding: expanded ? "8px 16px 8px 12px" : "8px 18px 8px 12px",
          borderRadius: 999, display: "inline-flex", alignItems: "center", justifyContent: expanded ? "space-between" : "flex-start", gap: expanded ? 10 : 8,
          color: "var(--cream)", border: "1.5px solid rgba(243,238,218,.45)",
          background: hover || playing ? "rgba(243,238,218,.18)" : "rgba(243,238,218,.10)",
          backdropFilter: "blur(8px)", WebkitBackdropFilter: "blur(8px)", boxShadow: "none",
          overflow: "hidden",
          transition: "width .34s cubic-bezier(.22,1,.36,1), padding .34s cubic-bezier(.22,1,.36,1), background .22s ease, border-color .22s ease",
        }}>
        <button className="hero-radio-main" type="button" onClick={radio ? radio.toggle : undefined}
          aria-label={playing || loading ? "Остановить радио" : "Слушать радио"}
          style={{
            fontFamily: "var(--font-ui)", fontWeight: 600, fontSize: 17, padding: 0,
            border: "none", borderRadius: 999, background: "transparent", color: "var(--cream)",
            cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 11,
            whiteSpace: "nowrap", flex: "none",
          }}>
          <span style={{ width: 40, height: 40, borderRadius: 999, display: "inline-flex", alignItems: "center",
            justifyContent: "center", background: playing ? "var(--terracotta)" : "rgba(243,238,218,.18)",
            boxShadow: playing ? "0 0 0 6px rgba(211,97,60,.24)" : "none", flex: "none" }}>
            <Icon name={playing || loading ? "pause" : "radio"} size={18} color="var(--cream)" strokeWidth={2} />
          </span>
          <span style={{ display: "inline-flex", flexDirection: "column", alignItems: "flex-start", gap: 2 }}>
            <span>{loading || playing ? "Остановить радио" : errored ? "Повторить" : "Слушать радио"}</span>
            <span className="hero-radio-status" style={{ display: "inline-flex", alignItems: "center", gap: 7,
              fontFamily: "var(--font-ui)", fontSize: 11.5, lineHeight: 1.1, fontWeight: 700,
              color: errored ? "#FFD6C8" : "rgba(243,238,218,.82)", textShadow: "0 1px 10px rgba(6,14,10,.48)",
              whiteSpace: "nowrap", pointerEvents: "none", opacity: 1 }}>
              <span aria-hidden="true" style={{ width: 7, height: 7, minWidth: 7, minHeight: 7, borderRadius: "50%",
                display: "inline-block", background: errored ? "#FFD6C8" : playing ? "var(--terracotta-bright)" : "rgba(243,238,218,.72)",
                boxShadow: playing ? "0 0 0 4px rgba(224,112,63,.18)" : "none",
                animation: playing ? "heroRadioPulse 1.8s ease-in-out infinite" : "none" }} />
              {statusText}
            </span>
          </span>
        </button>
        <div className="hero-volume-control" aria-label="Громкость радио" style={{ display: "inline-flex", alignItems: "center", gap: 7,
          height: 40, padding: "0 0 0 7px", color: "var(--cream)",
          borderLeft: "1px solid rgba(243,238,218,.24)",
          opacity: expanded ? 1 : 0, visibility: expanded ? "visible" : "hidden",
          pointerEvents: expanded ? "auto" : "none", transition: "opacity .24s ease .08s, visibility .24s ease .08s" }}>
          <button type="button" onClick={radio ? radio.toggleMute : undefined} tabIndex={expanded ? 0 : -1}
            aria-label={muted || volume === 0 ? "Включить звук" : "Выключить звук"}
            style={{ width: 28, height: 28, borderRadius: 999, border: "none", background: "transparent",
              color: "var(--cream)", padding: 0, display: "inline-flex", alignItems: "center",
              justifyContent: "center", cursor: "pointer", flex: "none" }}>
            <Icon name={muted || volume === 0 ? "volume-x" : "volume-2"} size={18} color="var(--cream)" strokeWidth={2} />
          </button>
          <span className="hero-volume-label" style={{ position: "absolute", width: 1, height: 1, padding: 0, margin: -1,
            overflow: "hidden", clip: "rect(0 0 0 0)", whiteSpace: "nowrap", border: 0 }}>Громкость радио</span>
          <input className="hero-volume-slider" type="range" min="0" max="100" step="1"
            value={Math.round(effectiveVolume * 100)} onChange={radio ? radio.changeVolume : undefined} aria-label="Громкость радио"
            tabIndex={expanded ? 0 : -1}
            style={{ width: 62, accentColor: "var(--terracotta-bright)", cursor: "pointer" }} />
        </div>
      </div>
    </div>
  );
}

function Hero({ onNav, radio }) {
  const [headerH, setHeaderH] = React.useState(72);
  React.useEffect(() => {
    const measure = () => {
      const h = document.querySelector("header");
      if (h) setHeaderH(h.offsetHeight);
    };
    measure();
    window.addEventListener("resize", measure);
    const t = setTimeout(measure, 300); // после загрузки шрифтов
    return () => { window.removeEventListener("resize", measure); clearTimeout(t); };
  }, []);

  React.useEffect(() => {
    const setViewportHeight = () => {
      const h = window.visualViewport ? window.visualViewport.height : window.innerHeight;
      document.documentElement.style.setProperty("--hero-viewport-height", `${Math.round(h)}px`);
    };
    setViewportHeight();
    window.addEventListener("resize", setViewportHeight);
    if (window.visualViewport) window.visualViewport.addEventListener("resize", setViewportHeight);
    return () => {
      window.removeEventListener("resize", setViewportHeight);
      if (window.visualViewport) window.visualViewport.removeEventListener("resize", setViewportHeight);
    };
  }, []);

  return (
    <section style={{ position: "relative", height: "var(--hero-viewport-height, 100svh)", minHeight: "100svh", display: "flex",
      alignItems: "flex-end", overflow: "hidden", marginTop: -headerH /* под прозрачную шапку */ }}>
      <div aria-hidden="true" style={{ position: "absolute", inset: 0,
        background: "url(../../assets/hero-main.png) center top / cover",
        animation: "heroBreathe 24s ease-in-out infinite", willChange: "transform" }} />
      {/* живой тёплый свет — мягко «дышит» */}
      <div aria-hidden="true" data-hero-glow style={{ position: "absolute", inset: 0, pointerEvents: "none",
        background: "radial-gradient(60% 50% at 72% 22%, rgba(255,214,160,.5), rgba(255,214,160,0) 70%)",
        animation: "heroGlow 9s ease-in-out infinite", willChange: "opacity, transform" }} />
      {/* верхний wash — под прозрачную навигацию */}
      <div style={{ position: "absolute", inset: 0,
        background: "linear-gradient(to bottom, rgba(6,14,10,.46) 0%, rgba(6,14,10,.22) 16%, rgba(8,20,16,0) 40%, rgba(8,18,14,.74) 100%)" }} />
      {/* левый скрим — читаемость текста */}
      <div style={{ position: "absolute", inset: 0,
        background: "linear-gradient(to right, rgba(8,18,14,.5) 0%, rgba(8,18,14,.12) 42%, rgba(8,18,14,0) 66%)" }} />

      <div style={{ position: "relative", width: "100%", boxSizing: "border-box",
        display: "flex", flexDirection: "column", alignItems: "flex-start",
        padding: "0 40px clamp(40px, 6vh, 64px) clamp(24px, 5vw, 64px)" }}>
        <div style={{ maxWidth: 720 }}>
          <h1 className="hero-rise hero-title" style={{ fontFamily: "var(--font-display)", fontWeight: 700,
            color: "var(--cream)", margin: "0 0 18px", letterSpacing: 0, animationDelay: ".1s",
            textShadow: "0 3px 28px rgba(6,14,10,.58)", textTransform: "uppercase" }}>
            Северо-<br />Осетинская<br />миссия
          </h1>
          <p className="hero-rise" style={{ fontFamily: "var(--font-ui)", fontSize: 19, lineHeight: 1.6,
            color: "rgba(243,238,218,.94)", margin: 0, textWrap: "pretty", animationDelay: ".22s",
            textShadow: "0 1px 16px rgba(6,14,10,.55)" }}>
            Наша миссия — возвещать Христа и служить людям Северной Осетии.
          </p>

          <div className="hero-rise hero-cta-row" style={{ display: "flex", gap: 14, flexWrap: "wrap", marginTop: 30, animationDelay: ".34s" }}>
            <Button variant="primary" size="lg" iconRight="arrow-right" onClick={() => onNav("О миссии")}>О нашей миссии</Button>
            <RadioPlayer radio={radio} />
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, RadioPlayer });
