/* ============================================================
   Hero — home

   Two modes, switchable from the Tweaks panel ("AIR-скролл"):

   · classic — the original single-screen composition: giant
     flanking А|Л, frosted chart, scroll affordance. The letters
     collapse into the top-centre monogram as you scroll out.

   · air — the aircenter.space-style PINNED scroll act. The chart
     background pins for the whole section while the content rides
     over it (parallax). A rotating tagline cycles through three
     statements, driven directly by scroll, with a numeric counter
     (01 / 03) + progress bar. A "+" card opens a detail popup on
     hover. The giant А|Л travels up and collapses across the pin.

   Reduced-motion always falls back to the classic single screen.
   ============================================================ */

const easeInOut = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
const lerp = (a, b, t) => a + (b - a) * t;
const clamp01 = (v) => Math.min(1, Math.max(0, v));

/* fixed, scroll-linked А|Л that collapses into a top-CENTER monogram */
function MorphLogo({ progress, dims, onHome, dark }) {
  const { W, H } = dims;
  const e = easeInOut(progress);
  // white while the logo sits over a dark area (hero / Results), black over the white sections
  const letterColor = dark ? "var(--paper-on-ink)" : "var(--ink)";

  const mob = W < 700;
  // start (hero, giant flanking letters) ⇢ end (small centred А|Л monogram, top centre)
  const startFS = Math.max(88, Math.min(mob ? 0.30 * W : 0.18 * W, 0.42 * H, 260));
  const endFS = mob ? 24 : 28;
  const fs = lerp(startFS, endFS, e);

  const xC = W / 2;
  const gap = mob ? 18 : 21;        // half-distance between А and Л centres when collapsed
  const yEnd = 36;
  const yA = lerp(0.5 * H, yEnd, e);
  const xA = lerp((mob ? 0.18 : 0.086) * W, xC - gap, e);
  const xL = lerp((mob ? 0.82 : 0.9) * W, xC + gap, e);
  const track = lerp(0.02, -0.01, e);

  const letter = (ch, x) => ({
    position: "fixed", left: x, top: yA, transform: "translate(-50%, -50%)",
    fontFamily: "var(--font-display)", fontWeight: 300, fontSize: fs,
    lineHeight: 0.8, letterSpacing: track + "em", color: letterColor,
    pointerEvents: "none", zIndex: 45, willChange: "left, top, font-size",
  });

  const collapsed = progress > 0.92;

  return (
    <React.Fragment>
      {/* А|Л text monogram — letterColor already flips to white over dark sections,
          so the collapsed mark stays the same size on black as on paper. */}
      <React.Fragment>
        <span style={letter("А", xA)}>А</span>
        {/* thin separator bar — fades in only as the monogram forms */}
        <span aria-hidden style={{
          position: "fixed", left: (xA + xL) / 2, top: yA, transform: "translate(-50%, -50%)",
          width: 1, height: lerp(0, 22, e), background: letterColor,
          opacity: Math.max(0, (progress - 0.62) / 0.38), pointerEvents: "none", zIndex: 45,
        }} />
        <span style={letter("Л", xL)}>Л</span>
      </React.Fragment>
      {/* invisible hit-area over the collapsed monogram → back to top */}
      <button aria-label="Наверх" onClick={onHome} style={{
        position: "fixed", left: xC, top: yEnd, transform: "translate(-50%, -50%)",
        width: 78, height: 40, border: "none", background: "transparent", padding: 0,
        cursor: "pointer", zIndex: 46, pointerEvents: collapsed ? "auto" : "none",
      }} />
    </React.Fragment>
  );
}

