// Shared UI primitives + utilities
const { useState, useEffect, useRef, useLayoutEffect, useMemo, useCallback } = React;

// Register ScrollTrigger plugin
if (window.gsap && window.ScrollTrigger) {
  gsap.registerPlugin(ScrollTrigger);
}

// Detect reduced-motion
function usePrefersReducedMotion() {
  const [reduced, setReduced] = useState(false);
  useEffect(() => {
    const mql = window.matchMedia("(prefers-reduced-motion: reduce)");
    setReduced(mql.matches);
    const onChange = () => setReduced(mql.matches);
    mql.addEventListener?.("change", onChange);
    return () => mql.removeEventListener?.("change", onChange);
  }, []);
  return reduced;
}

// In-view fade up via IntersectionObserver
function FadeUp({ children, delay = 0, y = 18, className = "", as = "div" }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const Tag = as;
  return (
    <Tag
      ref={ref}
      className={className}
      style={{
        opacity: seen ? 1 : 0,
        transform: seen ? "translate3d(0,0,0)" : `translate3d(0,${y}px,0)`,
        transition: `opacity .9s cubic-bezier(.2,.7,.1,1) ${delay}s, transform .9s cubic-bezier(.2,.7,.1,1) ${delay}s`,
        willChange: "transform, opacity",
      }}
    >
      {children}
    </Tag>
  );
}

// Pill label
function Pill({ children, dark = false, className = "" }) {
  return (
    <span
      className={
        "inline-flex items-center gap-2 px-3 py-1 rounded-full text-[12px] font-medium tracking-tight " +
        (dark
          ? "bg-white/[0.06] text-white/80 border border-white/10"
          : "bg-ink-950/[0.04] text-ink-950/70 border border-ink-950/10") +
        " " + className
      }
    >
      <span className={"inline-block w-1.5 h-1.5 rounded-full " + (dark ? "bg-brand-500" : "bg-brand-500")}></span>
      {children}
    </span>
  );
}

// Buttons
function CTA({ children, variant = "primary", className = "", icon = true, href, onClick }) {
  const base = "inline-flex items-center justify-center gap-2 h-12 px-6 rounded-full text-[15px] font-medium tracking-tight";
  const cls =
    variant === "primary" ? `${base} btn-primary` :
    variant === "ghost-dark" ? `${base} btn-ghost-dark` :
    `${base} btn-ghost`;
  const inner = (
    <>
      <span>{children}</span>
      {icon && (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
          <path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      )}
    </>
  );
  if (href) return <a href={href} className={cls + " " + className} onClick={onClick}>{inner}</a>;
  return <button type="button" className={cls + " " + className} onClick={onClick}>{inner}</button>;
}

// Logo mark — CondoClin wordmark
function Logo({ light = false, size = 28 }) {
  const height = size + 4;
  return (
    <a href="#top" className="inline-flex items-center group" aria-label="CondoClin">
      <img
        src="assets/condoclin-wordmark.png"
        alt="CondoClin"
        style={{ height, width: "auto", display: "block" }}
        className={light ? "brightness-0 invert-0" : ""}
        draggable="false"
      />
    </a>
  );
}

// Section wrapper
function Section({ id, dark = false, className = "", children, label }) {
  return (
    <section
      id={id}
      data-screen-label={label || id}
      data-om-validate
      className={"relative w-full " + (dark ? "text-paper-50 bg-ink-950 " : "text-ink-950 ") + className}
    >
      {children}
    </section>
  );
}

// Container
function Container({ className = "", children }) {
  return <div className={"mx-auto w-full max-w-[1240px] px-5 sm:px-8 " + className}>{children}</div>;
}

