/* global React */
// FORMA primitives — shared building blocks used across all pages.
// Loaded as a Babel script; exposes globals on window at the end.

const { useState: usePrim, useEffect: useEffPrim, useRef: useRefPrim } = React;

/* ── FORMA "C" mark ───────────────────────────────────────────── */
function Mark({ size = 24, color = 'currentColor', style }) {
  return (
    <svg width={size} height={size} viewBox="0 0 64 64" fill={color} style={style} aria-hidden="true">
      <path fillRule="evenodd" clipRule="evenodd" d="M52.78 20A24 24 0 1 0 52.78 44L44.12 39A14 14 0 1 1 44.12 25Z"/>
      <circle cx="32" cy="32" r="5"/>
    </svg>
  );
}

/* ── Editorial divider: ——— • ——— ───────────────────────────── */
function Divider({ pad = 64 }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14, padding: `${pad}px 0` }}>
      <span style={{ width: 100, height: 1, background: 'var(--color-border-strong)' }} />
      <span style={{ width: 7, height: 7, borderRadius: '9999px', background: 'var(--color-primary)' }} />
      <span style={{ width: 100, height: 1, background: 'var(--color-border-strong)' }} />
    </div>
  );
}

/* ── Eyebrow label ──────────────────────────────────────────── */
function Eyebrow({ children, color, style }) {
  return (
    <div style={{
      fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 13,
      letterSpacing: '0.12em', textTransform: 'uppercase',
      color: color || 'var(--color-primary)',
      ...style,
    }}>{children}</div>
  );
}

/* ── Reveal on scroll ──────────────────────────────────────── */
/* Reveal — passthrough. Le animazioni d'entrata ora arrivano solo dalle
   classi anim-* (char-reveal sui titoli, mask-wipe sulle immagini) gestite
   da GSAP, così i titoli fanno il reveal carattere-per-carattere senza il
   fade del wrapper che si sommava. Mantiene style/className/as per il layout. */
function Reveal({ children, as: As = 'div', style, className }) {
  return (
    <As className={className} style={style}>{children}</As>
  );
}

/* ── Placeholder photo: warm tinted block, suggests photography
       Variants give different palettes so a page reads as a collection,
       not one repeated block. ────────────────────────────────── */
const PHOTO_VARIANTS = {
  warm:   { from: '#d4bca0', mid: '#a08b6f', to: '#5d4f3d' },
  rose:   { from: '#e8c9c4', mid: '#b78c87', to: '#6b4742' },
  sand:   { from: '#e3d3b6', mid: '#a18c6d', to: '#5e4d36' },
  olive:  { from: '#c4bea0', mid: '#867f63', to: '#4a4632' },
  taupe:  { from: '#bcaea0', mid: '#7d6e60', to: '#3f342a' },
  bronze: { from: '#d6b89a', mid: '#8d6f53', to: '#4e3b29' },
};
function PhotoBlock({ variant = 'warm', label, radius = 12, style, children, ratio }) {
  const v = PHOTO_VARIANTS[variant] || PHOTO_VARIANTS.warm;
  return (
    <div style={{
      position: 'relative', borderRadius: radius, overflow: 'hidden',
      background: `linear-gradient(140deg, ${v.from} 0%, ${v.mid} 55%, ${v.to} 100%)`,
      boxShadow: '0 24px 60px rgba(26,26,26,.10)',
      aspectRatio: ratio,
      ...style,
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at 32% 24%, rgba(255,255,255,.36) 0%, transparent 50%), radial-gradient(ellipse at 78% 82%, rgba(0,0,0,.22) 0%, transparent 60%)',
      }} />
      {label && (
        <div style={{
          position: 'absolute', left: 16, bottom: 14,
          fontFamily: 'Inter, sans-serif', fontSize: 10.5,
          color: 'rgba(249, 244, 237,.62)', letterSpacing: '0.1em', textTransform: 'uppercase',
        }}>{label}</div>
      )}
      {children}
    </div>
  );
}

/* ── Pink circle background — signature pattern ────────────── */
function PinkCircle({ size = 320, top, left, right, bottom, style }) {
  return (
    <div style={{
      position: 'absolute', width: size, height: size, borderRadius: '9999px',
      background: 'var(--color-accent-pink)', zIndex: 0,
      top, left, right, bottom,
      ...style,
    }} />
  );
}

