/* FinBalance Pro — v4 · shared primitives (chips, icons, CTAs, layout) */

const { useState, useEffect, useRef } = React;

function Container({ children, narrow = false, style = {} }) {
  return (
    <div style={{
      maxWidth: narrow ? 960 : "var(--maxw)",
      margin: "0 auto",
      padding: "0 var(--pad)",
      ...style,
    }}>{children}</div>
  );
}

/* ── Inline chips with mini-icons (signature element from reference) ────── */

function Chip({ tone = "peach", icon, children }) {
  return (
    <span className={`chip chip-${tone}`}>
      {icon ? <ChipIcon kind={icon} /> : null}
      <span>{children}</span>
    </span>
  );
}

function ChipIcon({ kind }) {
  const s = 14;
  const stroke = "currentColor";
  const sw = 2;
  switch (kind) {
    case "chart":
      return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw}><path d="M3 20h18M6 16V9m4 7V5m4 11v-7m4 7v-9"/></svg>;
    case "xlsx":
      return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw}><rect x="4" y="4" width="16" height="16" rx="1.5"/><path d="M9 8l6 8M15 8l-6 8"/></svg>;
    case "bolt":
      return <svg width={s} height={s} viewBox="0 0 24 24" fill={stroke}><path d="M13 2L4 14h6l-1 8 9-12h-6l1-8z"/></svg>;
    case "bank":
      return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw}><path d="M3 10h18L12 3 3 10zM5 10v8m4-8v8m6-8v8m4-8v8M3 20h18"/></svg>;
    case "shift":
      return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw}><path d="M4 12h12M12 8l4 4-4 4M20 6v12"/></svg>;
    case "pdf":
      return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw}><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><path d="M14 3v6h6"/></svg>;
    case "clock":
      return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
    case "check":
      return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw}><path d="M5 12l4 4 10-11"/></svg>;
    case "star":
      return <svg width={s} height={s} viewBox="0 0 24 24" fill={stroke}><path d="M12 2l3 7 7 .8-5 5 1.5 7L12 18l-6.5 3.8L7 14.8 2 9.8 9 9z"/></svg>;
    default:
      return null;
  }
}

/* ── CTAs ───────────────────────────────────────────────────────────────── */

function PrimaryCTA({ children, size = "md", arrow = true, href = "#demo", variant = "navy" }) {
  const sizes = {
    md: { padding: "12px 22px", fontSize: 15, borderRadius: 999 },
    lg: { padding: "15px 28px", fontSize: 16, borderRadius: 999 },
  };
  const variants = {
    navy:  { bg: "var(--navy)",  color: "var(--white)", hoverBg: "var(--navy-mid)" },
    teal:  { bg: "var(--teal)",  color: "var(--navy)",  hoverBg: "var(--teal-dark)" },
    white: { bg: "var(--white)", color: "var(--navy)",  hoverBg: "rgba(255,255,255,0.92)" },
  };
  const v = variants[variant];
  const onClick = (e) => {
    if (href === "#demo") { e.preventDefault(); window.openDemoModal && window.openDemoModal(); }
  };
  return (
    <a href={href} onClick={onClick} style={{
      display: "inline-flex", alignItems: "center", gap: 10,
      background: v.bg, color: v.color,
      textDecoration: "none",
      fontWeight: 600,
      letterSpacing: "-0.005em",
      whiteSpace: "nowrap",
      border: "none",
      cursor: "pointer",
      transition: "background .15s ease, transform .15s ease, box-shadow .15s ease",
      boxShadow: "0 1px 2px rgba(13,34,64,0.18)",
      ...sizes[size],
    }}
      onMouseOver={(e)=>{ e.currentTarget.style.background = v.hoverBg; e.currentTarget.style.transform = "translateY(-1px)"; e.currentTarget.style.boxShadow = "0 8px 22px -8px rgba(13,34,64,0.32)"; }}
      onMouseOut={(e)=>{ e.currentTarget.style.background = v.bg; e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = "0 1px 2px rgba(13,34,64,0.18)"; }}
    >
      <span>{children}</span>
      {arrow ? <span style={{ display: "inline-block" }}>→</span> : null}
    </a>
  );
}

function GhostLink({ children, href = "#", light = false }) {
  return (
    <a href={href} style={{
      display: "inline-flex", alignItems: "center", gap: 8,
      color: light ? "var(--white)" : "var(--navy)",
      textDecoration: "none",
      fontWeight: 600,
      fontSize: 15,
      padding: "12px 0",
    }}>
      <span style={{ borderBottom: light ? "1px solid rgba(255,255,255,0.4)" : "1px solid var(--navy)", paddingBottom: 1 }}>{children}</span>
      <span>→</span>
    </a>
  );
}

/* ── Eyebrow ────────────────────────────────────────────────────────────── */

