/* Header + Hero (v4: air + smooth groove-field + logo-cursor) + Ticker */

const Header = ({ onCta }) =>
<header className="hdr">
    <div className="wrap hdr-inner">
      <a href="#top" className="brand" aria-label="Вкусноты">
        <Mark />
        <span>Вкусноты</span>
      </a>
      <nav className="nav" aria-label="Главное меню">
        <a href="#product">Продукт</a>
        <a href="#scenarios">Сценарии</a>
        <a href="#queue">Очередь</a>
        <a href="#investors">Инвесторам</a>
        <a href="#apply">Заявка</a>
      </nav>
      <div className="hdr-cta">
        <span className="lang">RU</span>
        <button className="btn sm acid" onClick={() => onCta("regular")}>
          Занять слот <Arrow size={12} dir="down" />
        </button>
      </div>
    </div>
  </header>;


const Ticker = () => {
  const items = [
  "ЗАКРЫТЫЙ ЗАПУСК",
  "УНИКАЛЬНЫЙ ВКУС",
  "ВЫБРАННЫЙ ВАМИ ЦВЕТ",
  "Ограниченные слоты",
  "МОСКВА И САНКТ-ПЕТЕРБУРГ",
  "R&D — пилотные партии",
  "Слот в очередь",
  "Edible · Music · Drop"];

  const doubled = [...items, ...items];
  return (
    <div className="ticker" aria-hidden="true">
      <div className="ticker-track">
        {doubled.map((t, i) => <span key={i}>{t}</span>)}
      </div>
    </div>);

};

/* Поле карамельных дорожек — точный порт анимации из версии «НА ЯЗЫК»:
   дорожки расступаются вокруг иглы, дорожка под иглой играет оранжевым,
   без указателя игла сама едет по пластинке.
   Единственное отличие: игла — не точка, а знак Вкуснот (медленно вращается). */
