/* global React */
const { useState, useEffect, useRef, useCallback, useLayoutEffect } = React;

/* ---------------- Icons (stroke, 1.6, currentColor) ---------------- */
const I = {};
function mk(name, paths, opts){
  I[name] = function(props){
    props = props || {};
    var size = props.size || 18, sw = props.sw || 1.7, fill = props.fill || "none";
    var p = { width:size, height:size, viewBox:"0 0 24 24", fill:fill,
      stroke:"currentColor", strokeWidth:sw, strokeLinecap:"round", strokeLinejoin:"round",
      className:props.className, style:props.style };
    if(opts) Object.assign(p, opts);
    return React.createElement("svg", p, paths.map(function(d,i){ return React.createElement("path",{ key:i, d:d }); }));
  };
}
mk("arrow",      ["M5 12h14","M13 6l6 6-6 6"]);
mk("spark",      ["M12 3l1.6 4.6L18 9l-4.4 1.4L12 15l-1.6-4.6L6 9l4.4-1.4z","M19 14l.7 2 2 .7-2 .7-.7 2-.7-2-2-.7 2-.7z"]);
mk("doc",        ["M7 3h7l4 4v14H7z","M14 3v4h4","M10 12h6","M10 16h6"]);
mk("shield",     ["M12 3l7 3v5c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z","M9 12l2 2 4-4"]);
mk("chart",      ["M4 20V10","M10 20V4","M16 20v-7","M22 20H2"]);
mk("activity",   ["M3 12h4l2 6 4-14 2 8h6"]);
mk("workflow",   ["M5 5h5v5H5z","M14 14h5v5h-5z","M10 7h6a2 2 0 012 2v5"]);
mk("bolt",       ["M13 2L4 14h7l-1 8 9-12h-7z"]);
mk("check",      ["M5 12l5 5L20 7"]);
mk("copy",       ["M8 8h11v11H8z","M5 16V5h11"]);
mk("alert",      ["M12 3l9 16H3z","M12 10v4","M12 17h.01"]);
mk("upload",     ["M12 16V4","M8 8l4-4 4 4","M5 16v3a1 1 0 001 1h12a1 1 0 001-1v-3"]);
mk("quote",      ["M9 7H5v6h4l-2 4M19 7h-4v6h4l-2 4"]);
mk("plus",       ["M12 5v14","M5 12h14"]);
mk("clock",      ["M12 21a9 9 0 100-18 9 9 0 000 18z","M12 8v4l3 2"]);
mk("layers",     ["M12 3l9 5-9 5-9-5z","M3 13l9 5 9-5"]);
mk("link",       ["M9 13a4 4 0 005.66 0l3-3a4 4 0 10-5.66-5.66l-1 1","M15 11a4 4 0 00-5.66 0l-3 3a4 4 0 105.66 5.66l1-1"]);
mk("brain",      ["M9 4a3 3 0 00-3 3 3 3 0 00-1 5 3 3 0 002 5 3 3 0 005 0V4","M15 4a3 3 0 013 3 3 3 0 011 5 3 3 0 01-2 5"]);
mk("dollar",     ["M12 2v20","M17 6.5c0-2-2.2-3-5-3s-5 1-5 3.2c0 5 10 2.8 10 7.6 0 2.2-2.2 3.2-5 3.2s-5-1.2-5-3.2"]);
mk("mail",       ["M3 6h18v12H3z","M3 7l9 6 9-6"]);
mk("user",       ["M12 12a4 4 0 100-8 4 4 0 000 8z","M5 20a7 7 0 0114 0"]);
mk("chevron",    ["M6 9l6 6 6-6"]);
mk("pulse",      ["M3 12h3l2-7 4 14 3-9 2 2h4"]);

/* ---------------- Logo ---------------- */
function Logo({ size = 30 }){
  return (
    React.createElement("svg",{ width:size, height:size, viewBox:"0 0 40 40", className:"logo", "aria-hidden":true },
      React.createElement("circle",{ cx:20, cy:20, r:19, fill:"#16182a" }),
      React.createElement("circle",{ cx:20, cy:20, r:9.5, fill:"none", stroke:"#fff", strokeWidth:4.5 }),
      React.createElement("circle",{ cx:20, cy:20, r:3, fill:"#cfc7f2" })
    )
  );
}