// Soft icon (line)
function I({ name, size = 20, className = "" }) {
  const icons = {
    arrow: <path d="M5 12h14M13 6l6 6-6 6" />,
    plus: <path d="M12 5v14M5 12h14" />,
    check: <path d="M4 12l5 5L20 6" />,
    x: <path d="M6 6l12 12M18 6 6 18" />,
    spark: <><path d="M12 3v6M12 15v6M3 12h6M15 12h6"/><circle cx="12" cy="12" r="2"/></>,
    chevron: <path d="M6 9l6 6 6-6" />,
    bolt: <path d="M13 2 4 14h7l-1 8 9-12h-7l1-8Z" />,
    shield: <path d="M12 3l8 3v6c0 5-3.5 8.5-8 9-4.5-.5-8-4-8-9V6l8-3Z" />,
    sparkle: <path d="M12 3l1.6 4.4L18 9l-4.4 1.6L12 15l-1.6-4.4L6 9l4.4-1.6L12 3Z" />,
    msg: <><path d="M4 5h16v11H8l-4 4V5Z"/></>,
    chart: <><path d="M4 19h16M7 16V9M12 16V5M17 16v-7"/></>,
    lock: <><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></>,
    doc: <><path d="M7 3h7l5 5v13H7V3Z"/><path d="M14 3v5h5"/></>,
    user: <><circle cx="12" cy="8" r="4"/><path d="M4 21c1.5-4 4.5-6 8-6s6.5 2 8 6"/></>,
    cog: <><circle cx="12" cy="12" r="3"/><path d="M19 12a7 7 0 0 0-.1-1.2l2.1-1.6-2-3.4-2.5.9a7 7 0 0 0-2.1-1.2L14 3h-4l-.4 2.5a7 7 0 0 0-2.1 1.2l-2.5-.9-2 3.4 2.1 1.6A7 7 0 0 0 5 12c0 .4 0 .8.1 1.2L3 14.8l2 3.4 2.5-.9c.6.5 1.3.9 2.1 1.2L10 21h4l.4-2.5c.8-.3 1.5-.7 2.1-1.2l2.5.9 2-3.4-2.1-1.6c.1-.4.1-.8.1-1.2Z"/></>,
    calendar: <><rect x="4" y="5" width="16" height="16" rx="2"/><path d="M4 10h16M9 3v4M15 3v4"/></>,
    bell: <><path d="M6 16V11a6 6 0 0 1 12 0v5l2 2H4l2-2Z"/><path d="M10 21a2 2 0 0 0 4 0"/></>,
    pix: <path d="M12 3l8 8-8 8-8-8 8-8Zm0 5 5 5-5 5-5-5 5-5Z" />,
    qrcode: <><rect x="4" y="4" width="6" height="6"/><rect x="14" y="4" width="6" height="6"/><rect x="4" y="14" width="6" height="6"/><path d="M14 14h3v3M20 17v3h-3M17 20h-3"/></>,
    box: <><path d="M12 3 4 7v10l8 4 8-4V7l-8-4Z"/><path d="M4 7l8 4 8-4M12 11v10"/></>,
    key: <><circle cx="8" cy="15" r="3"/><path d="M10.5 13l9-9M16 7l2 2M14 9l2 2"/></>,
    sign: <><path d="M4 18c4-1 6-8 10-8 2 0 3 2 1 4-2 1-3-2 0-3 2 0 4 2 4 5"/></>,
    home: <path d="M4 11.5 12 5l8 6.5V20H4v-8.5Z" />,
    building: <><rect x="5" y="3" width="14" height="18" rx="1"/><path d="M9 7h2M13 7h2M9 11h2M13 11h2M9 15h2M13 15h2"/></>,
    cam: <><path d="M5 7h3l2-3h4l2 3h3v12H5V7Z"/><circle cx="12" cy="13" r="3.5"/></>,
    sliders: <><path d="M4 6h10M18 6h2M4 12h6M14 12h6M4 18h12M20 18h0"/><circle cx="16" cy="6" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="18" cy="18" r="1.5"/></>,
    grid: <><rect x="4" y="4" width="7" height="7"/><rect x="13" y="4" width="7" height="7"/><rect x="4" y="13" width="7" height="7"/><rect x="13" y="13" width="7" height="7"/></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden="true">
      {icons[name] || icons.spark}
    </svg>
  );
}

// Image placeholder with stripes (for missing assets)
function ImgFrame({ src, alt, ratio = "1/1", className = "", fit = "contain" }) {
  return (
    <div className={"relative w-full " + className} style={{ aspectRatio: ratio }}>
      <img src={src} alt={alt} loading="lazy" decoding="async"
        style={{ width: "100%", height: "100%", objectFit: fit, display: "block" }} />
    </div>
  );
}