function Eyebrow({ children, tone = "navy" }) {
  const color = tone === "teal" ? "var(--teal-dark)" :
                tone === "light" ? "var(--teal)" :
                "var(--ink-mid)";
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 8,
      fontSize: 13, fontWeight: 600,
      color, letterSpacing: "0.12em", textTransform: "uppercase",
    }}>
      <span style={{ width: 18, height: 1, background: "currentColor", opacity: 0.6 }}></span>
      <span>{children}</span>
    </span>
  );
}

/* ── Stars + trust strip ────────────────────────────────────────────────── */

function StarRating({ value = 4.9, count = 28 }) {
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
      <div style={{ display: "inline-flex", gap: 2 }}>
        {[0,1,2,3,4].map(i => (
          <svg key={i} width="15" height="15" viewBox="0 0 24 24" fill="#1a3f67">
            <path d="M12 2l3 7 7 .8-5 5 1.5 7L12 18l-6.5 3.8L7 14.8 2 9.8 9 9z"/>
          </svg>
        ))}
      </div>
      <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--navy)" }}>{value.toFixed(1)} / 5</span>
      <span style={{ fontSize: 13.5, color: "var(--ink-soft)" }}>· {count} responsabili intervistati</span>
    </div>
  );
}

/* ── Logo ────────────────────────────────────────────────────────────────── */

function Logo({ height = 28, light = false }) {
  return (
    <a href="#" style={{ display: "inline-flex", alignItems: "center", textDecoration: "none" }}>
      <img src="assets/finbalance-logo.png" alt="FinBalance Pro"
           style={{ height, filter: light ? "brightness(0) invert(1)" : "none" }} />
    </a>
  );
}

/* ── Geometric background — large stacked chevrons (reference signature) ─── */

function HeroBackdrop() {
  return (
    <div aria-hidden style={{
      position: "absolute", inset: 0, overflow: "hidden", pointerEvents: "none",
    }}>
      {/* pastel mesh gradient — animated panning */}
      <div className="fbp-bg-pan" style={{
        position: "absolute", inset: 0,
        backgroundImage: "radial-gradient(70% 60% at 8% 35%, var(--peach-soft) 0%, transparent 70%), \
                          radial-gradient(75% 70% at 92% 35%, var(--sky-soft) 0%, transparent 70%), \
                          radial-gradient(70% 50% at 50% 100%, var(--lilac-soft) 0%, transparent 60%), \
                          linear-gradient(180deg, #fafaf7 0%, #ffffff 100%)",
        backgroundSize: "140% 140%, 140% 140%, 140% 140%, 100% 100%",
        backgroundRepeat: "no-repeat",
        animation: "fbp-bg-pan 22s ease-in-out infinite",
        willChange: "background-position",
      }}></div>

      {/* secondary slow-floating soft blob */}
      <div aria-hidden style={{
        position: "absolute", top: "-10%", left: "30%",
        width: 520, height: 520,
        background: "radial-gradient(circle, rgba(255,216,168,0.32) 0%, transparent 65%)",
        filter: "blur(12px)",
        animation: "fbp-floatY 14s ease-in-out infinite",
        willChange: "transform",
      }}></div>
      <div aria-hidden style={{
        position: "absolute", bottom: "-12%", right: "10%",
        width: 580, height: 580,
        background: "radial-gradient(circle, rgba(200,219,255,0.34) 0%, transparent 65%)",
        filter: "blur(14px)",
        animation: "fbp-floatY 18s ease-in-out infinite reverse",
        willChange: "transform",
      }}></div>

      {/* large chevron field — slow skew/drift */}
      <svg viewBox="0 0 1400 900" preserveAspectRatio="xMidYMid slice"
           style={{
             position: "absolute", inset: 0, width: "100%", height: "100%",
             opacity: 0.55,
             animation: "fbp-skew 16s ease-in-out infinite",
             willChange: "transform",
           }}>
        <defs>
          <linearGradient id="cg1" x1="0" x2="1" y1="0" y2="1">
            <stop offset="0%"  stopColor="#ffd8a8" stopOpacity="0.55"/>
            <stop offset="55%" stopColor="#c8dbff" stopOpacity="0.55"/>
            <stop offset="100%" stopColor="#e0d4ff" stopOpacity="0.55"/>
          </linearGradient>
          <linearGradient id="cg2" x1="0" x2="1" y1="0" y2="0">
            <stop offset="0%" stopColor="#ffe7c9" stopOpacity="0.0"/>
            <stop offset="50%" stopColor="#ffe7c9" stopOpacity="0.5"/>
            <stop offset="100%" stopColor="#e0eaff" stopOpacity="0.5"/>
          </linearGradient>
        </defs>
        {/* stack of skewed rectangles from left to right, larger and softer */}
        {[0,1,2,3,4,5,6].map(i => (
          <rect key={i}
            x={120 + i*180}
            y={-100}
            width="220"
            height="1100"
            fill="url(#cg1)"
            opacity={0.18 + (i % 3) * 0.05}
            transform={`skewX(-14)`}/>
        ))}
      </svg>
    </div>
  );
}

/* ── Decorative inline arrow ───────────────────────────────────────────── */