/* ---------------- Buttons ---------------- */
function Button({ variant = "grad", icon = true, children, onClick, className = "", style }){
  const ref = useRef(null);
  // magnetic hover
  const onMove = (e)=>{
    const el = ref.current; if(!el) return;
    const r = el.getBoundingClientRect();
    const mx = (e.clientX - r.left - r.width/2);
    const my = (e.clientY - r.top - r.height/2);
    const m = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--motion'))||1;
    el.style.transform = `translate(${mx*0.18*m}px, ${my*0.22*m}px)`;
  };
  const reset = ()=>{ if(ref.current) ref.current.style.transform = ""; };
  return (
    React.createElement("button",{ ref, className:`btn btn-${variant} ${className}`, onClick,
      onMouseMove:onMove, onMouseLeave:reset, style },
      icon && React.createElement("span",{ className:"ic" }, React.createElement(I.arrow,{ size:13 })),
      React.createElement("span",null, children)
    )
  );
}

/* ---------------- Nav ---------------- */
const NAV = [
  { id:"home",      label:"Home" },
  { id:"product",   label:"Product" },
  { id:"solutions", label:"Solutions" },
  { id:"security",  label:"Security" },
  { id:"blog",      label:"Blog" },
  { id:"contact",   label:"Contact" },
];
// analyzer-flow views live under Product in the nav
const FLOW_VIEWS = ["new","analysis","raw"];
function Nav({ view, go }){
  const activeId = FLOW_VIEWS.indexOf(view) >= 0 ? "product" : view;
  const [scrolled, setScrolled] = useState(false);
  const pillRef = useRef(null);
  const btnRefs = useRef({});
  const [bg, setBg] = useState({ left:0, width:0 });
  const [bgReady, setBgReady] = useState(false);
  useEffect(()=>{
    const onScroll = ()=> setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll); onScroll();
    return ()=> window.removeEventListener("scroll", onScroll);
  },[]);
  useEffect(()=>{
    const measure = ()=>{ const b = btnRefs.current[activeId]; if(b) setBg({ left:b.offsetLeft, width:b.offsetWidth }); };
    measure();
    const r = requestAnimationFrame(()=>{ measure(); setBgReady(true); });
    const t = setTimeout(measure, 400);
    window.addEventListener("resize", measure);
    return ()=>{ cancelAnimationFrame(r); clearTimeout(t); window.removeEventListener("resize", measure); };
  },[activeId]);
  const rightLabel = view === "analysis" ? "View raw response" : "Start review";
  const rightGo = view === "analysis" ? ()=>go("raw") : ()=>go("new");
  return (
    React.createElement("nav",{ className:`navbar ${scrolled?"scrolled":""}` },
      React.createElement("div",{ className:"navbar-inner" },
        React.createElement("div",{ className:"brand", style:{cursor:"pointer"}, onClick:()=>go("home") },
          React.createElement(Logo,null), React.createElement("span",null,"MedCode")),
        React.createElement("div",{ className:"navpill", ref:pillRef },
          React.createElement("div",{ className:"pill-bg", style:{ left:bg.left, width:bg.width, transition: bgReady ? "left .4s cubic-bezier(.5,1.3,.4,1), width .4s cubic-bezier(.5,1.3,.4,1)" : "none" } }),
          NAV.map(n=>(
            React.createElement("button",{ key:n.id, ref:el=>btnRefs.current[n.id]=el,
              className: activeId===n.id?"active":"", onClick:()=>go(n.id) },
              React.createElement("span",null,n.label))
          ))
        ),
        React.createElement("div",{ className:"nav-right" },
          React.createElement(Button,{ variant:"grad", onClick:rightGo, style:{padding:"11px 17px"} }, rightLabel),
          React.createElement("button",{ className:"btn btn-dark", style:{padding:"11px 18px"}, onClick:()=>go("new") }, "Sign up")
        )
      )
    )
  );
}

/* ---------------- Mac window ---------------- */
function MacWindow({ title, children, dark = false, style, className = "", barRight }){
  const base = dark ? {background:"#11132a",border:"1px solid #20233f"} : {};
  return (
    React.createElement("div",{ className:`mac ${className}`, style:Object.assign({}, base, style) },
      React.createElement("div",{ className:"mac-bar", style: dark?{borderBottom:"1px solid #20233f"}:undefined },
        React.createElement("span",{ className:"mac-dot", style:{background:"#f5655b"} }),
        React.createElement("span",{ className:"mac-dot", style:{background:"#f6be42"} }),
        React.createElement("span",{ className:"mac-dot", style:{background:"#52c93f"} }),
        React.createElement("span",{ className:"mac-title", style: dark?{color:"#6b6f96"}:undefined }, title),
        barRight && React.createElement("div",{ style:{marginLeft:"auto", position:"relative", zIndex:1} }, barRight)
      ),
      children
    )
  );
}