/* ---- scroll affordance with a rotating arrow (AIR btn--rotation) ---- */
function RotScroll({ onClick, light }) {
  const [hover, setHover] = React.useState(false);
  const stroke = light ? "var(--ink)" : "var(--paper-on-ink)";
  const border = light ? "var(--hairline-2)" : "rgba(250,250,248,0.28)";
  return (
    <button onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      aria-label="Листать дальше"
      style={{ width: 46, height: 46, borderRadius: 999, display: "grid", placeItems: "center",
        cursor: "pointer", background: hover ? (light ? "var(--surface)" : "rgba(250,250,248,0.10)") : "transparent",
        border: "1px solid " + border, transition: "background var(--dur) var(--ease)", overflow: "hidden" }}>
      <span style={{ display: "block", transition: "transform var(--dur-slow) var(--ease)",
        transform: hover ? "translateY(34px) rotate(-90deg)" : "translateY(0) rotate(0deg)" }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth="1.6"
          strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"
          style={{ display: "block" }}>
          <line x1="12" y1="5" x2="12" y2="19" /><polyline points="19 12 12 19 5 12" />
        </svg>
      </span>
    </button>
  );
}

/* ---- hover-expand card (AIR card-team popup) ---- */
function HoverPanelCard({ label, items, light }) {
  const [open, setOpen] = React.useState(false);
  const ink = light;
  const surface = ink ? "rgba(255,255,255,0.72)" : "rgba(16,17,19,0.42)";
  const txt = ink ? "var(--ink)" : "var(--paper-on-ink)";
  const sub = ink ? "var(--ink-2)" : "rgba(250,250,248,0.74)";
  const line = ink ? "var(--hairline-2)" : "rgba(250,250,248,0.18)";
  return (
    <div onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}
      style={{ position: "relative" }}>
      {/* popup */}
      <div style={{ position: "absolute", left: 0, bottom: "calc(100% + 10px)", width: 268,
        background: surface, backdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)",
        border: "1px solid " + line, borderRadius: 14, padding: "16px 18px",
        transformOrigin: "bottom left",
        opacity: open ? 1 : 0, transform: open ? "translateY(0) scale(1)" : "translateY(8px) scale(0.97)",
        pointerEvents: open ? "auto" : "none",
        transition: "opacity var(--dur) var(--ease), transform var(--dur) var(--ease)" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
          {items.map((it, i) => (
            <div key={i} style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: sub,
                fontVariantNumeric: "tabular-nums", flex: "0 0 auto", letterSpacing: "0.04em" }}>
                {String(i + 1).padStart(2, "0")}
              </span>
              <span style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, lineHeight: 1.35, color: txt }}>{it}</span>
            </div>
          ))}
        </div>
      </div>

      {/* trigger pill */}
      <button style={{ display: "inline-flex", alignItems: "center", gap: 12, height: 44, padding: "0 16px 0 18px",
        borderRadius: 999, cursor: "pointer", background: surface,
        backdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)",
        border: "1px solid " + line, color: txt,
        fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 11, letterSpacing: "0.16em",
        textTransform: "uppercase", transition: "background var(--dur) var(--ease)" }}>
        {label}
        <span style={{ width: 26, height: 26, borderRadius: 999, display: "grid", placeItems: "center",
          border: "1px solid " + line, transition: "transform var(--dur) var(--ease)",
          transform: open ? "rotate(135deg)" : "rotate(0deg)" }}>
          <Plus size={11} color={txt} weight={1.4} />
        </span>
      </button>
    </div>
  );
}