const Hero = ({ onCta }) => {
  const secRef = React.useRef(null);
  const cvRef = React.useRef(null);

  React.useEffect(() => {
    const sec = secRef.current, cv = cvRef.current;
    if (!sec || !cv) return;
    let reduce = false;
    try { reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches; } catch (e) {}
    const ctx = cv.getContext("2d");
    if (!ctx) { sec.classList.add("no-canvas"); return; }

    const DPR = Math.min(window.devicePixelRatio || 1, 2);
    let W = 0, H = 0, CX = 0, CY = 0, maxR = 0;
    let rings = [];
    const RING_STEP = 14;
    const INFL = 170; /* радиус влияния иглы */
    const PUSH = 30;  /* максимальный сдвиг дорожки */
    const pointer = { x: -9999, y: -9999 };
    const target = { x: -9999, y: -9999 };
    let lastInput = -1e9, raf = 0;
    const t0 = performance.now();
    const now = () => performance.now() - t0;

    const resize = () => {
      W = sec.clientWidth || 1;
      H = sec.clientHeight || 1;
      cv.width = Math.round(W * DPR);
      cv.height = Math.round(H * DPR);
      cv.style.width = W + "px";
      cv.style.height = H + "px";
      ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
      CX = W > 720 ? W * 0.72 : W * 0.5;
      CY = W > 720 ? H * 0.42 : H * 0.34;
      const dx = Math.max(CX, W - CX), dy = Math.max(CY, H - CY);
      maxR = Math.sqrt(dx * dx + dy * dy);
      rings = [];
      let i = 0;
      for (let r = 78; r < maxR; r += RING_STEP) {
        /* неровная яркость дорожек — живая карамель, не сетка */
        let a = 0.045 + 0.035 * (0.5 + 0.5 * Math.sin(i * 2.4));
        if (i % 6 === 0) a += 0.05;
        rings.push({ r, a });
        i++;
      }
    };

    /* игла = знак Вкуснот: три волнистых кольца + точка */
    const MK = [
      { base: 4.1, amp: 1.0, w: 1.9, o: 0.95 },
      { base: 8.1, amp: 1.25, w: 1.4, o: 0.74 },
      { base: 12, amp: 1.5, w: 1.4, o: 0.53 }];

    const drawMark = (px, py, rot) => {
      ctx.lineJoin = "round";
      for (const m of MK) {
        ctx.beginPath();
        for (let s = 0; s <= 48; s++) {
          const a = (s / 48) * 6.2832;
          const r = m.base + Math.sin(a * 7) * m.amp;
          const x = px + Math.cos(a + rot) * r, y = py + Math.sin(a + rot) * r;
          s === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
        }
        ctx.closePath();
        ctx.strokeStyle = "rgba(236,113,46," + m.o + ")";
        ctx.lineWidth = m.w;
        ctx.stroke();
      }
      ctx.beginPath();
      ctx.fillStyle = "rgba(236,113,46,.95)";
      ctx.arc(px, py, 1.9, 0, 6.2832);
      ctx.fill();
    };

    const drawStatic = () => {
      ctx.clearRect(0, 0, W, H);
      for (const ring of rings) {
        ctx.beginPath();
        ctx.strokeStyle = "rgba(244,233,220," + ring.a.toFixed(3) + ")";
        ctx.lineWidth = 1;
        ctx.arc(CX, CY, ring.r, 0, Math.PI * 2);
        ctx.stroke();
      }
    };

    const frame = () => {
      raf = requestAnimationFrame(frame);
      const t = now() / 1000;

      /* автопилот: игла сама едет по дорожкам, пока нет указателя */
      if (now() - lastInput > 2600) {
        const ang = t * 0.22;
        const orbit = Math.min(W, H) * 0.30 + Math.sin(t * 0.5) * 34;
        target.x = CX + Math.cos(ang) * orbit;
        target.y = CY + Math.sin(ang) * orbit * 0.86;
      }
      if (pointer.x < -999) { pointer.x = target.x; pointer.y = target.y; }
      pointer.x += (target.x - pointer.x) * 0.1;
      pointer.y += (target.y - pointer.y) * 0.1;

      const pdx = pointer.x - CX, pdy = pointer.y - CY;
      const needleR = Math.sqrt(pdx * pdx + pdy * pdy);

      ctx.clearRect(0, 0, W, H);

      for (const ring of rings) {
        const wob = Math.sin(t * 0.7 + ring.r * 0.021) * 1.7;
        const r = ring.r + wob;
        const nearNeedle = Math.abs(r - needleR) < INFL + 26;
        const playing = Math.abs(r - needleR) < RING_STEP * 0.55;

        if (playing) {
          /* дорожка под иглой — играет */
          ctx.beginPath();
          ctx.strokeStyle = "rgba(236,113,46,.16)";
          ctx.lineWidth = 6;
          ctx.arc(CX, CY, r, 0, Math.PI * 2);
          ctx.stroke();
          ctx.beginPath();
          ctx.strokeStyle = "rgba(236,113,46,.85)";
          ctx.lineWidth = 1.7;
        } else {
          ctx.beginPath();
          ctx.strokeStyle = "rgba(244,233,220," + ring.a.toFixed(3) + ")";
          ctx.lineWidth = 1;
        }

        if (!nearNeedle) {
          /* далеко от иглы — быстрая идеальная окружность */
          ctx.arc(CX, CY, r, 0, Math.PI * 2);
          ctx.stroke();
          continue;
        }

        /* рядом с иглой — дорожка гнётся, вершины расступаются */
        const steps = Math.max(60, Math.min(200, Math.round(r * 0.5)));
        const da = (Math.PI * 2) / steps;
        for (let s = 0; s <= steps; s++) {
          const a2 = s * da;
          let x = CX + Math.cos(a2) * r;
          let y = CY + Math.sin(a2) * r;
          const ddx = x - pointer.x, ddy = y - pointer.y;
          const d = Math.sqrt(ddx * ddx + ddy * ddy);
          if (d < INFL && d > 0.001) {
            const f = 1 - d / INFL;
            const push = f * f * PUSH;
            x += (ddx / d) * push;
            y += (ddy / d) * push;
          }
          s === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
        }
        ctx.stroke();
      }

      /* игла — знак Вкуснот */
      drawMark(pointer.x, pointer.y, t * 0.4);
    };

    const onMove = (x, y) => {
      const rect = sec.getBoundingClientRect();
      target.x = x - rect.left;
      target.y = y - rect.top;
      lastInput = now();
    };
    const onMouse = (e) => onMove(e.clientX, e.clientY);
    const onTouch = (e) => { if (e.touches && e.touches.length) onMove(e.touches[0].clientX, e.touches[0].clientY); };
    const onResize = () => { resize(); if (reduce) drawStatic(); };

    window.addEventListener("resize", onResize);
    sec.addEventListener("mousemove", onMouse);
    sec.addEventListener("touchmove", onTouch, { passive: true });

    resize();
    if (reduce) {
      drawStatic();
    } else {
      raf = requestAnimationFrame(frame);
    }
    const io = !reduce && "IntersectionObserver" in window ? new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (e.isIntersecting && !raf) raf = requestAnimationFrame(frame);
        else if (!e.isIntersecting && raf) { cancelAnimationFrame(raf); raf = 0; }
      });
    }, { threshold: 0.04 }) : null;
    if (io) io.observe(sec);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", onResize);
      sec.removeEventListener("mousemove", onMouse);
      sec.removeEventListener("touchmove", onTouch);
      if (io) io.disconnect();
    };
  }, []);

  return (
    <section className="hero hero-v4" id="top" ref={secRef}>
      <canvas className="hero-canvas" ref={cvRef} aria-hidden="true"></canvas>

      <div className="wrap hero-air">
        <h1 className="hero-headline">Вкус<span className="accent">ноты</span></h1>
        <p className="hero-slogan">Любимый трек теперь <span className="accent">со&nbsp;вкусом</span> и&nbsp;<span className="accent">цветом</span></p>
        <p className="hero-sub">
          Съедобные музыкальные пластинки&nbsp;— инновационный инструмент продвижения ваших треков.
        </p>
        <div className="hero-ctarow">
          <button className="btn acid" onClick={() => onCta("regular")}>
            Встать в очередь <Arrow />
          </button>
          <button className="btn ghost" onClick={() => onCta("priority")}>
            Приоритетный слот
          </button>
          <a className="quiet" href="#investors" onClick={(e) => {e.preventDefault();onCta("investor");}}>
            Инвесторам →
          </a>
        </div>
      </div>

      <div className="wrap hero-specstrip">
        <span className="s"><span className="k">Формат</span> <b>12″ · 7″</b></span>
        <span className="sep">/</span>
        <span className="s"><span className="k">Тираж</span> <b>по брифу</b></span>
        <span className="sep">/</span>
        <span className="s"><span className="k">Вкус и цвет</span> <b>кастом</b></span>
        <span className="sep">/</span>
        <span className="s"><span className="k">Срок</span> <b>от даты релиза</b></span>
        <span className="sep">/</span>
        <span className="s"><span className="k">Канал</span> <b>B2B</b></span>
      </div>
    </section>);

};

Object.assign(window, { Header, Ticker, Hero });

