/* === Zebra Insurtech components — Vortik redesign === */

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

/* ---- Reveal on scroll ---- */
function Reveal({ children, delay = 0, as: As = "div", className = "", ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // If already in viewport on mount, show immediately (handles iframes/SSR/short pages).
    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight && r.bottom > 0) {
      setTimeout(() => setShown(true), delay);
      return;
    }
    // Safety fallback in case IntersectionObserver never fires.
    const fallback = setTimeout(() => setShown(true), 1200 + delay);
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setTimeout(() => setShown(true), delay); io.disconnect(); clearTimeout(fallback); }
    }, { threshold: 0.1 });
    io.observe(el);
    return () => { io.disconnect(); clearTimeout(fallback); };
  }, [delay]);
  return <As ref={ref} className={`reveal ${shown ? "in" : ""} ${className}`} {...rest}>{children}</As>;
}

/* ---- Count-up ---- */
function CountUp({ to, prefix = "", suffix = "", decimals = 0, duration = 1500 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) { setVal(to); return; }
    const run = () => {
      const start = performance.now();
      const tick = (now) => {
        const t = Math.min(1, (now - start) / duration);
        const ease = 1 - Math.pow(1 - t, 3);
        setVal(to * ease);
        if (t < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    };
    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight && r.bottom > 0) { run(); return; }
    const fallback = setTimeout(run, 1500);
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { run(); io.disconnect(); clearTimeout(fallback); }
    }, { threshold: 0.4 });
    io.observe(el);
    return () => { io.disconnect(); clearTimeout(fallback); };
  }, [to, duration]);
  const formatted = decimals > 0
    ? val.toFixed(decimals)
    : Math.round(val).toLocaleString('en-US');
  return <span ref={ref}>{prefix}{formatted}{suffix}</span>;
}

/* ---- Brand mark (stylized zebra stripes) ---- */
function BrandMark({ size = 26, color = "var(--orange)" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 26 26" fill="none" aria-hidden="true">
      <rect x="2" y="3" width="3" height="20" rx="1.5" fill={color} />
      <rect x="7" y="3" width="3" height="20" rx="1.5" fill={color} opacity="0.85" transform="skewX(-12)" />
      <rect x="13" y="3" width="3" height="20" rx="1.5" fill={color} opacity="0.7" transform="skewX(-12)" />
      <rect x="19" y="3" width="3" height="20" rx="1.5" fill={color} opacity="0.55" transform="skewX(-12)" />
    </svg>
  );
}

/* ---- Stripe divider ---- */
function StripeDivider({ color = "var(--orange)", opacity = 0.12 }) {
  return (
    <svg className="stripe-divider" viewBox="0 0 1440 24" preserveAspectRatio="none" aria-hidden="true">
      <defs>
        <pattern id="sd-pat" width="48" height="24" patternUnits="userSpaceOnUse" patternTransform="skewX(-22)">
          <rect width="24" height="24" fill={color} fillOpacity={opacity} />
        </pattern>
      </defs>
      <rect width="1440" height="24" fill="url(#sd-pat)" />
    </svg>
  );
}