function Hero({ onContact, onNav, theme = "dark", air = true }) {
  const reduce = typeof window !== "undefined" && window.matchMedia
    && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const airOn = air && !reduce;

  const { t } = useT();
  const secRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0); // logo-collapse driver (0..1)
  const [p, setP] = React.useState(0);               // pin progress in air mode (0..1)
  const [dark, setDark] = React.useState(false);
  const [dims, setDims] = React.useState({ W: window.innerWidth, H: window.innerHeight });
  const themeRef = React.useRef(theme);
  themeRef.current = theme;
  const airRef = React.useRef(airOn);
  airRef.current = airOn;
  const light = theme === "light";

  React.useEffect(() => {
    let raf = 0;
    const compute = () => {
      raf = 0;
      const H = window.innerHeight;
      const sec = secRef.current;

      if (airRef.current && sec) {
        const rect = sec.getBoundingClientRect();
        const scrollable = Math.max(1, sec.offsetHeight - H);
        const pp = clamp01(-rect.top / scrollable);
        setP(pp);
        setProgress(pp);                 // letters collapse across the whole pin
      } else {
        const span = Math.max(1, H * 0.72);
        setProgress(clamp01(window.scrollY / span));
      }

      // is a dark area sitting under the top-left logo? (dark hero, or Results)
      let isDark = false;
      const home = document.querySelector('[data-screen-label="Home"]');
      if (home && themeRef.current !== "light") { const r = home.getBoundingClientRect(); if (r.bottom > 56) isDark = true; }
      document.querySelectorAll('[data-screen-label="Results"], [data-screen-label="Call"]').forEach((dk) => {
        const r = dk.getBoundingClientRect(); if (r.top <= 56 && r.bottom >= 26) isDark = true;
      });
      setDark(isDark);
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(compute); };
    const onResize = () => { setDims({ W: window.innerWidth, H: window.innerHeight }); compute(); };
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onResize);
    compute();
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onResize); cancelAnimationFrame(raf); };
  }, []);

  // re-evaluate when the theme or mode flips (without needing a scroll)
  React.useEffect(() => { window.dispatchEvent(new Event("scroll")); }, [theme, airOn]);

  const morph = (
    <MorphLogo progress={progress} dims={dims} dark={dark}
      onHome={() => window.scrollTo({ top: 0, behavior: "smooth" })} />
  );

  /* ---------------- CLASSIC (also reduced-motion) ---------------- */
  if (!airOn) {
    const fade = Math.max(0, 1 - progress * 1.6);
    return (
      <section ref={secRef} data-screen-label="Home" style={{ position: "relative", height: "100vh", minHeight: 600,
        background: light ? "#f1f1ef" : "#0a0b0d", overflow: "hidden" }}>
        <ChartField speed={0.7} frost={0.92} amp={0.9} density="mid" theme={theme} />
        <div style={{ position: "absolute", right: 28, bottom: 28, zIndex: 10,
          opacity: fade, pointerEvents: progress > 0.4 ? "none" : "auto", transition: "opacity 120ms linear" }}>
          <RotScroll light={light} onClick={() => onNav("method")} />
        </div>
        {morph}
      </section>
    );
  }

  /* ---------------- AIR pinned scroll act ---------------- */
  const roll = t("home.heroRoll") || [];
  const N = Math.max(1, roll.length);
  // The first stretch of the pin is a clean "classic" screen — just the giant
  // А|Л letters over the chart. The AIR roll (taglines, counter, progress bar,
  // hover card) fades in only once the user starts scrolling.
  const INTRO = 0.16;
  const airIn = easeInOut(clamp01(p / INTRO));        // 0 at rest → 1 once scrolling
  const q = clamp01((p - INTRO) / (1 - INTRO));       // roll progress after the intro
  const fp = q * (N - 1);
  const activeIdx = Math.min(N - 1, Math.max(0, Math.round(fp)));

  const lineColor = light ? "var(--ink)" : "var(--paper-on-ink)";
  const eyeColor = light ? "var(--ink-3)" : "rgba(250,250,248,0.62)";
  const barTrack = light ? "var(--hairline-2)" : "rgba(250,250,248,0.22)";
  const barFill = light ? "var(--ink)" : "var(--paper-on-ink)";
  const arrowFade = clamp01(1 - p * 2.4); // affordance retreats as you ride the pin

  // chart parallax — recedes & lifts a touch so the content rides over it
  const chartShift = { transform: `translateY(${-p * 7}vh) scale(${1 + p * 0.06})`, transformOrigin: "50% 40%",
    opacity: 1 - p * 0.18, transition: "none", willChange: "transform" };

  const stageItems = t("home.m2.rows");
  const cardItems = Array.isArray(stageItems)
    ? stageItems.slice(0, 4).map((r) => r.title)
    : ["Чтение рынка", "Smart Money", "Риск-менеджмент"];

  return (
    <section ref={secRef} data-screen-label="Home"
      style={{ position: "relative", height: "300vh",
        background: light ? "#f1f1ef" : "#0a0b0d" }}>

      {/* pinned viewport-height layer — everything rides on top of the chart */}
      <div style={{ position: "sticky", top: 0, height: "100vh", overflow: "hidden" }}>

        {/* parallax background */}
        <div style={{ position: "absolute", inset: 0, ...chartShift }}>
          <ChartField speed={0.7} frost={0.92} amp={0.9} density="mid" theme={theme} />
        </div>
        {/* readability veil that deepens slightly as content takes over */}
        <div style={{ position: "absolute", inset: 0, pointerEvents: "none",
          background: light
            ? `rgba(241,241,239,${0.10 + p * 0.20})`
            : `radial-gradient(120% 80% at 50% 46%, rgba(10,11,13,${0.18 + p * 0.30}) 0%, rgba(10,11,13,${0.34 + p * 0.30}) 100%)` }} />

        {/* rotating tagline stack — scroll-driven crossfade */}
        <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center",
          padding: "0 24px", zIndex: 8 }}>
          <div style={{ position: "relative", width: "min(900px, 92vw)", height: 240, textAlign: "center" }}>
            {roll.map((m, i) => {
              const d = fp - i;                       // <0 below (incoming), >0 above (outgoing)
              // each label fully fades out before the next begins: visible only within
              // |d| < 0.46, so adjacent labels never overlap (one clears, then the next arrives)
              const op = easeInOut(clamp01(1 - Math.abs(d) / 0.46)) * airIn;
              const ty = -d * 42;
              return (
                <div key={i} aria-hidden={i !== activeIdx} style={{ position: "absolute", inset: 0,
                  display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
                  gap: 22, opacity: op, transform: `translateY(${ty}px)`, willChange: "opacity, transform",
                  pointerEvents: i === activeIdx ? "auto" : "none" }}>
                  <span style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 12,
                    letterSpacing: "0.22em", textTransform: "uppercase", color: eyeColor }}>{m.eyebrow}</span>
                  <p style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 300,
                    fontSize: "clamp(30px, 5vw, 62px)", lineHeight: 1.06, letterSpacing: "-0.01em",
                    color: lineColor, whiteSpace: "pre-line", textWrap: "balance" }}>{m.line}</p>
                </div>
              );
            })}
          </div>
        </div>

        {/* bottom chrome: hover card (left) · counter + progress + arrow (right) */}
        <div style={{ position: "absolute", left: 0, right: 0, bottom: 28, zIndex: 12,
          padding: "0 28px", display: "flex", alignItems: "flex-end", justifyContent: "space-between",
          gap: 16, pointerEvents: "none" }}>

          <div style={{ pointerEvents: airIn > 0.5 ? "auto" : "none", opacity: airIn,
            transform: `translateY(${(1 - airIn) * 10}px)`, transition: "opacity 120ms linear" }}
            className="hero-hovercard">
            <HoverPanelCard label={t("home.heroCardLabel", "Что внутри")} items={cardItems} light={light} />
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 18, pointerEvents: "auto" }}>
            {/* counter + progress — only once the AIR act is riding */}
            <div style={{ display: "flex", alignItems: "center", gap: 18, opacity: airIn,
              transform: `translateY(${(1 - airIn) * 10}px)`, transition: "opacity 120ms linear",
              pointerEvents: "none" }}>
              {/* counter */}
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.06em",
                color: lineColor, fontVariantNumeric: "tabular-nums", display: "flex", alignItems: "center", gap: 7 }}>
                <span>{String(activeIdx + 1).padStart(2, "0")}</span>
                <span style={{ opacity: 0.5 }}>/</span>
                <span style={{ opacity: 0.5 }}>{String(N).padStart(2, "0")}</span>
              </div>
              {/* progress bar */}
              <div style={{ position: "relative", width: 90, height: 2, background: barTrack, borderRadius: 2,
                overflow: "hidden" }}>
                <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: (q * 100) + "%",
                  background: barFill, transition: "width 80ms linear" }} />
              </div>
            </div>
            {/* rotating arrow */}
            <div style={{ opacity: arrowFade, transition: "opacity 160ms linear",
              pointerEvents: arrowFade < 0.1 ? "none" : "auto" }}>
              <RotScroll light={light} onClick={() => onNav("method")} />
            </div>
          </div>
        </div>
      </div>

      {morph}
    </section>
  );
}

Object.assign(window, { Hero });
