// hero.jsx — Hero + анимированная инфографика круговорота

const { useEffect, useRef, useState } = React;

// useInView — простой хук, чтобы стартовать анимацию при появлении
function useInView(threshold = 0.15) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current || seen) return;
    // First, check if element is already in view on mount (e.g. hero above the fold)
    const rect = ref.current.getBoundingClientRect();
    const vh = window.innerHeight || 800;
    if (rect.top < vh && rect.bottom > 0) {
      setSeen(true);
      return;
    }
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {setSeen(true);io.disconnect();}
    }, { threshold });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [seen, threshold]);
  return [ref, seen];
}
window.useInView = useInView;

function CycleDiagram() {
  // Анимированный круговорот: 4 узла на окружности, вращается медленно
  const nodes = [
  { label: "Очистки", sub: "0,5–1 кг / сутки", angle: -90, color: "var(--accent)" },
  { label: "Черви", sub: "Eisenia fetida", angle: 0, color: "var(--accent-2)" },
  { label: "Биогумус", sub: "Премиум-удобрение", angle: 90, color: "var(--accent)" },
  { label: "Урожай", sub: "+25–40% к норме", angle: 180, color: "var(--accent-2)" }];

  return (
    <div className="cycle-wrap" aria-label="Круговорот ЭкоКруг">
      <svg viewBox="-200 -200 400 400" className="cycle-svg" aria-hidden="true">
        <defs>
          <marker id="cycle-arrow" viewBox="0 0 10 10" refX="6" refY="5"
          markerWidth="6" markerHeight="6" orient="auto-start-reverse">
            <path d="M 0 0 L 10 5 L 0 10 z" fill="currentColor" />
          </marker>
        </defs>
        {/* Внешний пунктирный круг */}
        <circle r="160" fill="none" stroke="currentColor" strokeWidth="0.5"
        strokeDasharray="2 6" opacity="0.35" className="cycle-outer" />
        {/* Основной круг со стрелкой */}
        <g className="cycle-arc" style={{ color: "var(--accent)" }}>
          <circle r="140" fill="none" stroke="currentColor" strokeWidth="1.25" opacity="0.9" />
          <path d="M 140 0 A 140 140 0 0 1 138.9 8.4" fill="none" stroke="currentColor"
          strokeWidth="2.5" markerEnd="url(#cycle-arrow)" />
        </g>
        {/* Внутренний круг с лого-точкой */}
        <circle r="48" fill="var(--bg-card)" stroke="var(--line)" strokeWidth="1" />
        <g transform="translate(-20 -8)" style={{ color: "var(--ink)" }}>
          <text x="20" y="0" textAnchor="middle"
          style={{
            font: "500 14px var(--f-display)",
            letterSpacing: "0.04em",
            fill: "currentColor",
            textTransform: "uppercase",
            fontFamily: "var(--f-mono)",
            fontSize: "9px"
          }}>
            ЦИКЛ
          </text>
          <text x="20" y="18" textAnchor="middle"
          style={{
            font: "500 22px var(--f-display)",
            fill: "currentColor"
          }}>
            ЭкоКруг
          </text>
        </g>
      </svg>

      {/* HTML-узлы поверх SVG — для нормальной типографики */}
      {nodes.map((n, i) => {
        const rad = n.angle * Math.PI / 180;
        const x = 50 + 44 * Math.cos(rad);
        const y = 50 + 44 * Math.sin(rad);
        return (
          <div
            key={n.label}
            className="cycle-node"
            style={{
              left: `${x}%`,
              top: `${y}%`,
              animationDelay: `${i * 0.18}s`
            }}>

            <div className="cycle-dot" style={{ background: n.color }} />
            <div className="cycle-label">{n.label}</div>
            <div className="cycle-sub">{n.sub}</div>
          </div>);

      })}
    </div>);

}
window.CycleDiagram = CycleDiagram;

function StatCounter({ to, suffix = "", duration = 1400, decimals = 0, delay = 0 }) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const [started, setStarted] = useState(false);

  useEffect(() => {
    if (started || !ref.current) return;
    const el = ref.current;
    const start = () => {
      if (started) return;
      setStarted(true);
    };
    const rect = el.getBoundingClientRect();
    const vh = window.innerHeight || 800;
    // Already visible? Start now.
    if (rect.top < vh + 200 && rect.bottom > -200) {
      const t = setTimeout(start, delay);
      return () => clearTimeout(t);
    }
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {start();io.disconnect();}
    }, { threshold: 0.1 });
    io.observe(el);
    return () => io.disconnect();
  }, [started, delay]);

  useEffect(() => {
    if (!started) return;
    const t0 = performance.now();
    let raf;
    const step = (t) => {
      const p = Math.min(1, (t - t0) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(to * eased);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [started, to, duration]);

  const formatted = decimals ?
  val.toFixed(decimals) :
  Math.round(val).toLocaleString("ru-RU");
  return <span ref={ref}>{formatted}{suffix}</span>;
}
window.StatCounter = StatCounter;

function Hero({ heroTitle, heroSub, logoVariant }) {
  const [ref, seen] = useInView(0);
  return (
    <section className="hero" id="top">
      <div className="wrap">
        <div className="hero-grid">
          <div ref={ref} className={`hero-copy reveal ${seen ? "in" : ""}`}>
            <div className="eyebrow">домашняя вермиферма · ekokrug.ru</div>
            <h1 className="display h1" style={{ whiteSpace: "pre-line" }}>
              {heroTitle}
            </h1>
            <p className="lead" style={{ maxWidth: "44ch" }}>
              {heroSub}
            </p>
            <div className="hero-cta">
              <a href="#products" className="btn btn-primary">
                Заказать за 9 900 ₽
                <span className="arrow">→</span>
              </a>
              <a href="#how" className="btn btn-ghost">
                Как это работает
              </a>
            </div>

            <div className="hero-stats">
              <div className="hero-stat">
                <div className="n"><StatCounter to={40} suffix="%" /></div>
                <div className="l">меньше мусора от семьи</div>
              </div>
              <div className="hero-stat">
                <div className="n">×<StatCounter to={6} /></div>
                <div className="l">эффективнее навоза</div>
              </div>
              <div className="hero-stat">
                <div className="n"><StatCounter to={9900} /><span style={{ fontSize: "0.55em", marginLeft: 4 }}>₽</span></div>
                <div className="l">комплект с поддержкой</div>
              </div>
            </div>
          </div>

          <div className="hero-art-col">
            <div className="hero-product-stack">
              <div className="hero-photo">
                <img src="images/hero-product.webp"
                alt="ЭкоКруг — 4-ярусная вермиферма в кухне"
                loading="eager" />
              </div>

              <div className="hero-pin-tag hp-1">
                <span className="dot" />
                <span>Очистки</span>
              </div>
              <div className="hero-pin-tag hp-2">
                <span className="dot" />
                <span>Черви работают</span>
              </div>
              <div className="hero-pin-tag hp-3">
                <span className="dot" />
                <span>Биогумус</span>
              </div>
              <div className="hero-pin-tag hp-4">
                <span className="dot" />
                <span>Вермичай</span>
              </div>
            </div>
          </div>
        </div>

        {/* Декоративные фоновые элементы */}
        <FloatingShape top="6%" left="3%" size={110} delay={0} opacity={0.07} />
        <FloatingShape top="60%" left="44%" size={70} delay={4} opacity={0.06} />
        <FloatingShape top="80%" left="8%" size={50} delay={8} opacity={0.08} />
      </div>
    </section>);

}
window.Hero = Hero;
