/* global React, I18N */
const { useState, useEffect, useRef, useCallback, createContext, useContext } = React;

// ---------- Symbol (cartesian-curve from brand manual) ----------
function BrandSymbol({ size = 120, dark = false }){
  const stroke = dark ? "#F4EFE8" : "#1A1A1A";
  const axis = dark ? "#B8AFA2" : "#8A8278";
  const dot = dark ? "#C7A877" : "#A88A5C";
  return (
    <svg width={size} height={size} viewBox="22 21 96 99" fill="none" xmlns="http://www.w3.org/2000/svg">
      <g transform="rotate(90 70 70)">
        <line x1="70" y1="30" x2="70" y2="110" stroke={axis} strokeWidth="0.6" opacity=".85"></line>
        <line x1="25" y1="70" x2="115" y2="70" stroke={axis} strokeWidth="0.6" opacity=".85"></line>
        <path d="M25,105 Q45,25 70,55 Q95,85 115,35" stroke={stroke} strokeWidth="1.2" strokeLinecap="round"></path>
        <circle cx="117.4" cy="29.4" r="2" fill={dot}></circle>
      </g>
    </svg>
  );
}

// ---------- Wordmark ----------
function Wordmark({ className = "", style }){
  return (
    <span className={`wordmark ${className}`} style={style}>
      <span className="r">R</span>odrigo<span className="dot"></span> Benítez
    </span>
  );
}

// ---------- Liquid Metal CTA ----------
function LiquidCTA({ children, light = false, href = "#contact", onClick, target, rel, dataCta }){
  return (
    <a className={`liquid-cta ${light ? "light" : ""}`} href={href} onClick={onClick} target={target} rel={rel} data-cta={dataCta}>
      <span>{children}</span>
      <span className="arr"></span>
    </a>
  );
}

// ---------- Lang context ----------
const LangCtx = createContext({ lang: "en", setLang: () => {}, t: I18N.en });
function useLang(){ return useContext(LangCtx); }

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

// ---------- Nav ----------
function Nav({ darkMode = false }){
  const { lang, setLang, t } = useLang();
  const [solid, setSolid] = useState(false);
  useEffect(() => {
    const onScroll = () => setSolid(window.scrollY > 50);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={`nav ${solid ? "solid" : ""} ${darkMode ? "dark" : ""}`}>
      <a href="#top" style={{ textDecoration: "none", display: "flex", alignItems: "center", gap: 10 }}>
        <BrandSymbol size={28} dark={darkMode} />
        <Wordmark className="brand" style={{ fontSize: 22 }} />
      </a>
      <div className="links">
        <a href="#services">{t.nav.work}</a>
        <a href="#gallery">{t.nav.gallery}</a>
        <a href="#cases">{t.nav.cases}</a>
        <a href="#process">{t.nav.process}</a>
        <a href="#about">{t.nav.about}</a>
      </div>
      <div className="right">
        <div className="lang">
          <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
          <button className={lang === "es" ? "active" : ""} onClick={() => setLang("es")}>ES</button>
        </div>
        <a href="https://ig.me/m/dr.rodrigobenitez" target="_blank" rel="noopener" data-cta="reservar-consulta-privada" className="liquid-cta" style={{ "--h": "40px", padding: "0 18px", fontSize: 11 }}>
          <span>{t.nav.book}</span>
          <span className="arr"></span>
        </a>
      </div>
    </nav>
  );
}

// ---------- Before/After Card ----------
function BeforeAfterCard({ before, after, caseNo, bScale, bOrigin = "50% 50%", aPos }){
  const [p, setP] = useState(50);
  const [ratio, setRatio] = useState(null); // natural width/height
  const ref = useRef(null);
  const dragging = useRef(false);
  const { t } = useLang();

  // Detect natural aspect ratio so the card frames the image without cropping
  useEffect(() => {
    let cancelled = false;
    const img = new Image();
    img.onload = () => {
      if (cancelled) return;
      if (img.naturalWidth && img.naturalHeight){
        setRatio(img.naturalWidth / img.naturalHeight);
      }
    };
    img.src = before;
    return () => { cancelled = true; };
  }, [before]);

  const update = useCallback((clientX) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const x = Math.max(0, Math.min(r.width, clientX - r.left));
    setP((x / r.width) * 100);
  }, []);

  const onDown = (e) => {
    dragging.current = true;
    update(e.touches ? e.touches[0].clientX : e.clientX);
  };
  const onMove = (e) => {
    if (!dragging.current) return;
    update(e.touches ? e.touches[0].clientX : e.clientX);
  };
  const onUp = () => { dragging.current = false; };

  useEffect(() => {
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseup", onUp);
    window.addEventListener("touchmove", onMove);
    window.addEventListener("touchend", onUp);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseup", onUp);
      window.removeEventListener("touchmove", onMove);
      window.removeEventListener("touchend", onUp);
    };
  }, []);

  // gentle pulse on first paint
  const [pulsed, setPulsed] = useState(false);
  useEffect(() => {
    if (pulsed) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting){
          let v = 50, dir = 1, n = 0;
          const id = setInterval(() => {
            v += dir * 0.7; n++;
            if (v > 62){ dir = -1; }
            if (v < 38){ dir = 1; }
            setP(v);
            if (n > 100){ clearInterval(id); setP(50); setPulsed(true); }
          }, 16);
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.4 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [pulsed]);

  return (
    <div
      className="ba-card"
      ref={ref}
      style={{ "--p": `${p}%`, aspectRatio: ratio ? String(ratio) : "4 / 5" }}
      onMouseDown={onDown}
      onTouchStart={onDown}
    >
      <div className="layer before" style={{ backgroundImage: `url("${before}")`, ...(bScale ? { transform: `scale(${bScale})`, transformOrigin: bOrigin } : {}) }}></div>
      <div className="layer after" style={{ backgroundImage: `url("${after}")`, ...(aPos ? { backgroundPosition: aPos } : {}) }}></div>
      <div className="tag left">{t.gallery.before}</div>
      <div className="tag right">{t.gallery.after}</div>
      <div className="case-no">{t.gallery.caseLabel} · {String(caseNo).padStart(3, "0")}</div>
      <div className="divider"></div>
      <div className="handle"></div>
    </div>
  );
}

Object.assign(window, { BrandSymbol, Wordmark, LiquidCTA, LangCtx, useLang, useReveal, Nav, BeforeAfterCard });