/* ── Floating stat card ────────────────────────────────────── */
function FloatingStatCard({ icon, big, label, style }) {
  return (
    <div style={{
      background: 'var(--color-background)', borderRadius: 8,
      padding: '18px 22px',
      boxShadow: 'var(--shadow-float)',
      minWidth: 180, display: 'flex', flexDirection: 'column', gap: 6,
      ...style,
    }}>
      {icon && <div style={{ color: 'var(--color-primary)' }}>{icon}</div>}
      <div className="tnum" style={{
        fontFamily: 'Fraunces, serif', fontWeight: 600,
        fontSize: 44, lineHeight: 1, color: 'var(--color-primary)',
      }}>{big}</div>
      <div style={{
        fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 11,
        letterSpacing: '0.12em', textTransform: 'uppercase',
        color: 'var(--color-text-secondary)', lineHeight: 1.4,
      }}>{label}</div>
    </div>
  );
}

/* ── CTA primary button — single source of truth ──────────────
   Bordeaux primary by default. Hover: a white circle anchored at
   the top-right corner expands from scale(0) to cover the button;
   a second copy of the label (bordeaux) is overlaid and clipped to
   that same circle, so the text under the white area is already
   bordeaux while the rest is still cream — no "invisible" frame.
   `light` prop is a no-op for now. ─────────────────────────── */
function CTAButton({ children = 'Prenota la tua consulenza GRATUITA', onClick, light, fullWidth, size = 'md', type = 'button', className }) {
  const [hover, setHover] = usePrim(false);
  const [active, setActive] = usePrim(false);
  const pad = size === 'lg' ? '16px 32px' : size === 'sm' ? '10px 18px' : '14px 24px';
  const fs  = size === 'lg' ? 17 : size === 'sm' ? 14.5 : 16;
  const base      = '#700e10';   // bordeaux primary
  const fillColor = '#FFFFFF';   // pure white (the expanding circle / final hover bg)
  const textBase  = '#F9F4ED';
  const textHover = '#700e10';
  const dur = '600ms';
  const ease = 'cubic-bezier(.65, 0, .35, 1)';
  const labelStyle = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    fontFamily: 'Inter, sans-serif', fontWeight: 700, fontSize: fs,
    letterSpacing: '-0.5px', whiteSpace: 'nowrap',
  };
  return (
    <button
      type={type}
      onClick={onClick}
      className={['pf-btn', className].filter(Boolean).join(' ')}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setActive(false); }}
      onMouseDown={() => setActive(true)}
      onMouseUp={() => setActive(false)}
      style={{
        position: 'relative',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        ...labelStyle,
        background: base, color: textBase,
        border: 'none', borderRadius: 8,
        padding: pad, cursor: 'pointer',
        width: fullWidth ? '100%' : 'auto',
        overflow: 'hidden', isolation: 'isolate',
        transform: active ? 'scale(0.985)' : 'scale(1)',
        boxShadow: hover
          ? '0 14px 32px rgba(56, 32, 20, 0.22), 0 4px 10px rgba(56, 32, 20, 0.12)'
          : '0 0 0 rgba(56, 32, 20, 0)',
        transition: 'transform 120ms cubic-bezier(.22,1,.36,1), box-shadow 600ms cubic-bezier(.65, 0, .35, 1)',
      }}
    >
      {/* Layer 1 — testo cream sempre presente sotto */}
      <span style={{ position: 'relative', zIndex: 1 }}>{children}</span>

      {/* Layer 2 — cerchio bianco che esce dall'angolo top-right */}
      <span aria-hidden="true" style={{
        position: 'absolute',
        width: 40, height: 40,
        top: -20, right: -20,
        background: fillColor,
        borderRadius: '50%',
        transform: hover ? 'scale(22)' : 'scale(0)',
        transformOrigin: 'center',
        transition: `transform ${dur} ${ease}`,
        zIndex: 2,
      }} />

      {/* Layer 3 — testo bordeaux ritagliato sulla circonferenza in espansione */}
      <span aria-hidden="true" style={{
        position: 'absolute', inset: 0,
        ...labelStyle,
        padding: pad,
        color: textHover,
        clipPath: hover ? 'circle(880px at 100% 0)' : 'circle(0 at 100% 0)',
        WebkitClipPath: hover ? 'circle(880px at 100% 0)' : 'circle(0 at 100% 0)',
        transition: `clip-path ${dur} ${ease}, -webkit-clip-path ${dur} ${ease}`,
        pointerEvents: 'none',
        zIndex: 3,
      }}>{children}</span>
    </button>
  );
}