// Reusable badge
function MiniStat({ label, value, sub, dark = false }) {
  return (
    <div className={(dark ? "glass-dark text-white" : "glass text-ink-950") + " rounded-2xl p-4 lift"}>
      <div className={"text-[11px] uppercase tracking-[0.16em] " + (dark ? "text-white/60" : "text-mute-500")}>{label}</div>
      <div className="mt-1 text-[22px] font-semibold tracking-tightest">{value}</div>
      {sub && <div className={"text-[12px] mt-0.5 " + (dark ? "text-white/60" : "text-mute-500")}>{sub}</div>}
    </div>
  );
}

Object.assign(window, {
  FadeUp, Pill, CTA, Logo, Section, Container, I, ImgFrame, MiniStat,
  usePrefersReducedMotion, Splash,
});

// Splash: fullscreen contour-draw of the CondoClin mark
function Splash() {
  const [show, setShow] = useState(true);
  const [phase, setPhase] = useState("in");
  useEffect(() => {
    let mounted = true;
    const waitAssets = () => {
      const urls = [
        "assets/logo-laranja.png",
        "assets/tudo-em-um.png",
        "assets/celular-fundo.png",
        "assets/celular-frente.png",
        "assets/notebook.png",
        "assets/tela-notebook.png",
      ];
      return Promise.all(urls.map((u) => new Promise((resolve) => {
        const img = new Image();
        img.onload = img.onerror = () => resolve();
        img.src = u;
      })));
    };
    const minTime = new Promise((r) => setTimeout(r, 3600));
    Promise.all([waitAssets(), minTime]).then(() => {
      if (!mounted) return;
      setPhase("out");
      setTimeout(() => mounted && setShow(false), 600);
    });
    return () => { mounted = false; };
  }, []);

  if (!show) return null;
  return (
    <div
      aria-hidden="true"
      className="fixed inset-0 z-[100] flex items-center justify-center transition-opacity duration-[600ms] ease-out bg-paper-50"
      style={{
        opacity: phase === "out" ? 0 : 1,
        pointerEvents: phase === "out" ? "none" : "auto",
      }}
    >
      <div className="flex flex-col items-center" style={{ gap: "clamp(8px, 1.5vw, 16px)" }}>
        <div
          className="splash-stage relative"
          style={{ width: "clamp(180px, 38vw, 260px)", aspectRatio: "1 / 1" }}
        >
          <svg viewBox="0 0 1080 1080" className="splash-vector absolute inset-0 w-full h-full" fill="none" stroke="#fb5b1d" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            {(window.LOGO_PATHS || []).map((d, i) => (
              <path key={i} d={d} pathLength="1" style={{ animationDelay: `${i * 38}ms` }} />
            ))}
          </svg>
        </div>

        {/* CondoClin wordmark — contour-draws after the shield mark */}
        <div className="splash-wordmark" style={{ width: "clamp(220px, 46vw, 320px)" }}>
          <svg viewBox="0 0 2048 512" className="splash-vector-mark w-full h-auto block" fill="none" stroke="#fb5b1d" strokeWidth="6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            {(window.WORDMARK_PATHS || []).map((d, i) => (
              <path key={i} d={d} pathLength="1" style={{ animationDelay: `${1700 + i * 90}ms` }} />
            ))}
          </svg>
        </div>
      </div>

      <style>{`
        @keyframes contour-draw {
          0%   { stroke-dashoffset: 1; }
          100% { stroke-dashoffset: 0; }
        }
        .splash-vector path,
        .splash-vector-mark path {
          stroke-dasharray: 1;
          stroke-dashoffset: 1;
          animation: contour-draw 1100ms cubic-bezier(.65,0,.35,1) forwards;
        }
        @media (prefers-reduced-motion: reduce) {
          .splash-vector path,
          .splash-vector-mark path { animation: none !important; stroke-dashoffset: 0 !important; }
        }
      `}</style>
    </div>
  );
}