/* ---------------- Reveal (scroll-in) ---------------- */
function Reveal({ children, delay = 0, scale = false, as = "div", className = "", style }){
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  const [instant, setInstant] = useState(false);
  // Before paint: if the tab is hidden (transitions are frozen), snap in-view
  // elements to visible with no transition so content never gets stuck at opacity 0.
  useLayoutEffect(()=>{
    const el = ref.current; if(!el) return;
    const r = el.getBoundingClientRect();
    const iv = r.top < (window.innerHeight||800)*0.95 && r.bottom > -40;
    if(iv && document.hidden){ setInstant(true); setSeen(true); }
  },[]);
  useEffect(()=>{
    if(seen) return;
    const el = ref.current; if(!el) return;
    let done = false;
    const reveal = ()=>{ if(!done){ done = true; setSeen(true); setTimeout(()=>setInstant(true), 900); } };
    const inView = ()=>{ const r = el.getBoundingClientRect();
      return r.top < (window.innerHeight||800)*0.92 && r.bottom > -40; };
    // Visible + in view: paint hidden state, then animate in next frames.
    if(inView()){ requestAnimationFrame(()=>requestAnimationFrame(reveal)); return; }
    let io;
    try{ io = new IntersectionObserver(([e])=>{ if(e.isIntersecting) reveal(); },
      { threshold:0.1, rootMargin:"0px 0px -6% 0px" }); io.observe(el); }catch(e){}
    const onScroll = ()=>{ if(inView()){ reveal(); cleanup(); } };
    const onVis = ()=>{ if(!document.hidden && inView()){ reveal(); cleanup(); } };
    const cleanup = ()=>{ if(io) io.disconnect(); window.removeEventListener("scroll", onScroll); document.removeEventListener("visibilitychange", onVis); };
    window.addEventListener("scroll", onScroll, { passive:true });
    document.addEventListener("visibilitychange", onVis);
    return cleanup;
  },[seen]);
  return React.createElement(as,{ ref, className:`reveal ${scale?"scale":""} ${seen?"in":""} ${instant?"instant":""} ${className}`,
    style:{ transitionDelay:`${delay}ms`, ...style } }, children);
}

/* ---------------- CountUp ---------------- */
function CountUp({ to, dur = 1400, decimals = 0, suffix = "", prefix = "", start = true }){
  const [v, setV] = useState(0);
  const ref = useRef(null);
  const [run, setRun] = useState(false);
  useEffect(()=>{
    if(!start) return;
    const el = ref.current; if(!el) return;
    const inView = ()=>{ const r = el.getBoundingClientRect();
      return r.top < (window.innerHeight||800)*0.95 && r.bottom > -40; };
    if(inView()){ setRun(true); return; }
    let io;
    try{ io = new IntersectionObserver(([e])=>{ if(e.isIntersecting){ setRun(true); io.disconnect(); }},{threshold:.3}); io.observe(el); }catch(e){}
    const onScroll = ()=>{ if(inView()){ setRun(true); cleanup(); } };
    const cleanup = ()=>{ if(io) io.disconnect(); window.removeEventListener("scroll", onScroll); };
    window.addEventListener("scroll", onScroll, { passive:true });
    return cleanup;
  },[start]);
  useEffect(()=>{
    if(!run) return;
    if(document.hidden){ setV(to); return; }
    let raf, t0;
    const tick = (t)=>{ if(!t0) t0=t; const p=Math.min(1,(t-t0)/dur);
      const e = 1-Math.pow(1-p,3); setV(to*e); if(p<1) raf=requestAnimationFrame(tick); };
    raf=requestAnimationFrame(tick);
    const onVis = ()=>{ if(document.hidden) setV(to); };
    document.addEventListener("visibilitychange", onVis);
    return ()=>{ cancelAnimationFrame(raf); document.removeEventListener("visibilitychange", onVis); };
  },[run,to,dur]);
  return React.createElement("span",{ ref }, prefix + v.toFixed(decimals) + suffix);
}