/* ── CTA Banner — used 10+ times across the site
   variant="inline"  → centered button
   variant="banner"  → full-width section with title + button + subtitle */
function CTABanner({ variant = 'inline', title, subtitle, onCTA, bg = 'pink' }) {
  if (variant === 'inline') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, padding: '40px 0' }}>
        <CTAButton onClick={onCTA} size="lg" />
        {subtitle && (
          <div style={{
            fontFamily: 'Inter, sans-serif', fontSize: 13, color: 'var(--color-text-muted)',
            letterSpacing: '0.04em',
          }}>{subtitle}</div>
        )}
      </div>
    );
  }
  const bgColor = bg === 'pink' ? '#fbeeee' : bg === 'cream' ? 'var(--color-surface-alt)' : 'var(--color-background)';
  return (
    <section style={{
      background: bgColor, padding: '88px 30px',
      borderTop: '1px solid var(--color-border)',
      borderBottom: '1px solid var(--color-border)',
    }}>
      <div style={{ maxWidth: 760, margin: '0 auto', textAlign: 'center' }}>
        {title && (
          <h2 className="anim-char-reveal" style={{
            fontFamily: 'Fraunces, serif', fontWeight: 600,
            fontSize: 'clamp(28px, 3.4vw, 42px)', lineHeight: 1.15,
            letterSpacing: '-0.01em', color: 'var(--color-text-primary)',
            margin: '0 0 24px',
          }}>{title}</h2>
        )}
        <CTAButton onClick={onCTA} size="lg" />
        {subtitle && (
          <div style={{
            fontFamily: 'Inter, sans-serif', fontSize: 14, color: 'var(--color-text-secondary)',
            marginTop: 14, letterSpacing: '0.02em',
          }}>{subtitle}</div>
        )}
      </div>
    </section>
  );
}

/* ── Parallax CTA section — slow parallax bg image + dark overlay top→0
       + content centrato con form 3-input. Usata sia da Metodo CTA finale
       sia da Chi-siamo closing. ─────────────────────────────── */
function ParallaxCTASection({ bgSrc, eyebrow, title, subtitle, onCTA }) {
  const sectionRef = useRefPrim(null);
  const bgRef = useRefPrim(null);

  useEffPrim(() => {
    const sec = sectionRef.current;
    const bg = bgRef.current;
    if (!sec || !bg) return;
    let raf = 0;
    const update = () => {
      raf = 0;
      const r = sec.getBoundingClientRect();
      const vh = window.innerHeight;
      // p ≈ -0.5 quando la sezione è sotto il viewport, +0.5 quando è sopra
      const p = (vh - r.top - r.height / 2 - vh / 2) / (vh + r.height);
      // Parallax più marcato: ±90px di traslazione, scale 1.30 per coprire i bordi
      bg.style.transform = `translateY(${(p * 180).toFixed(2)}px) scale(1.30)`;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <section ref={sectionRef} className="bg-parallax" style={{
      position: 'relative', overflow: 'hidden',
      padding: '110px 30px',
    }}>
      <div ref={bgRef} style={{
        position: 'absolute', inset: 0, zIndex: 0, willChange: 'transform',
      }}>
        <img src={bgSrc} alt="" aria-hidden="true"
          style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center', display: 'block' }} />
      </div>
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0, zIndex: 1,
        background: 'linear-gradient(to bottom, rgba(0,0,0,0.80) 0%, rgba(0,0,0,0.65) 100%)',
        pointerEvents: 'none',
      }} />

      <div style={{
        position: 'relative', zIndex: 2,
        maxWidth: 720, margin: '0 auto', textAlign: 'center',
        color: 'var(--color-text-on-dark)',
      }}>
        {eyebrow && (
          <Eyebrow color="rgba(249, 244, 237, 0.78)" style={{ marginBottom: 16 }}>{eyebrow}</Eyebrow>
        )}
        <h2 className="anim-char-reveal" style={{
          fontFamily: 'Fraunces, serif', fontWeight: 600,
          fontSize: 'clamp(40px, 4.6vw, 56px)', lineHeight: 1.05,
          letterSpacing: '-0.02em', color: 'var(--color-text-on-dark)',
          margin: '0 0 18px', textWrap: 'balance',
        }}>{title}</h2>
        {subtitle && (
          <p style={{
            fontFamily: 'Inter, sans-serif', fontSize: 18, lineHeight: 1.6,
            color: 'rgba(249, 244, 237, 0.85)', margin: '0 auto 36px', maxWidth: 540,
          }}>{subtitle}</p>
        )}

        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <CTAButton onClick={onCTA} size="lg" />
        </div>
      </div>
    </section>
  );
}

