/* ============================================================
   Shared components · Надёжные люди
   ============================================================ */
const { useState, useEffect, useRef, useContext, createContext } = React;

/* ---------- navigation context ---------- */
const NavCtx = createContext({ page: 'home', go: () => {} });
const useNav = () => useContext(NavCtx);

/* ---------- icons (rounded stroke set) ---------- */
function Icon({ name, size = 24, stroke = 2.1, style, className }) {
  const p = { fill: 'none', stroke: 'currentColor', strokeWidth: stroke, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const paths = {
    heart: <path {...p} d="M12 20s-7-4.6-9.2-9C1.3 8 2.6 4.6 6 4.6c2 0 3.2 1.3 4 2.6.8-1.3 2-2.6 4-2.6 3.4 0 4.7 3.4 3.2 6.4C19 15.4 12 20 12 20Z" />,
    hands: <g {...p}><path d="M3 12.5 7 9l4 3 3-2.5 4 3.5" /><path d="M3 12.5V18a1 1 0 0 0 1 1h16a1 1 0 0 0 1-1v-5" /></g>,
    chat: <path {...p} d="M4 5h16a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H9l-4 3v-3H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Z" />,
    calendar: <g {...p}><rect x="3" y="5" width="18" height="16" rx="2.5" /><path d="M3 9h18M8 3v4M16 3v4" /></g>,
    shield: <path {...p} d="M12 3 5 6v5c0 4.5 3 8 7 10 4-2 7-5.5 7-10V6l-7-3Z" />,
    star: <path {...p} d="m12 3 2.7 5.6 6.1.9-4.4 4.3 1 6-5.4-2.8L6.6 20l1-6L3.2 9.5l6.1-.9L12 3Z" />,
    arrow: <path {...p} d="M5 12h14M13 6l6 6-6 6" />,
    arrowUpRight: <path {...p} d="M7 17 17 7M9 7h8v8" />,
    check: <path {...p} d="m5 12.5 4.5 4.5L19 7" />,
    phone: <path {...p} d="M5 4h3l2 5-2.5 1.5a11 11 0 0 0 5 5L16 13l5 2v3a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2Z" />,
    mail: <g {...p}><rect x="3" y="5" width="18" height="14" rx="2.5" /><path d="m4 7 8 6 8-6" /></g>,
    pin: <g {...p}><path d="M12 21s-6.5-5.5-6.5-10.5A6.5 6.5 0 0 1 18.5 10.5C18.5 15.5 12 21 12 21Z" /><circle cx="12" cy="10.3" r="2.3" /></g>,
    users: <g {...p}><circle cx="9" cy="8" r="3" /><path d="M3.5 19a5.5 5.5 0 0 1 11 0M16 6.2a3 3 0 0 1 0 5.6M21 19a5.4 5.4 0 0 0-3.5-5" /></g>,
    sprout: <g {...p}><path d="M12 21v-7" /><path d="M12 14c0-3-2.5-5-6-5 0 3 2.5 5 6 5Z" /><path d="M12 12c0-3 2.5-5.5 6-5.5 0 3-2.5 5.5-6 5.5Z" /></g>,
    gift: <g {...p}><rect x="4" y="9" width="16" height="11" rx="1.5" /><path d="M2.5 9h19M12 9v11M12 9S9 3.5 6.5 5 9 9 12 9Zm0 0s3-5.5 5.5-4-2.5 4-5.5 4Z" /></g>,
    handHeart: <g {...p}><path d="M3 13l3-2 4 1.5 4-.5a1.3 1.3 0 0 1 0 2.6l-3 .4M3 13v6h11l6-2.5a1.5 1.5 0 0 0-1.3-2.6" /><path d="M13.5 5.2c.6-1 2.3-1 2.8.2.5-1.2 2.2-1.2 2.8-.2.5.9 0 2-2.8 3.8-2.8-1.8-3.3-2.9-2.8-3.8Z" /></g>,
    play: <g {...p}><circle cx="12" cy="12" r="9" /><path d="m10 9 5 3-5 3V9Z" fill="currentColor" /></g>,
    quote: <path {...p} d="M9 7H5a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h3v2a2 2 0 0 1-2 2m13-10h-4a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h3v2a2 2 0 0 1-2 2" />,
    menu: <path {...p} d="M4 7h16M4 12h16M4 17h16" />,
    close: <path {...p} d="M6 6l12 12M18 6 6 18" />,
    repeat: <path {...p} d="M4 9a5 5 0 0 1 5-5h7l-2-2m2 2-2 2M20 15a5 5 0 0 1-5 5H8l2 2m-2-2 2-2" />,
    doc: <g {...p}><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Z" /><path d="M14 3v5h5M8.5 13h7M8.5 17h7M8.5 9h2" /></g>,
    download: <path {...p} d="M12 3v12m0 0 4-4m-4 4-4-4M5 19h14" />,
  };
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} style={style} className={className} aria-hidden="true">
      {paths[name] || null}
    </svg>
  );
}