/* ---------------- Particle field (canvas) ---------------- */
function ParticleField(){
  const ref = useRef(null);
  useEffect(()=>{
    const cv = ref.current; if(!cv) return;
    const ctx = cv.getContext("2d");
    let w,h,dpr,parts=[],raf,mouse={x:-999,y:-999};
    const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
    const resize=()=>{ dpr=Math.min(2,devicePixelRatio||1); w=cv.width=innerWidth*dpr; h=cv.height=innerHeight*dpr;
      cv.style.width=innerWidth+"px"; cv.style.height=innerHeight+"px"; };
    resize();
    const motion=()=> parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--motion'))||1;
    const make=()=>{ const n=reduce?0:Math.round((innerWidth*innerHeight)/26000);
      parts = Array.from({length:n},()=>({ x:Math.random()*w, y:Math.random()*h,
        vx:(Math.random()-.5)*.12*dpr, vy:(Math.random()-.5)*.12*dpr,
        r:(Math.random()*1.6+.6)*dpr, a:Math.random()*.5+.2 })); };
    make();
    const colors=["120,108,210","90,135,230","200,150,200"];
    const draw=()=>{
      const m=motion(); ctx.clearRect(0,0,w,h);
      for(const p of parts){
        p.x+=p.vx*m; p.y+=p.vy*m;
        if(p.x<0)p.x=w; if(p.x>w)p.x=0; if(p.y<0)p.y=h; if(p.y>h)p.y=0;
        const dx=p.x-mouse.x, dy=p.y-mouse.y, d=Math.hypot(dx,dy);
        if(d<120*dpr){ const f=(120*dpr-d)/(120*dpr); p.x+=dx/d*f*1.4; p.y+=dy/d*f*1.4; }
        ctx.beginPath(); ctx.arc(p.x,p.y,p.r,0,7); ctx.fillStyle=`rgba(120,108,205,${p.a*.7})`; ctx.fill();
      }
      // links
      for(let i=0;i<parts.length;i++){ for(let j=i+1;j<parts.length;j++){
        const a=parts[i],b=parts[j],dx=a.x-b.x,dy=a.y-b.y,d=Math.hypot(dx,dy);
        if(d<110*dpr){ ctx.strokeStyle=`rgba(125,112,205,${(1-d/(110*dpr))*.12})`; ctx.lineWidth=dpr*.6;
          ctx.beginPath(); ctx.moveTo(a.x,a.y); ctx.lineTo(b.x,b.y); ctx.stroke(); } } }
      raf=requestAnimationFrame(draw);
    };
    if(!reduce) draw();
    const onMove=(e)=>{ mouse.x=e.clientX*dpr; mouse.y=e.clientY*dpr; };
    const onLeave=()=>{ mouse.x=-999; mouse.y=-999; };
    addEventListener("resize",()=>{resize();make();}); addEventListener("mousemove",onMove); addEventListener("mouseleave",onLeave);
    return ()=>{ cancelAnimationFrame(raf); removeEventListener("mousemove",onMove); removeEventListener("mouseleave",onLeave); };
  },[]);
  return React.createElement("canvas",{ ref, className:"particles", "aria-hidden":true });
}

/* ---------------- Ambient orbs (parallax to scroll) ---------------- */
function PageBackground({ orbs = true }){
  const r1=useRef(null), r2=useRef(null);
  useEffect(()=>{
    const onScroll=()=>{ const y=window.scrollY; const m=parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--motion'))||1;
      if(r1.current) r1.current.style.transform=`translateY(${y*0.12*m}px)`;
      if(r2.current) r2.current.style.transform=`translateY(${-y*0.08*m}px)`; };
    addEventListener("scroll",onScroll); return ()=>removeEventListener("scroll",onScroll);
  },[]);
  return React.createElement("div",{ className:"page-bg" },
    React.createElement("div",{ className:"grid" }),
    orbs && React.createElement("div",{ ref:r1, className:"orb", style:{ width:420, height:420, top:-60, right:-40, background:"radial-gradient(circle,#cdb8f5,#cdb8f500)", animation:"orbDrift calc(20s/(var(--motion)*.5+.5)) ease-in-out infinite" } }),
    orbs && React.createElement("div",{ ref:r2, className:"orb", style:{ width:360, height:360, top:520, left:-80, background:"radial-gradient(circle,#b8cdf5,#b8cdf500)", animation:"orbDrift calc(26s/(var(--motion)*.5+.5)) ease-in-out infinite reverse" } })
  );
}

/* tilt on hover for cards */
function useTilt(maxDeg = 5){
  const ref = useRef(null);
  const onMove=(e)=>{ const el=ref.current; if(!el) return; const r=el.getBoundingClientRect();
    const m=parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--motion'))||1;
    const px=(e.clientX-r.left)/r.width-.5, py=(e.clientY-r.top)/r.height-.5;
    el.style.transform=`perspective(900px) rotateY(${px*maxDeg*m}deg) rotateX(${-py*maxDeg*m}deg) translateY(-4px)`; };
  const reset=()=>{ if(ref.current) ref.current.style.transform=""; };
  return { ref, onMouseMove:onMove, onMouseLeave:reset };
}

Object.assign(window, { I, Logo, Button, Nav, NAV, MacWindow, Reveal, CountUp, ParticleField, PageBackground, useTilt });