/* ── Video testimonial card — portrait 9:16, custom play overlay
       Click toggles play/pause. Mute toggles via the unmute button. ── */
function VideoTestimonialCard({ src, name, label }) {
  const videoRef = useRefPrim(null);
  const [playing, setPlaying] = usePrim(false);
  const [hover, setHover] = usePrim(false);
  const toggle = (e) => {
    e.stopPropagation();
    const v = videoRef.current;
    if (!v) return;
    if (v.paused) {
      v.muted = false;
      const p = v.play();
      if (p && p.catch) p.catch(() => { v.muted = true; v.play(); });
    } else {
      v.pause();
    }
  };
  return (
    <article
      onClick={toggle}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: 'relative', borderRadius: 12, overflow: 'hidden',
        aspectRatio: '9 / 16',
        cursor: 'pointer',
        background: 'var(--color-surface-alt)',
        boxShadow: hover ? 'var(--shadow-md)' : 'var(--shadow-xs)',
        transition: 'box-shadow 280ms cubic-bezier(.22,1,.36,1)',
      }}>
      <video
        ref={videoRef}
        src={src}
        muted
        loop
        playsInline
        preload="metadata"
        onPlay={() => setPlaying(true)}
        onPause={() => setPlaying(false)}
        style={{
          width: '100%', height: '100%',
          objectFit: 'cover', display: 'block',
        }}
      />
      {/* Bottom gradient overlay (only when not playing) */}
      {!playing && (
        <div aria-hidden="true" style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(to bottom, rgba(0,0,0,0) 45%, rgba(0,0,0,0.55) 100%)',
          pointerEvents: 'none',
        }} />
      )}
      {/* Play / pause indicator */}
      <div style={{
        position: 'absolute', top: '50%', left: '50%',
        transform: hover ? 'translate(-50%, -50%) scale(1.06)' : 'translate(-50%, -50%)',
        width: 64, height: 64, borderRadius: '9999px',
        background: 'rgba(255,255,255,0.94)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 8px 24px rgba(26,26,26,.22)',
        transition: 'transform 280ms cubic-bezier(.22,1,.36,1), opacity 280ms',
        opacity: playing ? (hover ? 0.85 : 0) : 1,
        pointerEvents: 'none',
      }}>
        {playing ? (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="var(--color-primary)">
            <rect x="6" y="5" width="4" height="14" rx="1"/>
            <rect x="14" y="5" width="4" height="14" rx="1"/>
          </svg>
        ) : (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="var(--color-primary)" style={{ marginLeft: 3 }}>
            <polygon points="6 4 20 12 6 20 6 4"/>
          </svg>
        )}
      </div>
      {/* Caption (name) */}
      {(name || label) && !playing && (
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0,
          padding: '16px 18px',
          color: 'var(--color-background)',
          pointerEvents: 'none',
        }}>
          {name && <div style={{ fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 15 }}>{name}</div>}
          {label && <div style={{ fontFamily: 'Fraunces, serif', fontStyle: 'italic', fontWeight: 400, fontSize: 14, lineHeight: 1.4, color: 'rgba(249, 244, 237,.85)', marginTop: 2 }}>{label}</div>}
        </div>
      )}
    </article>
  );
}

/* ── Logo mark watermark — uses the FORMA "C" as soft brand
       decoration in the background of select sections. Use it
       inside a position:relative container; place sparingly. ─ */
function LogoWatermark({ size = 360, top, right, bottom, left, rotate = 0, opacity = 0.04 }) {
  return (
    <div aria-hidden="true" style={{
      position: 'absolute',
      top, right, bottom, left,
      color: 'var(--color-primary)',
      opacity,
      transform: rotate ? `rotate(${rotate}deg)` : undefined,
      pointerEvents: 'none',
      userSelect: 'none',
      lineHeight: 0,
      zIndex: 0,
    }}>
      <Mark size={size} />
    </div>
  );
}

