// Primitives.jsx — базовые элементы UI: кнопки, бейджи, поля, иконки, заголовки секций

// Lucide-иконка (CDN). Использует data-lucide; перерисовывается после монтирования.
function Icon({ name, size = 20, color = "currentColor", strokeWidth = 1.75, style }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (window.lucide && ref.current) {
      ref.current.innerHTML = "";
      const el = document.createElement("i");
      el.setAttribute("data-lucide", name);
      ref.current.appendChild(el);
      window.lucide.createIcons({
        attrs: { width: size, height: size, "stroke-width": strokeWidth, stroke: color },
        nameAttr: "data-lucide",
      });
    }
  }, [name, size, color, strokeWidth]);
  return <span ref={ref} style={{ display: "inline-flex", lineHeight: 0, color, ...style }} />;
}

function Button({ children, variant = "primary", size = "md", icon, iconRight, onClick, style, disabled, type }) {
  const [hover, setHover] = React.useState(false);
  const [press, setPress] = React.useState(false);
  const pads = size === "lg" ? "16px 32px" : size === "sm" ? "9px 18px" : "13px 26px";
  const fs = size === "lg" ? 17 : size === "sm" ? 14 : 15;
  const variants = {
    primary: {
      background: press ? "var(--terracotta-deep)" : hover ? "var(--terracotta-bright)" : "var(--terracotta)",
      color: "var(--cream)", border: "1.5px solid transparent",
      boxShadow: hover ? "0 14px 34px rgba(211,97,60,.34)" : "0 8px 22px rgba(211,97,60,.24)",
    },
    secondary: {
      background: hover ? "rgba(211,97,60,.08)" : "transparent",
      color: "var(--terracotta)", border: "1.5px solid var(--terracotta)", boxShadow: "none",
    },
    dark: {
      background: press ? "#05332C" : hover ? "#0A4A40" : "var(--green-deep)",
      color: "var(--cream)", border: "1.5px solid transparent", boxShadow: "none",
    },
    ghost: {
      background: hover ? "rgba(43,38,34,.05)" : "transparent",
      color: "var(--graphite)", border: "1.5px solid transparent", boxShadow: "none",
    },
    onPhoto: {
      background: hover ? "rgba(243,238,218,.16)" : "rgba(243,238,218,.10)",
      color: "var(--cream)", border: "1.5px solid rgba(243,238,218,.45)",
      backdropFilter: "blur(8px)", WebkitBackdropFilter: "blur(8px)", boxShadow: "none",
    },
  };
  return (
    <button type={type} disabled={disabled} onClick={disabled ? undefined : onClick}
      onMouseEnter={() => !disabled && setHover(true)} onMouseLeave={() => { setHover(false); setPress(false); }}
      onMouseDown={() => !disabled && setPress(true)} onMouseUp={() => setPress(false)}
      style={{
        fontFamily: "var(--font-ui)", fontWeight: 600, fontSize: fs, padding: pads,
        borderRadius: 999, cursor: disabled ? "not-allowed" : "pointer", display: "inline-flex", alignItems: "center",
        justifyContent: "center", maxWidth: "100%", minWidth: 0, textAlign: "center", lineHeight: 1.18,
        gap: 9, transition: "all .22s cubic-bezier(.22,1,.36,1)",
        transform: press ? "scale(.975)" : "scale(1)", whiteSpace: "nowrap",
        opacity: disabled ? 0.58 : 1,
        ...variants[variant], ...style,
      }}>
      {icon && <Icon name={icon} size={fs + 3} />}
      {children}
      {iconRight && <Icon name={iconRight} size={fs + 1} />}
    </button>
  );
}

function Badge({ children, tone = "soft" }) {
  const tones = {
    solid: { background: "var(--terracotta)", color: "var(--cream)" },
    soft: { background: "rgba(211,97,60,.12)", color: "var(--terracotta)" },
    green: { background: "rgba(1,65,56,.10)", color: "var(--green-deep)" },
    outline: { background: "transparent", color: "var(--graphite)", border: "1px solid var(--line-warm)" },
  };
  return (
    <span style={{
      fontFamily: "var(--font-ui)", fontWeight: 600, fontSize: 12.5, padding: "6px 13px",
      borderRadius: 999, display: "inline-flex", alignItems: "center", gap: 6, ...tones[tone],
    }}>{children}</span>
  );
}

