// src/components.jsx — shared components
// Globals: Logo, Header, Footer, Button, Placeholder, SectionHead, ArrowIcon, etc.

const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────────────
// Logo / icons
// ─────────────────────────────────────────────────────────────

function ArrowIcon({ size = 14 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square" />
    </svg>
  );
}

function LogoMark() {
  return (
    <svg viewBox="0 0 32 32" fill="none">
      <path d="M4 26L16 4l12 22" stroke="currentColor" strokeWidth="2.5" strokeLinecap="square" />
      <path d="M9.5 19h13" style={{ stroke: "var(--accent)" }} strokeWidth="2.5" strokeLinecap="square" />
    </svg>
  );
}

function Logo({ onClick, size = 48 }) {
  // Theme-aware logo: navy-text PNG on light theme, white-text PNG on dark theme.
  // CSS swaps based on html[data-theme].
  return (
    <a className="logo" href="./" onClick={onClick} style={{ cursor: "pointer" }} aria-label="ACCORD GROUP — главная">
      <span className="logo__wrap" style={{ height: size, display: "inline-flex", alignItems: "center" }}>
        <img
          src="assets/logo-dark.png?v=6"
          alt="ACCORD GROUP"
          className="logo__img logo__img--dark"
          style={{ height: size, width: "auto" }}
        />
        <img
          src="assets/logo-light.png?v=6"
          alt="ACCORD GROUP"
          className="logo__img logo__img--light"
          style={{ height: size, width: "auto" }}
        />
      </span>
    </a>
  );
}

// ─────────────────────────────────────────────────────────────
// Header
// ─────────────────────────────────────────────────────────────

const NAV_ITEMS = [
  { id: "home", label: "Главная" },
  { id: "about", label: "О компании" },
  { id: "services", label: "Услуги" },
  { id: "contacts", label: "Контакты" },
];

function routeHref(id) {
  return id === "home" ? "./" : `#${id}`;
}

function handleRouteClick(ev, navigate, id) {
  ev.preventDefault();
  navigate(id);
}

function Header({ route, navigate }) {
  const [open, setOpen] = useState(false);
  useEffect(() => { setOpen(false); }, [route]);

  return (
    <header className="header" data-comment-anchor="site-header">
      <div className="wrap header__inner">
        <Logo onClick={(ev) => handleRouteClick(ev, navigate, "home")} />
        <nav className="nav">
          {NAV_ITEMS.map((n) => (
            <a key={n.id}
               href={routeHref(n.id)}
               className={route === n.id ? "active" : ""}
               aria-current={route === n.id ? "page" : undefined}
               onClick={(ev) => handleRouteClick(ev, navigate, n.id)}
               style={{ cursor: "pointer" }}>
              {n.label}
            </a>
          ))}
        </nav>
        <div className="header__cta">
          <Button onClick={() => navigate("request")} size="sm">
            Оставить заявку <ArrowIcon size={12} />
          </Button>
        </div>
        <button className="mobile-menu-btn" onClick={() => setOpen(true)} aria-label="Меню">
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
            <path d="M2 5h14M2 9h14M2 13h14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square" />
          </svg>
        </button>
      </div>

      {open && (
        <div className="mobile-drawer">
          <div className="wrap header__inner">
            <Logo onClick={(ev) => handleRouteClick(ev, navigate, "home")} />
            <button className="mobile-menu-btn" onClick={() => setOpen(false)} aria-label="Закрыть">
              <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                <path d="M4 4l10 10M14 4L4 14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square" />
              </svg>
            </button>
          </div>
          <nav className="mobile-drawer__nav">
            {NAV_ITEMS.map((n) => (
              <a key={n.id} href={routeHref(n.id)} onClick={(ev) => handleRouteClick(ev, navigate, n.id)}>{n.label} <ArrowIcon /></a>
            ))}
            <a href={routeHref("request")} onClick={(ev) => handleRouteClick(ev, navigate, "request")} style={{ color: "var(--accent)" }}>Оставить заявку <ArrowIcon /></a>
          </nav>
        </div>
      )}
    </header>
  );
}

// ─────────────────────────────────────────────────────────────
// Footer
// ─────────────────────────────────────────────────────────────

