// Shared components: Header, Footer, ImagePlaceholder
const { useState, useEffect, useRef, useCallback, useMemo } = React;

// ============ IMAGE PLACEHOLDER ============
const ImagePlaceholder = ({ label, dark = false, style, aspect, className = '' }) => {
  return (
    <div
      className={`imgph ${dark ? 'imgph--dark' : ''} ${className}`}
      style={{
        aspectRatio: aspect || undefined,
        ...style,
      }}
    >
      <span className="imgph__label">{label}</span>
    </div>
  );
};

// ============ DNA WAVE (nav decoration) — rotating in place via rAF ============
const NavDna = () => {
  const W = 240;
  const H = 30;
  const cy = H / 2;
  const amp = 9;
  const PERIODS = 3.5;      // visible cycles across width
  const DURATION = 5.5;     // seconds per full rotation
  const N_RUNGS = 26;
  const SAMPLES = 90;       // points on each strand

  const topRef = useRef(null);
  const botRef = useRef(null);
  const rungRefs = useRef([]);

  useEffect(() => {
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    const start = performance.now();
    let raf;

    const draw = (phase) => {
      let topD = '', botD = '';
      for (let i = 0; i <= SAMPLES; i++) {
        const x = (i / SAMPLES) * W;
        const arg = (x / W) * PERIODS * 2 * Math.PI + phase;
        const s = Math.sin(arg);
        topD += (i === 0 ? 'M' : 'L') + x.toFixed(2) + ',' + (cy - amp * s).toFixed(2) + ' ';
        botD += (i === 0 ? 'M' : 'L') + x.toFixed(2) + ',' + (cy + amp * s).toFixed(2) + ' ';
      }
      if (topRef.current) topRef.current.setAttribute('d', topD);
      if (botRef.current) botRef.current.setAttribute('d', botD);

      for (let i = 0; i < N_RUNGS; i++) {
        const x = (i / (N_RUNGS - 1)) * W;
        const arg = (x / W) * PERIODS * 2 * Math.PI + phase;
        const s = Math.sin(arg);
        const ref = rungRefs.current[i];
        if (ref) {
          ref.setAttribute('y1', (cy - amp * s).toFixed(2));
          ref.setAttribute('y2', (cy + amp * s).toFixed(2));
          ref.setAttribute('opacity', (Math.abs(s) * 0.8).toFixed(2));
        }
      }
    };

    if (reduce) {
      draw(0);
      return;
    }

    const tick = (now) => {
      const t = ((now - start) / 1000 / DURATION) % 1;
      const phase = t * 2 * Math.PI;
      draw(phase);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <div className="nav-dna" aria-hidden="true">
      <svg viewBox={`0 0 ${W} ${H}`} width={W} height={H}>
        {Array.from({ length: N_RUNGS }).map((_, i) => {
          const x = (i / (N_RUNGS - 1)) * W;
          return (
            <line
              key={i}
              x1={x} x2={x}
              y1={cy} y2={cy}
              stroke="rgba(255,255,255,0.7)"
              strokeWidth="1"
              strokeLinecap="round"
              ref={(el) => { rungRefs.current[i] = el; }}
            />
          );
        })}
        <path ref={topRef} d="" stroke="#fff" strokeWidth="1.4" fill="none" strokeLinecap="round" />
        <path ref={botRef} d="" stroke="#fff" strokeWidth="1.4" fill="none" strokeLinecap="round" />
      </svg>

      <style>{`
        .nav-dna {
          display: inline-flex;
          align-items: center;
          height: 100%;
          padding: 0 18px;
        }
        .nav-dna svg { display: block; }
        @media (max-width: 1100px) {
          .nav-dna { display: none; }
        }
      `}</style>
    </div>
  );
};

// ============ HEADER ============
const Header = ({ activeSection, currentPage = 'home', onBook, onSecondOpinion, onSearch }) => {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const handleNavClick = (e, item) => {
    // Full-href links: let browser navigate
    if (item.href) return;

    e.preventDefault();
    // If on home page, scroll to section
    if (currentPage === 'home') {
      const el = document.getElementById(item.id);
      if (el) {
        const y = el.getBoundingClientRect().top + window.scrollY - 88;
        window.scrollTo({ top: y, behavior: 'smooth' });
      }
    } else {
      // From other pages: navigate to home with hash
      window.location.href = `index.html#${item.id}`;
    }
    setMobileOpen(false);
  };

  const handleBrandClick = (e) => {
    if (currentPage === 'home') {
      e.preventDefault();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
    // otherwise default navigation to index.html
  };

  return (
    <header className={`site-header ${scrolled ? 'is-scrolled' : ''}`}>
      {/* Top utility bar */}
      <div className="top-bar">
        <div className="container top-bar__inner">
          <a href="index.html" className="brand" onClick={handleBrandClick}>
            <Logo width={230} color="var(--navy-800)" subColor="var(--ink-500)" />
          </a>

          <div className="top-bar__meta">
            <div className="meta-item">
              <Icon name="pin" size={18} />
              <div>
                <div className="meta-item__sub">{DATA.brand.address.split(',')[0]}</div>
                <div className="meta-item__main">{DATA.brand.address.split(',').slice(1).join(',').trim()}</div>
              </div>
            </div>

            <div className="meta-item">
              <Icon name="clock" size={18} />
              <div>
                <div className="meta-item__sub">{DATA.brand.hours}</div>
                <a className="meta-item__main meta-item__main--link" href={`tel:${DATA.brand.phoneRaw}`}>
                  {DATA.brand.phone}
                </a>
              </div>
            </div>

            <button className="btn btn-primary" onClick={onBook}>
              Записаться на приём
            </button>
          </div>

          <button
            className="header-burger"
            onClick={() => setMobileOpen(!mobileOpen)}
            aria-label="Меню"
          >
            <Icon name={mobileOpen ? 'close' : 'menu'} size={22} />
          </button>
        </div>
      </div>

      {/* Nav bar */}
      <nav className={`nav-bar ${mobileOpen ? 'is-open' : ''}`}>
        <div className="container nav-bar__inner">
          <ul className="nav-list">
            {DATA.nav.map((item) => {
              const isActive = item.href
                ? (currentPage === item.id)
                : (currentPage === 'home' && activeSection === item.id);
              const href = item.href || (currentPage === 'home' ? `#${item.id}` : `index.html#${item.id}`);
              return (
                <li key={item.id}>
                  <a
                    href={href}
                    className={`nav-link ${isActive ? 'is-active' : ''}`}
                    onClick={(e) => handleNavClick(e, item)}
                  >
                    {item.label}
                  </a>
                </li>
              );
            })}
          </ul>

          <NavDna />

          <button className="nav-search" aria-label="Поиск" onClick={onSearch}>
            <Icon name="search" size={18} />
          </button>
        </div>
      </nav>

      <style>{`
        .site-header {
          position: sticky;
          top: 0;
          z-index: 50;
          background: #fff;
          transition: box-shadow .2s ease;
        }
        .site-header.is-scrolled {
          box-shadow: 0 2px 14px oklch(0.25 0.04 255 / 0.06);
        }
        .top-bar { background: #fff; }
        .top-bar__inner {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 24px;
          padding-top: 14px;
          padding-bottom: 14px;
        }
        .brand { display: inline-flex; align-items: center; flex-shrink: 0; }
        .top-bar__meta {
          display: flex;
          align-items: center;
          gap: 28px;
        }
        .meta-item {
          display: flex;
          align-items: center;
          gap: 10px;
          color: var(--ink-700);
        }
        .meta-item__sub {
          font-size: 12px;
          color: var(--ink-500);
          line-height: 1.2;
        }
        .meta-item__main {
          font-size: 14px;
          font-weight: 500;
          color: var(--ink-900);
          line-height: 1.2;
          margin-top: 1px;
        }
        .meta-item__main--link:hover { color: var(--navy-700); }

        .header-burger {
          display: none;
          width: 42px; height: 42px;
          align-items: center; justify-content: center;
          border-radius: var(--r-sm);
          color: var(--navy-800);
        }
        .header-burger:hover { background: var(--navy-100); }

        .nav-bar { background: var(--navy-800); }
        .nav-bar__inner {
          display: flex;
          align-items: stretch;
          justify-content: space-between;
          gap: 16px;
          height: 52px;
        }
        .nav-list {
          list-style: none;
          margin: 0; padding: 0;
          display: flex;
          align-items: stretch;
          gap: 2px;
        }
        .nav-link {
          display: inline-flex;
          align-items: center;
          height: 100%;
          padding: 0 18px;
          color: rgba(255,255,255,0.78);
          font-size: 14.5px;
          font-weight: 400;
          position: relative;
          transition: color .15s ease;
        }
        .nav-link:hover { color: #fff; }
        .nav-link.is-active { color: #fff; }
        .nav-link.is-active::after {
          content: "";
          position: absolute;
          left: 18px; right: 18px;
          bottom: 0;
          height: 2px;
          background: var(--accent);
        }
        .nav-search {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 44px;
          color: rgba(255,255,255,0.8);
        }
        .nav-search:hover { color: #fff; }

        .nav-call,
        .nav-wa { display: none; }

        /* Mobile */
        @media (max-width: 960px) {
          .top-bar__meta { display: none; }
          .header-burger { display: inline-flex; }
          .nav-bar { display: none; }
          .nav-bar.is-open {
            display: block;
            position: absolute;
            top: 100%; left: 0; right: 0;
            box-shadow: var(--shadow-md);
          }
          .nav-bar.is-open .nav-bar__inner {
            height: auto;
            flex-direction: column;
            padding-top: 12px;
            padding-bottom: 12px;
          }
          .nav-list { flex-direction: column; align-items: stretch; width: 100%; }
          .nav-link { padding: 14px 0; }
          .nav-link.is-active::after { display: none; }
          .nav-call, .nav-wa { display: none; }
        }
      `}</style>
    </header>
  );
};

// ============ STAT TICKER (animated number) ============
const StatNumber = ({ value }) => {
  // Just render — the visual emphasis is enough without animation
  return <span className="stat-num">{value}</span>;
};

// ============ SECTION HEADER ============
const SectionHead = ({ eyebrow, title, sub, action }) => (
  <div className="sec-head">
    <div className="sec-head__title">
      {eyebrow && <span className="eyebrow">{eyebrow}</span>}
      <h2>{title}</h2>
      {sub && <p className="sec-head__sub">{sub}</p>}
    </div>
    {action && <div className="sec-head__action">{action}</div>}
  </div>
);

// ============ CTA BUTTONS PAIR ============
const HeroCtas = ({ onBook, onSecondOpinion }) => (
  <div className="hero-ctas">
    <button className="btn btn-primary btn-lg" onClick={onSecondOpinion}>
      Получить второе мнение
    </button>
    <button className="btn btn-secondary btn-lg" onClick={onBook}>
      Записаться на приём
    </button>
  </div>
);

// Expose globally
Object.assign(window, {
  ImagePlaceholder,
  Header,
  StatNumber,
  SectionHead,
  HeroCtas,
});
