// Ikigai — Shared UI primitives
// Apple-pure aesthetic. Used across Hero, sections, prototype.

const { useEffect, useRef, useState, useCallback } = React;

// ─────────────────────────────────────────────────────────────────
// Reveal — IntersectionObserver-based scroll reveal
// ─────────────────────────────────────────────────────────────────
function Reveal({ children, delay = 0, as: Tag = "div", className = "", style = {}, ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const check = () => {
      const rect = el.getBoundingClientRect();
      if (rect.top < window.innerHeight - 40 && rect.bottom > 0) {
        setSeen(true);
        window.removeEventListener("scroll", check);
        return true;
      }
      return false;
    };
    if (check()) return;
    window.addEventListener("scroll", check, { passive: true });
    return () => window.removeEventListener("scroll", check);
  }, []);
  const revealStyle = {
    opacity: seen ? 1 : 0,
    transform: seen ? "translateY(0)" : "translateY(24px)",
    transition: `opacity 0.9s cubic-bezier(0.16,1,0.3,1) ${delay}ms, transform 0.9s cubic-bezier(0.16,1,0.3,1) ${delay}ms`,
    willChange: "opacity, transform",
    ...style,
  };
  return (
    <Tag
      ref={ref}
      className={className}
      style={revealStyle}
      {...rest}
    >
      {children}
    </Tag>
  );
}

// ─────────────────────────────────────────────────────────────────
// Apple-style nav (sticky, blurred)
// ─────────────────────────────────────────────────────────────────
function KNav({ tone = "light" }) {
  const items = [
    "Sobre", "Sensei", "Estilos", "Horários",
    "Eventos", "Galeria", "Notícias", "Contato"
  ];
  return (
    <nav className={`k-nav ${tone === "dark" ? "k-nav-dark" : ""}`}>
      <div className="k-nav-inner">
        <a href="#top" className="k-nav-logo" style={{ color: tone === "dark" ? "#f5f5f7" : "var(--k-ink)", display: "flex", alignItems: "center", gap: 10 }}>
          <img src="assets/logo-ikigai.png" alt="Ikigai" style={{ height: 36, width: "auto", display: "block" }}/>
          <span style={{ fontWeight: 600, letterSpacing: "-0.01em" }}>Ikigai</span>
        </a>
        <div className="k-row" style={{ gap: 28, alignItems: "center" }}>
          {items.map((label) => (
            <a key={label} href={`#${label.toLowerCase()}`} className="k-nav-link">
              {label}
            </a>
          ))}
        </div>
        <a href="#matricula" className="k-nav-link" style={{ fontWeight: 500 }}>
          Aula experimental ›
        </a>
      </div>
    </nav>
  );
}