function Footer({ navigate }) {
  const year = 2026;
  return (
    <footer className="footer" data-comment-anchor="site-footer">
      <div className="wrap">
        <div className="footer-grid">
          <div className="footer-col">
            <Logo onClick={() => navigate("home")} size={24} />
            <p className="t-body" style={{ marginTop: 16, maxWidth: 320, fontSize: 12.8 }}>
              Импорт, экспорт и поставки под ключ в условиях сложной международной логистики.
            </p>
            <div style={{ display: "flex", gap: 8, marginTop: 20 }}>
              <span className="tag">B2B · РБ · РФ · СНГ</span>
            </div>
          </div>
          <div className="footer-col">
            <h4>Навигация</h4>
            <ul>
              {NAV_ITEMS.map((n) => (
                <li key={n.id}><a href={routeHref(n.id)} onClick={(ev) => handleRouteClick(ev, navigate, n.id)} style={{cursor:"pointer"}}>{n.label}</a></li>
              ))}
              <li><a href={routeHref("request")} onClick={(ev) => handleRouteClick(ev, navigate, "request")} style={{cursor:"pointer"}}>Оставить заявку</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Контакты</h4>
            <ul>
              <li><a href="mailto:hello@accordgroup.by">hello@accordgroup.by</a></li>
              <li><a href="https://t.me/accord_supply">@accord_supply</a></li>
              <li><a href="tel:+375447275017">+375 44 727 50 17</a></li>
              <li><span style={{color:"var(--text-dim)"}}>Пн—Сб, 09:00—22:00 (GMT+3)</span></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Документы</h4>
            <ul>
              <li><a href={routeHref("privacy")} onClick={(ev) => handleRouteClick(ev, navigate, "privacy")} style={{cursor:"pointer"}}>Политика конфиденциальности</a></li>
              <li><a href={routeHref("consent")} onClick={(ev) => handleRouteClick(ev, navigate, "consent")} style={{cursor:"pointer"}}>Согласие на обработку данных</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span className="mono">© {year} ACCORD GROUP. Все права защищены.</span>
        </div>
      </div>
    </footer>
  );
}

// ─────────────────────────────────────────────────────────────
// Buttons
// ─────────────────────────────────────────────────────────────

function Button({ children, onClick, variant = "primary", size, type, disabled, style }) {
  const cls = `btn btn--${variant}${size ? " btn--" + size : ""}`;
  return (
    <button className={cls} onClick={onClick} type={type} disabled={disabled} style={style}>
      {children}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Placeholder image block
// ─────────────────────────────────────────────────────────────

function Placeholder({ label, tag, ratio = "16/10", style }) {
  return (
    <div className="ph" style={{ aspectRatio: ratio, ...style }}>
      <span className="ph__tag">{tag || "IMG"}</span>
      <span className="ph__label">{label}</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Section header (tag + title + optional aside)
// ─────────────────────────────────────────────────────────────

function SectionHead({ num, tag, title, lead, aside, className = "" }) {
  return (
    <div className={"section-head " + className}>
      <div style={{ flex: "1 1 480px", maxWidth: 720 }}>
        <div style={{ display: "flex", gap: 16, alignItems: "center", marginBottom: 28 }}>
          {num && <span className="section-num">{num}</span>}
          {tag && <span className="section-tag">{tag}</span>}
        </div>
        <h2 className="t-h2" style={{ marginBottom: 16 }}>{title}</h2>
        {lead && <p className="t-lead" style={{ maxWidth: 640 }}>{lead}</p>}
      </div>
      {aside && <div style={{ flex: "0 0 auto" }}>{aside}</div>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Number cycler for unique request ID
// ─────────────────────────────────────────────────────────────

function generateRequestId() {
  // REQ-2026-NNNN (persisted counter in localStorage)
  const key = "accord_req_counter";
  let n = parseInt(localStorage.getItem(key) || "47", 10);
  n += 1;
  localStorage.setItem(key, String(n));
  return `REQ-2026-${String(n).padStart(4, "0")}`;
}

// ─────────────────────────────────────────────────────────────
// Reveal-on-scroll wrapper
// ─────────────────────────────────────────────────────────────

function Reveal({ children, delay = 0, as: As = "div", className = "", style = {} }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // Eagerly reveal if already in viewport at mount
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight && rect.bottom > 0) {
      setVisible(true);
      return;
    }
    if ("IntersectionObserver" in window) {
      const io = new IntersectionObserver((entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setVisible(true);
            io.disconnect();
          }
        });
      }, { threshold: 0, rootMargin: "0px 0px 5% 0px" });
      io.observe(el);
      // Safety fallback: reveal after 1.2s no matter what
      const t = setTimeout(() => { setVisible(true); io.disconnect(); }, 1200);
      return () => { io.disconnect(); clearTimeout(t); };
    } else {
      setVisible(true);
    }
  }, []);
  return (
    <As
      ref={ref}
      className={className}
      style={{
        opacity: visible ? 1 : 0,
        transform: visible ? "translateY(0)" : "translateY(16px)",
        transition: `opacity 0.6s cubic-bezier(0.2,0.7,0.2,1) ${delay}s, transform 0.6s cubic-bezier(0.2,0.7,0.2,1) ${delay}s`,
        ...style,
      }}
    >
      {children}
    </As>
  );
}

Object.assign(window, {
  ArrowIcon, LogoMark, Logo, Header, Footer, Button, Placeholder,
  SectionHead, Reveal, generateRequestId, NAV_ITEMS,
});