/* ---------- squiggle underline ---------- */
function Squiggle({ color = 'var(--orange)', children }) {
  return (
    <span className="squiggle">
      {children}
      <svg viewBox="0 0 200 12" preserveAspectRatio="none" fill="none">
        <path d="M2 8C28 3 44 3 70 7s44 4 64-1 50-3 64 2" stroke={color} strokeWidth="5" strokeLinecap="round" />
      </svg>
    </span>
  );
}

/* ---------- logo ---------- */
function Logo({ size = 46, onClick, showText = true }) {
  return (
    <button className="logo-btn" onClick={onClick} aria-label="Фонд надежные - на главную">
      <img src="uploads/logo.png?v=96" alt="Фонд надежные люди" style={{ '--logo-height': `${size}px` }} />
    </button>
  );
}

/* ---------- button (router-aware) ---------- */
function Btn({ to, href, variant = 'orange', size = '', children, icon, iconLeft, onClick, ...rest }) {
  const { go } = useNav();
  const cls = `btn btn-${variant} ${size === 'lg' ? 'btn-lg' : size === 'sm' ? 'btn-sm' : ''}`;
  const handle = (e) => {
    if (onClick) onClick(e);
    if (to) { e.preventDefault(); go(to); }
  };
  const inner = (
    <>
      {iconLeft && <Icon name={iconLeft} size={size === 'lg' ? 21 : 18} />}
      {children}
      {icon && <Icon name={icon} size={size === 'lg' ? 21 : 18} />}
    </>
  );
  if (href) return <a className={cls} href={href} target="_blank" rel="noopener" {...rest}>{inner}</a>;
  return <button className={cls} onClick={handle} {...rest}>{inner}</button>;
}

/* ---------- scroll reveal ---------- */
function Reveal({ children, delay = 0, as = 'div', className = '', style, ...rest }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setTimeout(() => el.classList.add('in'), delay); io.unobserve(el); } });
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  const Tag = as;
  return <Tag ref={ref} className={`reveal ${className}`} style={style} {...rest}>{children}</Tag>;
}

/* ---------- stat ---------- */
function Stat({ value, label, color = 'var(--green)' }) {
  return (
    <div className="stat">
      <div className="stat-value" style={{ color }}>{value}</div>
      <div className="stat-label">{label}</div>
    </div>
  );
}

/* ============================================================
   HEADER
   ============================================================ */
const NAV_LINKS = [
  { id: 'about', label: 'О фонде' },
  { id: 'mentorship', label: 'Наставничество' },
  { id: 'business', label: 'Бизнесу' },
  { id: 'team', label: 'Команда' },
  { id: 'contacts', label: 'Контакты' },
];

function Header() {
  const { page, go } = useNav();
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 16);
    onScroll();
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => { setOpen(false); }, [page]);
  return (
    <header className={`header ${scrolled ? 'is-scrolled' : ''}`}>
      <div className="wrap header-inner">
        <Logo size={46} onClick={() => go('home')} />
        <nav className="nav-desktop">
          {NAV_LINKS.map((l) => (
            <button key={l.id} className={`nav-link ${page === l.id ? 'active' : ''}`} onClick={() => go(l.id)}>
              {l.label}
            </button>
          ))}
        </nav>
        <div className="header-actions">
          <Btn to="donate" variant="orange" size="sm" iconLeft="heart">Помочь</Btn>
          <button className="burger" aria-label="Меню" onClick={() => setOpen(true)}><Icon name="menu" /></button>
        </div>
      </div>

      {open && (
        <div className="mobile-menu" onClick={() => setOpen(false)}>
          <div className="mobile-sheet" onClick={(e) => e.stopPropagation()}>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 8 }}>
              <Logo size={40} onClick={() => go('home')} />
              <button className="burger" onClick={() => setOpen(false)}><Icon name="close" /></button>
            </div>
            {NAV_LINKS.map((l) => (
              <button key={l.id} className={`mobile-link ${page === l.id ? 'active' : ''}`} onClick={() => go(l.id)}>
                {l.label}<Icon name="arrow" size={18} />
              </button>
            ))}
            <Btn to="donate" variant="orange" size="lg" iconLeft="heart" style={{ marginTop: 12 }}>Помочь фонду</Btn>
          </div>
        </div>
      )}
    </header>
  );
}