function Eyebrow({ children, color = "var(--terracotta)", center }) {
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 10, justifyContent: center ? "center" : "flex-start",
      fontFamily: "var(--font-ui)", fontWeight: 600, fontSize: 13, letterSpacing: ".14em",
      textTransform: "uppercase", color,
    }}>
      <span style={{ width: 26, height: 2, background: color, borderRadius: 2 }} />
      {children}
    </div>
  );
}

function Field({ label, placeholder, type = "text", value, onChange, textarea }) {
  const [focus, setFocus] = React.useState(false);
  const base = {
    width: "100%", boxSizing: "border-box", fontFamily: "var(--font-ui)", fontSize: 15,
    padding: "13px 15px", border: "1.5px solid " + (focus ? "var(--terracotta)" : "var(--line-warm)"),
    borderRadius: 10, background: focus ? "#fff" : "var(--cream)", color: "var(--ink)", outline: "none",
    boxShadow: focus ? "0 0 0 3px rgba(211,97,60,.12)" : "none", transition: "all .2s ease",
    resize: "vertical",
  };
  return (
    <label style={{ display: "block" }}>
      {label && <span style={{ display: "block", fontFamily: "var(--font-ui)", fontSize: 12.5,
        fontWeight: 600, color: "var(--graphite)", marginBottom: 7 }}>{label}</span>}
      {textarea
        ? <textarea rows={4} placeholder={placeholder} value={value} onChange={onChange}
            onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} style={base} />
        : <input type={type} placeholder={placeholder} value={value} onChange={onChange}
            onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} style={base} />}
    </label>
  );
}

function SectionHead({ eyebrow, title, intro, center, dark }) {
  return (
    <div style={{ maxWidth: center ? 720 : 760, margin: center ? "0 auto" : 0,
      textAlign: center ? "center" : "left", display: "flex", flexDirection: "column",
      gap: 16, alignItems: center ? "center" : "flex-start" }}>
      <h2 className="h1" style={{ margin: 0, color: dark ? "var(--cream)" : "var(--ink)" }}>{title}</h2>
      {intro && <p className="lead" style={{ margin: 0, color: dark ? "var(--fg-on-dark-2)" : "var(--graphite)" }}>{intro}</p>}
    </div>
  );
}

// Reveal — мягкое появление при попадании в зону видимости (fade + подъём).
// БЕЗОПАСНО: в состоянии покоя контент ВИДИМ. Вход проигрывается один раз через
// Web Animations API с fill:"backwards" — даже если эффект не сработает или
// родитель переотрендерится, контент всё равно остаётся видимым (не пропадает).
function Reveal({ children, delay = 0, y = 24, style }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const node = ref.current;
    if (!node || !node.animate) return;
    const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) return;
    const scroller = node.closest("[data-scroller]");
    const target = scroller || window;
    let played = false;
    const play = () => {
      if (played) return;
      const r = node.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight;
      if (r.top < vh * 0.92 && r.bottom > 8) {
        played = true;
        target.removeEventListener("scroll", play);
        window.removeEventListener("resize", play);
        node.animate(
          [{ opacity: 0, transform: `translateY(${y}px)` }, { opacity: 1, transform: "none" }],
          { duration: 700, delay, easing: "cubic-bezier(.22,1,.36,1)", fill: "backwards" }
        );
      }
    };
    target.addEventListener("scroll", play, { passive: true });
    window.addEventListener("resize", play);
    const t = setTimeout(play, 80);
    return () => {
      target.removeEventListener("scroll", play);
      window.removeEventListener("resize", play);
      clearTimeout(t);
    };
  }, []);
  return <div ref={ref} style={style}>{children}</div>;
}

Object.assign(window, { Icon, Button, Badge, Eyebrow, Field, SectionHead, Reveal });