/* ---- Check icon ---- */
function Check({ size = 16, color = "var(--orange)" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path d="M3 8.5L6.5 12L13 4.5" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

/* ---- Icons used in solution / dashboard ---- */
function IconAPI({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 28 28" fill="none" aria-hidden="true">
      <path d="M5 9l-3 5 3 5M23 9l3 5-3 5M16 5l-4 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}
function IconDash({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 28 28" fill="none" aria-hidden="true">
      <rect x="3" y="5" width="10" height="8" rx="1.5" stroke="currentColor" strokeWidth="2"/>
      <rect x="15" y="5" width="10" height="14" rx="1.5" stroke="currentColor" strokeWidth="2"/>
      <rect x="3" y="15" width="10" height="8" rx="1.5" stroke="currentColor" strokeWidth="2"/>
    </svg>
  );
}
function IconCash({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 28 28" fill="none" aria-hidden="true">
      <circle cx="14" cy="14" r="10" stroke="currentColor" strokeWidth="2"/>
      <path d="M14 8v12M17 10.5c0-1.4-1.3-2.5-3-2.5s-3 1.1-3 2.5 1.3 2 3 2.5 3 1.1 3 2.5-1.3 2.5-3 2.5-3-1.1-3-2.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
    </svg>
  );
}
function IconArrow({ size = 14 }) {
  return (
    <svg className="arr" width={size} height={size} viewBox="0 0 14 14" fill="none" aria-hidden="true">
      <path d="M3 7h8M7.5 3.5L11 7l-3.5 3.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

/* ---- Sparkline / area chart svg (dashboard) ---- */
function AreaChart({ data, color = "#FF6B1A", height = 180 }) {
  const W = 600, H = height, pad = 24;
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((v, i) => {
    const x = pad + (i / (data.length - 1)) * (W - pad * 2);
    const y = pad + (1 - (v - min) / (max - min || 1)) * (H - pad * 2);
    return [x, y];
  });
  const path = pts.map(([x, y], i) => (i === 0 ? `M${x},${y}` : `L${x},${y}`)).join(" ");
  const area = `${path} L${pts[pts.length-1][0]},${H-pad} L${pts[0][0]},${H-pad} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none" aria-hidden="true">
      <defs>
        <linearGradient id="ac-fill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.3"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      {[0,1,2,3].map(i => (
        <line key={i} x1={pad} x2={W-pad} y1={pad + i*((H-pad*2)/3)} y2={pad + i*((H-pad*2)/3)} stroke="rgba(255,255,255,0.05)" strokeDasharray="2 4"/>
      ))}
      <path d={area} fill="url(#ac-fill)"/>
      <path d={path} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round"/>
      {pts.map(([x,y], i) => i === pts.length-1 ? (
        <g key={i}>
          <circle cx={x} cy={y} r="4" fill={color}/>
          <circle cx={x} cy={y} r="9" fill={color} opacity="0.2"/>
        </g>
      ) : null)}
    </svg>
  );
}

function BarChart({ data, color = "#FF6B1A", height = 180 }) {
  const W = 280, H = height, pad = 18;
  const max = Math.max(...data);
  const bw = (W - pad * 2) / data.length;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none" aria-hidden="true">
      {data.map((v, i) => {
        const h = (v / max) * (H - pad * 2);
        const x = pad + i * bw + bw * 0.2;
        const y = H - pad - h;
        const w = bw * 0.6;
        return (
          <g key={i}>
            <rect x={x} y={pad} width={w} height={H - pad * 2} rx="3" fill="rgba(255,255,255,0.04)"/>
            <rect x={x} y={y} width={w} height={h} rx="3" fill={i === data.length - 1 ? color : "rgba(255,107,26,0.55)"}/>
          </g>
        );
      })}
    </svg>
  );
}

function DonutChart({ value = 78, color = "#00D27A", size = 130 }) {
  const r = 50;
  const c = 2 * Math.PI * r;
  const off = c - (value/100) * c;
  return (
    <svg width={size} height={size} viewBox="0 0 130 130" aria-hidden="true">
      <circle cx="65" cy="65" r={r} stroke="rgba(255,255,255,0.08)" strokeWidth="14" fill="none"/>
      <circle cx="65" cy="65" r={r} stroke={color} strokeWidth="14" fill="none"
              strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round"
              transform="rotate(-90 65 65)"/>
      <text x="65" y="62" textAnchor="middle" fill="#fff" fontFamily="Space Grotesk" fontSize="24" fontWeight="600">{value}%</text>
      <text x="65" y="80" textAnchor="middle" fill="rgba(255,255,255,0.5)" fontFamily="JetBrains Mono" fontSize="9">RETENCIÓN</text>
    </svg>
  );
}

/* ---- API isometric svg (placeholder) ---- */
function ApiIso() {
  return (
    <svg viewBox="0 0 360 280" aria-hidden="true">
      <defs>
        <linearGradient id="iso-g" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#FF8A47"/>
          <stop offset="100%" stopColor="#C24500"/>
        </linearGradient>
      </defs>
      {/* nodes */}
      <g stroke="#FF6B1A" strokeWidth="1.5" fill="none" opacity="0.7">
        <path d="M180 60 L260 110 L260 200 L180 250 L100 200 L100 110 Z"/>
        <path d="M180 60 L180 250 M100 110 L260 200 M260 110 L100 200"/>
      </g>
      <g fill="url(#iso-g)">
        <circle cx="180" cy="60" r="14"/>
        <circle cx="260" cy="110" r="10"/>
        <circle cx="260" cy="200" r="10"/>
        <circle cx="180" cy="250" r="14"/>
        <circle cx="100" cy="200" r="10"/>
        <circle cx="100" cy="110" r="10"/>
      </g>
      <g fill="#FF6B1A" opacity="0.9">
        <rect x="160" y="135" width="40" height="40" rx="6"/>
      </g>
      <text x="180" y="160" textAnchor="middle" fill="#0A0A0A" fontFamily="JetBrains Mono" fontWeight="600" fontSize="11">API</text>
    </svg>
  );
}

/* expose */
Object.assign(window, {
  Reveal, CountUp, BrandMark, StripeDivider, Check,
  IconAPI, IconDash, IconCash, IconArrow,
  AreaChart, BarChart, DonutChart, ApiIso,
});