// ─────────────────────────────────────────────────────────────────
// Kanji watermark
// ─────────────────────────────────────────────────────────────────
function Kanji({
  char = "空手",
  size = 480,
  opacity = 0.05,
  vertical = false,
  color = "currentColor",
  style = {},
  ...rest
}) {
  return (
    <div
      className={`k-kanji ${vertical ? "k-kanji-vert" : ""}`}
      style={{
        fontSize: size,
        lineHeight: 0.9,
        opacity,
        color,
        letterSpacing: vertical ? 0 : -0.02,
        ...style,
      }}
      aria-hidden="true"
      {...rest}
    >
      {char}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// CTA pair — Apple's signature "Buy" / "Learn more" pattern
// ─────────────────────────────────────────────────────────────────
function CTAPair({ primary = "Agendar aula experimental", primaryHref = "#matricula", secondary = "Conhecer o dojo", secondaryHref = "#sobre", tone = "blue" }) {
  return (
    <div className="k-row" style={{ gap: 22, flexWrap: "wrap", alignItems: "center" }}>
      <a href={primaryHref} className={`k-btn ${tone === "blue" ? "k-btn-primary" : tone === "dark" ? "k-btn-dark" : "k-btn-light"}`}>
        {primary}
      </a>
      <a href={secondaryHref} className="k-link">
        {secondary}
      </a>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Apple footer
// ─────────────────────────────────────────────────────────────────
function KFooter({ onOpenDoc }) {
  const cols = [
    {
      title: "Praticar",
      links: [
        { label: "Aula experimental", href: "#matricula" },
        { label: "Estilos", href: "#estilos" },
        { label: "Horários", href: "#horários" },
        { label: "Mensalidades", href: "#mensalidades" },
        { label: "Faixa etária", href: "#" },
      ],
    },
    {
      title: "Dojo",
      links: [
        { label: "Sobre", href: "#sobre" },
        { label: "Sensei", href: "#sensei" },
        { label: "Instrutores", href: "#instrutores" },
        { label: "Galeria", href: "#galeria" },
        { label: "Eventos", href: "#eventos" },
      ],
    },
    {
      title: "Contato",
      links: [
        { label: "Endereço", href: "#contato" },
        { label: "WhatsApp (21) 99608-7003", href: "https://wa.me/5521996087003", target: "_blank" },
        { label: "Instagram @dojo_ikigai_", href: "https://www.instagram.com/dojo_ikigai_?igsh=YWxqZTg2ZnRnM2tx", target: "_blank" },
        { label: "Imprensa", href: "#" },
        { label: "FAQ", href: "#" },
      ],
    },
  ];
  return (
    <footer style={{ background: "#f5f5f7", borderTop: "1px solid var(--k-line-soft)" }}>
      <div className="k-container-wide" style={{ padding: "40px 22px 24px", maxWidth: 980 }}>
        <p className="k-meta" style={{ marginBottom: 24, lineHeight: 1.5 }}>
          Mais maneiras de começar: <a href="#matricula" style={{ color: "var(--k-blue)" }}>Agendar aula experimental</a>, ou <a href="https://wa.me/5521996087003" target="_blank" rel="noopener noreferrer" style={{ color: "var(--k-blue)" }}>WhatsApp (21) 99608-7003</a>.
        </p>
        <div className="k-grid" style={{ gridTemplateColumns: "repeat(4, 1fr)", gap: 24, paddingBottom: 28, borderBottom: "1px solid var(--k-line)" }}>
          {cols.map((c) => (
            <div key={c.title}>
              <h4 style={{ fontSize: 12, fontWeight: 600, color: "var(--k-ink)", marginBottom: 12, letterSpacing: -0.01 }}>{c.title}</h4>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 8 }}>
                {c.links.map((l) => (
                  <li key={l.label}><a href={l.href} target={l.target || undefined} rel={l.target ? "noopener noreferrer" : undefined} className="k-meta" style={{ color: "var(--k-ink-3)" }}>{l.label}</a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div className="k-row" style={{ justifyContent: "space-between", marginTop: 18, flexWrap: "wrap", gap: 12 }}>
          <p className="k-meta">© 2026 Ikigai · Sensei Inst. Robson · SKIBRASIL. Todos os direitos reservados.</p>
          <div className="k-row" style={{ gap: 18, alignItems: "center" }}>
            {/* Ícone Instagram */}
            <a
              href="https://www.instagram.com/dojo_ikigai_?igsh=YWxqZTg2ZnRnM2tx"
              target="_blank"
              rel="noopener noreferrer"
              title="Dojo Ikigai no Instagram"
              style={{
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                width: 32, height: 32, borderRadius: 8,
                background: "linear-gradient(135deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%)",
                color: "#fff", flexShrink: 0,
                transition: "opacity 0.15s",
              }}
              onMouseEnter={e => e.currentTarget.style.opacity = "0.8"}
              onMouseLeave={e => e.currentTarget.style.opacity = "1"}
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="2" y="2" width="20" height="20" rx="5" ry="5"/>
                <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/>
                <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/>
              </svg>
            </a>
            <a href="#" onClick={(e) => { e.preventDefault(); onOpenDoc && onOpenDoc("privacidade"); }} className="k-meta">Política de Privacidade</a>
            <a href="#" onClick={(e) => { e.preventDefault(); onOpenDoc && onOpenDoc("termos"); }} className="k-meta">Termos de Uso</a>
            <a href="#" onClick={(e) => { e.preventDefault(); localStorage.removeItem("ikigai_cookie_consent_v1"); window.dispatchEvent(new CustomEvent("ikigai-open-cookies")); }} className="k-meta">Gerenciar cookies</a>
            <a href="#" className="k-meta">Brasil 🇧🇷</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ─────────────────────────────────────────────────────────────────
// Parallax helpers
// ─────────────────────────────────────────────────────────────────
function useScrollY() {
  const [y, setY] = useState(0);
  useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => setY(window.scrollY));
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return y;
}

// Expose
Object.assign(window, { Reveal, KNav, Kanji, CTAPair, KFooter, useScrollY });
