// ===================== PRIMITIVES =====================
const { useState, useEffect, useRef, useMemo } = React;

// ---------- Reveal-on-scroll ----------
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          el.classList.add("in");
          io.unobserve(el);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

function Reveal({ children, delay = 0, className = "", as: Tag = "div", style }) {
  const ref = useReveal();
  return (
    <Tag
      ref={ref}
      className={`reveal ${className}`}
      style={{ transitionDelay: `${delay}ms`, ...style }}
    >
      {children}
    </Tag>
  );
}

// ---------- Count Up ----------
function CountUp({ to, suffix = "", duration = 1600 }) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const startedRef = useRef(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !startedRef.current) {
          startedRef.current = true;
          const start = performance.now();
          const animate = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(Math.floor(eased * to));
            if (t < 1) requestAnimationFrame(animate);
            else setVal(to);
          };
          requestAnimationFrame(animate);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration]);

  return (
    <span ref={ref} className="num">
      {val.toLocaleString()}{suffix}
    </span>
  );
}

// ---------- Eyebrow ----------
function Eyebrow({ children, gold = false }) {
  return (
    <span className={`eyebrow ${gold ? "gold" : ""}`}>
      <span className="dot" />
      {children}
    </span>
  );
}

// ---------- Section wrapper ----------
function Section({ id, label, children, tint = false, screenLabel }) {
  return (
    <section
      id={id}
      className={`section-y ${tint ? "sales-tint" : ""}`}
      data-screen-label={screenLabel}
    >
      <div className="container">{children}</div>
    </section>
  );
}

// ---------- CTA Button ----------
function CTAButton({ children, className = "", onClick, variant = "primary" }) {
  const cls = variant === "gold" ? "btn-gold" : variant === "ghost" ? "btn-ghost" : "btn-primary";
  return (
    <button className={`${cls} ${className}`} onClick={onClick || (() => {
      const target = document.getElementById("apply");
      if (target) target.scrollIntoView({ behavior: "smooth", block: "start" });
    })}>
      {children}
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
        <path d="M5 12h14M13 6l6 6-6 6" />
      </svg>
    </button>
  );
}

// ---------- Image with fallback ----------
function Img({ src, alt, className, style }) {
  const [errored, setErrored] = useState(false);
  if (errored) {
    return (
      <div className={`img-cover ${className || ""}`} style={{
        background: "linear-gradient(135deg, #1A2438, #131C2E)",
        display: "flex", alignItems: "center", justifyContent: "center",
        color: "#475569", fontSize: 12, ...style
      }}>
        {alt}
      </div>
    );
  }
  return (
    <img
      src={src}
      alt={alt || ""}
      className={`img-cover ${className || ""}`}
      style={style}
      loading="lazy"
      onError={() => setErrored(true)}
    />
  );
}

// ---------- Logo cell (handles white-on-dark) ----------
// scale = visual size multiplier for the logo inside the plate
// dark = use a dark plate (for logos with white elements like KUCC)
function LogoCell({ src, alt, h = 56, minW = 240, dark = false, offsetY = 0 }) {
  const PLATE_H = 110;
  return (
    <div style={{
      height: PLATE_H,
      minWidth: minW,
      padding: "12px 32px",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      background: dark
        ? "linear-gradient(135deg, #1A2438, #0F1626)"
        : "rgba(248, 250, 252, 0.97)",
      borderRadius: 16,
      border: `1px solid ${dark ? "rgba(148,163,184,0.18)" : "var(--line)"}`,
      boxShadow: dark
        ? "0 1px 0 rgba(255,255,255,0.04) inset"
        : "0 1px 0 rgba(255,255,255,0.5) inset",
    }}>
      <img src={src} alt={alt} style={{
        height: h,
        width: "auto",
        maxWidth: "none",
        objectFit: "contain",
        display: "block",
        transform: offsetY ? `translateY(${offsetY}px)` : undefined,
      }} />
    </div>
  );
}

// ---------- Nav ----------
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    { href: "#about", label: "강사 소개" },
    { href: "#lectures", label: "강의 이력" },
    { href: "#why", label: "Why 문기준 멘토?", gold: true },
    { href: "#content", label: "멘토링 콘텐츠" },
    { href: "#audience", label: "For Whom?" },
    { href: "#cases", label: "합격 사례" },
  ];

  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="container" style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        height: 68,
      }}>
        <a href="#top" style={{ display: "flex", alignItems: "center", gap: 10, fontWeight: 700, fontSize: 16 }}>
          <span style={{
            width: 28, height: 28, borderRadius: 8,
            background: "var(--grad-primary)",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontWeight: 800, fontSize: 13, color: "#fff",
          }}>문</span>
          <span>문기준 멘토링</span>
        </a>
        <div style={{ display: "flex", gap: 28, alignItems: "center" }} className="nav-links">
          {links.map((l) => (
            <a key={l.href} href={l.href} className="ul-link" style={{
              fontSize: 14, color: l.gold ? "#FCD34D" : "var(--text-1)", fontWeight: 500,
            }}>{l.label}</a>
          ))}
        </div>
        <a href="#apply" className="btn-primary" style={{ padding: "10px 18px", fontSize: 14 }}>
          멘토링 신청
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 12h14M13 6l6 6-6 6" />
          </svg>
        </a>
      </div>
      <style>{`
        @media (max-width: 880px) {
          .nav-links { display: none !important; }
        }
      `}</style>
    </nav>
  );
}

// ---------- Quote glyph ----------
function QuoteGlyph({ color = "var(--blue)" }) {
  return (
    <svg width="36" height="28" viewBox="0 0 36 28" fill="none" aria-hidden>
      <path d="M0 28V14C0 6 5 0 14 0V6C8 6 6 9 6 14H14V28H0ZM22 28V14C22 6 27 0 36 0V6C30 6 28 9 28 14H36V28H22Z"
        fill={color} opacity="0.35"/>
    </svg>
  );
}

// ---------- Accent strip ----------
function AccentStrip({ color = "var(--blue)" }) {
  return (
    <div style={{
      height: 2, width: 40, background: color, opacity: 0.7, borderRadius: 2,
    }} />
  );
}

Object.assign(window, {
  useReveal, Reveal, CountUp, Eyebrow, Section, CTAButton, Img, LogoCell, Nav, QuoteGlyph, AccentStrip,
});