/* ============================================================
   FOOTER
   ============================================================ */
function Footer() {
  const { go } = useNav();
  return (
    <footer className="footer">
      <div className="footer-cta">
        <div className="wrap footer-cta-inner">
          <div>
            <h2 className="h-lg" style={{ color: '#fff' }}>Каждому подростку<br />нужен рядом<br />надёжный человек</h2>
            <p className="lead" style={{ color: 'rgba(255,255,255,.86)', marginTop: 14 }}>
              Станьте наставником или поддержите проект — выберите свой способ быть рядом.
            </p>
          </div>
          <div className="footer-cta-btns">
            <Btn to="donate" variant="orange" size="lg" iconLeft="heart">Сделать пожертвование</Btn>
            <Btn to="mentorship" variant="white" size="lg">Стать наставником</Btn>
          </div>
        </div>
      </div>

      <div className="wrap footer-grid">
        <div className="footer-brand">
          <img src="uploads/logo.png?v=96" alt="Надёжные люди — фонд друзей" style={{ maxWidth: 280, height: 'auto', width: '100%', filter: 'drop-shadow(0 6px 14px rgba(0,0,0,.06))' }} />
          <p style={{ color: 'var(--ink-soft)', marginTop: 16, maxWidth: 280, fontSize: 16 }}>
            Детский благотворительный фонд «Надёжные люди». Помогаем подросткам из детских домов найти друга и опору.
          </p>
          <a className="vk-link" href="https://vk.com/fond_nl" target="_blank" rel="noopener">
            <img src="uploads/vk-logo-icon.png?v=102" alt="VK" className="vk-badge"/> Мы ВКонтакте
          </a>
        </div>
        <div className="footer-col">
          <h4>Фонд</h4>
          {NAV_LINKS.map((l) => <button key={l.id} onClick={() => go(l.id)}>{l.label}</button>)}
          <button onClick={() => go('docs')}>Уставные документы</button>
        </div>
        <div className="footer-col">
          <h4>Помощь</h4>
          <button onClick={() => go('donate')}>Сделать пожертвование</button>
          <button onClick={() => go('mentorship')}>Стать наставником</button>
          <button onClick={() => go('business')}>Бизнесу</button>
          <button onClick={() => go('reports')}>Годовые отчёты</button>
        </div>
        <div className="footer-col">
          <h4>Контакты</h4>
          <a href="tel:+79822905050"><Icon name="phone" size={16} /> +7 982 290-50-50</a>
          <a href="mailto:info@fond-nl.ru"><Icon name="mail" size={16} /> info@fond-nl.ru</a>
          <span><Icon name="pin" size={16} /> Челябинск, ул. Энгельса 43, оф. 403</span>
        </div>
      </div>

      <div className="wrap footer-bottom">
        <span>© 2021–2026 ДБФ «Надёжные люди». ОГРН 1217400018186</span>
        <div className="footer-legal">
          <button onClick={() => go('contacts')}>Реквизиты</button>
          <button onClick={() => go('politika')}>Безопасность платежей</button>
          <button onClick={() => go('privacy')}>Политика конфиденциальности</button>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { NavCtx, useNav, Icon, Squiggle, Logo, Btn, Reveal, Stat, Header, Footer, NAV_LINKS });

/* ============================================================
   COOKIE BANNER
   ============================================================ */
function CookieBanner() {
  const { go } = useNav();
  const [show, setShow] = useState(false);
  useEffect(() => {
    let ok = false;
    try { ok = localStorage.getItem('nl-cookie-consent') === 'yes'; } catch (e) {}
    if (!ok) { const t = setTimeout(() => setShow(true), 900); return () => clearTimeout(t); }
  }, []);
  const accept = () => {
    try { localStorage.setItem('nl-cookie-consent', 'yes'); } catch (e) {}
    setShow(false);
  };
  if (!show) return null;
  return (
    <div className={`cookie-banner ${show ? 'in' : ''}`} role="dialog" aria-label="Использование cookie">
      <div className="cookie-ic"><Icon name="shield" size={26} /></div>
      <p className="cookie-text">
        Мы используем cookie-файлы, чтобы сайт работал корректно, а также для аналитики и улучшения сервиса.
        Продолжая пользоваться сайтом, вы соглашаетесь с{' '}
        <a href="#" onClick={(e) => { e.preventDefault(); go('privacy'); }}>политикой об обработке персональных данных</a>.
      </p>
      <Btn variant="green" size="sm" onClick={accept}>Согласен</Btn>
    </div>
  );
}
Object.assign(window, { CookieBanner });