function ArrowMark({ tone = "ink" }) {
  const color = tone === "teal" ? "var(--teal-dark)" : tone === "soft" ? "var(--ink-soft)" : "var(--navy)";
  return <span style={{ color, fontWeight: 400, marginRight: 8 }}>→</span>;
}

Object.assign(window, {
  Container, Chip, ChipIcon, PrimaryCTA, GhostLink, Eyebrow, StarRating, Logo, HeroBackdrop, ArrowMark, Reveal
});

/* ─── Animations: global CSS + scroll-reveal helper ────────────────────── */

(function injectAnimCSS(){
  if (document.getElementById('__fbp_anim')) return;
  const s = document.createElement('style');
  s.id = '__fbp_anim';
  s.textContent = `
    @keyframes fbp-fadeUp {
      from { opacity: 0; transform: translateY(14px); }
      to   { opacity: 1; transform: translateY(0); }
    }
    @keyframes fbp-popIn {
      0%   { opacity: 0; transform: translateY(6px) scale(0.92); }
      60%  { opacity: 1; transform: translateY(0)   scale(1.03); }
      100% { opacity: 1; transform: translateY(0)   scale(1); }
    }
    @keyframes fbp-drift {
      0%   { transform: translate3d(0, 0, 0); }
      50%  { transform: translate3d(18px, -10px, 0); }
      100% { transform: translate3d(0, 0, 0); }
    }
    @keyframes fbp-floatY {
      0%, 100% { transform: translate3d(0, 0, 0); }
      50%      { transform: translate3d(-12px, 16px, 0); }
    }
    @keyframes fbp-bg-pan {
      0%   { background-position: 0% 50%, 100% 50%, 50% 100%, 0 0; }
      50%  { background-position: 8% 42%, 92% 58%, 50% 96%, 0 0; }
      100% { background-position: 0% 50%, 100% 50%, 50% 100%, 0 0; }
    }
    @keyframes fbp-skew {
      0%   { transform: translate3d(0, 0, 0) skewX(0deg); }
      50%  { transform: translate3d(8px, -6px, 0) skewX(0.6deg); }
      100% { transform: translate3d(0, 0, 0) skewX(0deg); }
    }
    @keyframes fbp-glow {
      0%, 100% { opacity: 0.55; }
      50%      { opacity: 0.75; }
    }
    @keyframes fbp-nudge {
      0%, 100% { transform: translateX(0); }
      50%      { transform: translateX(4px); }
    }

    /* Hero entrance — staggered */
    .fbp-hero-anim > * { opacity: 0; animation: fbp-fadeUp .7s cubic-bezier(.2,.7,.2,1) forwards; }
    .fbp-hero-anim > *:nth-child(1) { animation-delay: 0.05s; }
    .fbp-hero-anim > *:nth-child(2) { animation-delay: 0.18s; }
    .fbp-hero-anim > *:nth-child(3) { animation-delay: 0.36s; }
    .fbp-hero-anim > *:nth-child(4) { animation-delay: 0.50s; }

    /* Chips inside hero pop-in on top of the headline rise */
    .fbp-hero-anim .chip { animation: fbp-popIn .7s cubic-bezier(.2,1.3,.4,1) both; }
    .fbp-hero-anim h1 .chip:nth-of-type(1) { animation-delay: 0.55s; }
    .fbp-hero-anim h1 .chip:nth-of-type(2) { animation-delay: 0.70s; }
    .fbp-hero-anim h1 .chip:nth-of-type(3) { animation-delay: 0.85s; }

    /* Mesh background — slow drift */
    .fbp-mesh-drift { animation: fbp-drift 18s ease-in-out infinite; will-change: transform; }

    /* Scroll reveal — initial state */
    .fbp-reveal { opacity: 0; transform: translateY(18px); transition: opacity .7s ease, transform .7s cubic-bezier(.2,.7,.2,1); will-change: opacity, transform; }
    .fbp-reveal.fbp-in { opacity: 1; transform: translateY(0); }

    /* CTA arrow micro-interaction (override default static arrow) */
    a:hover > span:last-child { transition: transform .2s ease; }

    /* Respect reduced motion */
    @media (prefers-reduced-motion: reduce) {
      .fbp-hero-anim > *,
      .fbp-hero-anim .chip,
      .fbp-mesh-drift,
      .fbp-bg-pan,
      .fbp-reveal { animation: none !important; opacity: 1 !important; transform: none !important; transition: none !important; }
      [style*="fbp-floatY"], [style*="fbp-skew"], [style*="fbp-bg-pan"] { animation: none !important; }
    }
  `;
  document.head.appendChild(s);
})();

/* Reveal — IntersectionObserver wrapper to fade-in children on scroll */
function Reveal({ children, delay = 0, as = "div", style = {}, ...rest }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (typeof IntersectionObserver === 'undefined') { el.classList.add('fbp-in'); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          el.classList.add('fbp-in');
          io.unobserve(el);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const Tag = as;
  return (
    <Tag ref={ref} className="fbp-reveal" style={{ transitionDelay: `${delay}ms`, ...style }} {...rest}>
      {children}
    </Tag>
  );
}