/* ── Section number watermark (giant decorative numeral) ──── */
function SectionWatermark({ n, top = 0, right, left, size = 200, color }) {
  return (
    <div style={{
      position: 'absolute', top, right, left,
      fontFamily: 'Fraunces, serif', fontWeight: 600,
      fontSize: size, lineHeight: 1,
      color: color || 'var(--color-primary)', opacity: 0.06,
      letterSpacing: '-0.04em', userSelect: 'none', pointerEvents: 'none',
      zIndex: 0,
    }}>{n}</div>
  );
}

/* ── Count-up number (animates on viewport entry) ─────────── */
function CountUp({ end, suffix = '', duration = 1400, style }) {
  const ref = useRefPrim(null);
  const [val, setVal] = usePrim(0);
  useEffPrim(() => {
    const el = ref.current;
    if (!el) return;
    let raf, started = false;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !started) {
        started = true;
        const t0 = performance.now();
        const tick = (t) => {
          const p = Math.min(1, (t - t0) / duration);
          const eased = 1 - Math.pow(1 - p, 3);
          setVal(Math.round(end * eased));
          if (p < 1) raf = requestAnimationFrame(tick);
        };
        raf = requestAnimationFrame(tick);
        io.disconnect();
      }
    }, { threshold: 0.5 });
    io.observe(el);
    return () => { io.disconnect(); cancelAnimationFrame(raf); };
  }, [end, duration]);
  return <span ref={ref} style={style}>{val}{suffix}</span>;
}

/* ── GHL embedded form (Clienti in Cloud) ──────────────────────
   Stesso form usato inline e dentro al popup. id univoco per istanza
   per evitare collisioni se più iframe coesistono nel DOM. ─────── */
function GHLForm({ instanceId = 'inline', height = 700 }) {
  const idStr = `inline-grMTfN2uFaBUIOtLdmnO-${instanceId}`;
  return (
    <iframe
      src="https://api.clientiincloud.it/widget/form/grMTfN2uFaBUIOtLdmnO"
      style={{ width: '100%', height: height, border: 'none', borderRadius: 15, display: 'block', background: 'transparent' }}
      allowtransparency="true"
      id={idStr}
      data-layout="{'id':'INLINE'}"
      data-trigger-type="alwaysShow"
      data-trigger-value=""
      data-activation-type="alwaysActivated"
      data-activation-value=""
      data-deactivation-type="neverDeactivate"
      data-deactivation-value=""
      data-form-name="FORM | Progetto Forma- Sito web"
      data-height="669"
      data-layout-iframe-id={idStr}
      data-form-id="grMTfN2uFaBUIOtLdmnO"
      title="FORM | Progetto Forma- Sito web"
    />
  );
}

/* ── FormModal — popup che contiene il GHLForm, aperto dai CTA ─── */
function FormModal({ open, onClose }) {
  useEffPrim(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    if (window.__lenis) window.__lenis.stop();
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
      if (window.__lenis && window.location.hash.replace(/^#\/?/, '') !== 'chi-siamo') {
        window.__lenis.start();
      }
    };
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '24px 16px',
        background: 'rgba(26,26,26,0.55)',
        backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
        animation: 'modalFadeIn 280ms cubic-bezier(.22,1,.36,1)',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          position: 'relative',
          width: '100%', maxWidth: 560,
          animation: 'modalPopIn 360ms cubic-bezier(.22,1,.36,1)',
        }}
      >
        <button
          onClick={onClose}
          aria-label="Chiudi"
          className="anim-cursor-hover"
          style={{
            position: 'absolute', top: -14, right: -6, zIndex: 2,
            width: 38, height: 38, borderRadius: '9999px',
            border: 'none',
            background: 'var(--color-primary)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', color: '#FFFFFF',
            boxShadow: '0 6px 18px rgba(0,0,0,0.3)',
          }}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            <line x1="6" y1="6" x2="18" y2="18"/><line x1="6" y1="18" x2="18" y2="6"/>
          </svg>
        </button>
        <div style={{ maxHeight: '92vh', overflowY: 'auto', borderRadius: 15 }}>
          <GHLForm instanceId="modal" height={680} />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Mark, Divider, Eyebrow, Reveal,
  PhotoBlock, PinkCircle, FloatingStatCard,
  CTAButton, CTABanner, LogoWatermark, SectionWatermark, CountUp,
  VideoTestimonialCard, ParallaxCTASection,
  GHLForm, FormModal,
});
