// cr-visuals.jsx — designed product imagery + motion helpers
const { useState: useStateV, useEffect: useEffectV, useRef: useRefV } = React;

/* ---- useInView: fires once when element scrolls into view (scroll-based, robust) ---- */
function useInView(threshold = 0.25){
  const ref = useRefV(null);
  const [seen, setSeen] = useStateV(false);
  useEffectV(() => {
    const el = ref.current; if(!el) return;
    const check = () => {
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight;
      if(r.top < vh * (1 - threshold) && r.bottom > 0){ setSeen(true); return true; }
      return false;
    };
    if(check()) return;
    const onScroll = () => { if(check()){ window.removeEventListener("scroll", onScroll); } };
    window.addEventListener("scroll", onScroll, { passive: true });
    const t = setTimeout(check, 120);
    return () => { window.removeEventListener("scroll", onScroll); clearTimeout(t); };
  }, [threshold]);
  return [ref, seen];
}

/* ---- count-up number ---- */
function CountUp({ to, dur = 1400, prefix = "", suffix = "", decimals = 0 }){
  const [ref, seen] = useInView(0.4);
  const [val, setVal] = useStateV(0);
  useEffectV(() => {
    if(!seen) return;
    let raf, start;
    const ease = (t) => 1 - Math.pow(1 - t, 3);
    const tick = (now) => {
      if(!start) start = now;
      const p = Math.min((now - start) / dur, 1);
      setVal(to * ease(p));
      if(p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    // fallback if rAF throttled
    const fb = setTimeout(() => setVal(to), dur + 200);
    return () => { cancelAnimationFrame(raf); clearTimeout(fb); };
  }, [seen, to, dur]);
  return <span ref={ref}>{prefix}{val.toLocaleString(undefined,{minimumFractionDigits:decimals,maximumFractionDigits:decimals})}{suffix}</span>;
}

/* ---- floating decorative shapes (subtle drift) ---- */
function FloatShapes({ variant = "a" }){
  return (
    <div className={"float-shapes fs-"+variant} data-parallax="1.2" aria-hidden="true">
      <span className="fs-dot d1"/><span className="fs-dot d2"/><span className="fs-ring r1"/>
      <svg className="fs-spark" viewBox="0 0 120 40" fill="none"><path d="M2 30 L24 22 L46 26 L68 10 L90 16 L118 4" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
    </div>
  );
}

/* =========================================================
   DASHBOARD MOCKUP — the "after" picture (product imagery)
   ========================================================= */
function Sparkline({ pts, seen, delay = 0, color = "#3D4FBF" }){
  const d = pts.map((p,i)=>`${i===0?"M":"L"} ${(i/(pts.length-1))*100} ${30 - p*26}`).join(" ");
  return (
    <svg className="kpi-spark" viewBox="0 0 100 32" preserveAspectRatio="none" fill="none">
      <path className={"draw-line"+(seen?" go":"")} pathLength="1" style={{animationDelay:`${delay}s`,animationDuration:"1.3s"}}
        d={d} stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke"/>
    </svg>
  );
}

function DashboardMockup({ compact = false }){
  const [ref, seen] = useInView(0.3);
  const bars = [42,64,51,78,60,88,72];
  const line = "M0 150 C 60 140, 110 110, 170 96 S 290 60, 350 40 S 470 30, 540 18";
  return (
    <div className={"dash"+(compact?" dash--compact":"")+(seen?" in":"")} ref={ref}>
      <div className="dash-bar">
        <div className="dash-dots"><span/><span/><span/></div>
        <div className="dash-title">Operations Overview</div>
        <div className="dash-live"><span className="lv-dot"/>Live</div>
      </div>
      <div className="dash-body">
        <div className="dash-kpis">
          {[
            {l:"Revenue", v:1.84, pre:"$", suf:"M", dec:2, up:true, c:"#1F8A5B", pts:[.2,.35,.3,.5,.6,.78,.9]},
            {l:"Gross margin", v:38.6, suf:"%", dec:1, up:true, c:"#3D4FBF", pts:[.3,.4,.38,.55,.6,.7,.82]},
            {l:"Cycle time", v:4.2, suf:"d", dec:1, up:false, c:"#C25A3C", pts:[.9,.7,.75,.55,.5,.4,.3]},
          ].map((k,i)=>(
            <div className="kpi" key={k.l} style={{transitionDelay:`${0.15+i*0.1}s`}}>
              <div className="kpi-top">
                <span className="kpi-l">{k.l}</span>
                <span className={"kpi-chip "+(k.up?"up":"down")}>{k.up?"▲":"▼"}</span>
              </div>
              <div className="kpi-v"><CountUp to={k.v} prefix={k.pre||""} suffix={k.suf||""} decimals={k.dec||0}/></div>
              <Sparkline pts={k.pts} seen={seen} delay={0.3+i*0.12} color={k.c}/>
            </div>
          ))}
        </div>
        <div className="dash-grid">
          <div className="dash-chart">
            <div className="dc-head"><span>Performance trend</span><span className="dc-tag">Last 6 months</span></div>
            <svg className="dc-svg" viewBox="0 0 540 170" fill="none" preserveAspectRatio="none">
              <defs>
                <linearGradient id="dashFill" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0" stopColor="#3D4FBF" stopOpacity="0.22"/>
                  <stop offset="1" stopColor="#3D4FBF" stopOpacity="0"/>
                </linearGradient>
              </defs>
              {[40,80,120].map(y=><line key={y} x1="0" y1={y} x2="540" y2={y} stroke="#1A1F4C" strokeOpacity="0.07"/>)}
              <path className={"dc-area"+(seen?" in":"")} d={line+" L 540 170 L 0 170 Z"} fill="url(#dashFill)"/>
              <path className={"draw-line"+(seen?" go":"")} pathLength="1" style={{animationDuration:"1.8s",animationDelay:"0.4s"}}
                d={line} stroke="#3D4FBF" strokeWidth="3" strokeLinecap="round" vectorEffect="non-scaling-stroke"/>
              <circle className={"dot-pop"+(seen?" go":"")} style={{animationDelay:"2s"}} cx="540" cy="18" r="5" fill="#fff" stroke="#3D4FBF" strokeWidth="3"/>
            </svg>
          </div>
          <div className="dash-bars">
            <div className="dc-head"><span>By department</span></div>
            <div className="bars-row">
              {bars.map((b,i)=>(
                <div className="bar-col" key={i}>
                  <div className={"bar-fill"+(seen?" in":"")} style={{height:b+"%",transitionDelay:`${0.5+i*0.07}s`}}/>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* =========================================================
   PERSONA MINI-VIZ (triptych)
   ========================================================= */
function PersonaViz({ kind, seen }){
  const stroke = { fill:"none", stroke:"currentColor", strokeWidth:2.5, strokeLinecap:"round", strokeLinejoin:"round", vectorEffect:"non-scaling-stroke" };
  if(kind==="ceo") return (
    <svg className="pv" viewBox="0 0 160 70" fill="none">
      {[18,36,54].map(y=><line key={y} x1="0" y1={y} x2="160" y2={y} stroke="currentColor" strokeOpacity="0.14"/>)}
      <path className={"draw-line"+(seen?" go":"")} pathLength="1" style={{animationDelay:"0.2s"}} d="M4 58 L 24 49 L 40 55 L 58 37 L 76 44 L 98 26 L 118 31 L 138 14 L 156 8" {...stroke}/>
      <circle className={"dot-pop"+(seen?" go":"")} style={{animationDelay:"1.4s"}} cx="156" cy="8" r="4.5" fill="currentColor"/>
    </svg>
  );
  if(kind==="cfo") return (
    <svg className="pv" viewBox="0 0 160 70" fill="none">
      {[
        [10,38,90],[34,28,150],[58,44,90],[82,20,180],[106,34,130],[130,16,160]
      ].map((b,i)=>(
        <rect key={i} className={"bar-rise"+(seen?" go":"")} style={{animationDelay:`${0.2+i*0.1}s`,transformBox:"fill-box",transformOrigin:"bottom"}}
          x={b[0]} y={b[1]} width="14" height={70-b[1]} rx="2.5" fill="currentColor" fillOpacity={0.45+i*0.08}/>
      ))}
    </svg>
  );
  return (
    <svg className="pv" viewBox="0 0 160 70" fill="none">
      <path className={"draw-line"+(seen?" go":"")} pathLength="1" style={{animationDelay:"0.2s"}} d="M6 35 H 60" {...stroke}/>
      <path className={"draw-line"+(seen?" go":"")} pathLength="1" style={{animationDelay:"0.6s"}} d="M100 35 H 154" {...stroke}/>
      <circle className={"dot-pop"+(seen?" go":"")} style={{animationDelay:"0.9s"}} cx="80" cy="35" r="14" stroke="currentColor" strokeWidth="2.5" fill="none"/>
      <circle className={"dot-pop"+(seen?" go":"")} style={{animationDelay:"1.2s"}} cx="80" cy="35" r="4.5" fill="currentColor"/>
      <circle className={"dot-pop"+(seen?" go":"")} style={{animationDelay:"0.4s"}} cx="6" cy="35" r="4.5" fill="currentColor"/>
      <circle className={"dot-pop"+(seen?" go":"")} style={{animationDelay:"1.5s"}} cx="154" cy="35" r="4.5" fill="currentColor"/>
    </svg>
  );
}

/* =========================================================
   PRIMER STEP VISUALS (small illustrative diagrams)
   ========================================================= */
function StepViz({ kind, seen }){
  const s = { fill:"none", stroke:"currentColor", strokeWidth:2, strokeLinecap:"round", strokeLinejoin:"round" };
  if(kind===0) return ( // scattered
    <svg className="sv" viewBox="0 0 80 56" {...s}>
      {[[12,12],[40,8],[66,18],[20,40],[52,44],[70,38],[36,28]].map((p,i)=>(
        <rect key={i} className={"sv-fade"+(seen?" go":"")} style={{animationDelay:`${i*0.08}s`}} x={p[0]} y={p[1]} width="12" height="9" rx="2"/>
      ))}
    </svg>
  );
  if(kind===1) return ( // funnel into one box
    <svg className="sv" viewBox="0 0 80 56" {...s}>
      {[[8,8],[8,24],[8,40]].map((p,i)=>(
        <path key={i} className={"draw-line"+(seen?" go":"")} pathLength="1" style={{animationDelay:`${i*0.12}s`}} d={`M${p[0]+10} ${p[1]+4} C 36 ${p[1]+4}, 40 28, 54 28`}/>
      ))}
      <rect className={"sv-pop"+(seen?" go":"")} style={{animationDelay:"0.6s"}} x="54" y="18" width="20" height="20" rx="4"/>
    </svg>
  );
  if(kind===2) return ( // screen with chart
    <svg className="sv" viewBox="0 0 80 56" {...s}>
      <rect x="6" y="8" width="68" height="40" rx="4" className={"sv-pop"+(seen?" go":"")}/>
      <path className={"draw-line"+(seen?" go":"")} pathLength="1" style={{animationDelay:"0.4s"}} d="M14 38 L28 30 L40 34 L52 20 L66 16"/>
    </svg>
  );
  return ( // aligned arrows
    <svg className="sv" viewBox="0 0 80 56" {...s}>
      {[14,28,42].map((y,i)=>(
        <path key={i} className={"draw-line"+(seen?" go":"")} pathLength="1" style={{animationDelay:`${i*0.12}s`}} d={`M10 ${y} H 62 M56 ${y-5} L 64 ${y} L 56 ${y+5}`}/>
      ))}
    </svg>
  );
}

/* =========================================================
   CHAOS STACK — the messy "before" (scattered sources)
   ========================================================= */
function ChaosStack(){
  const [ref, seen] = useInView(0.3);
  return (
    <div className={"chaos"+(seen?" in":"")} ref={ref} aria-hidden="true">
      <svg className="chaos-web" viewBox="0 0 320 320" fill="none" preserveAspectRatio="none">
        <path d="M70 90 C 140 60, 180 140, 250 80 M90 220 C 150 180, 210 250, 250 200 M80 120 C 120 200, 200 180, 230 250"
          stroke="#9AA3B8" strokeWidth="1.5" strokeDasharray="4 5" strokeOpacity="0.7"/>
      </svg>
      {/* spreadsheet */}
      <div className="doc doc-xls" style={{"--r":"-7deg"}}>
        <div className="doc-top"><span className="doc-badge xls">XLSX</span><span className="doc-name">Sales_FINAL_v4</span></div>
        <div className="xls-grid">{Array.from({length:24}).map((_,i)=><span key={i}/>)}</div>
      </div>
      {/* pdf */}
      <div className="doc doc-pdf" style={{"--r":"5deg"}}>
        <div className="doc-top"><span className="doc-badge pdf">PDF</span><span className="doc-name">BoardDeck_Q3</span></div>
        <div className="doc-lines"><i style={{width:"90%"}}/><i style={{width:"70%"}}/><i style={{width:"80%"}}/><i style={{width:"55%"}}/></div>
      </div>
      {/* email */}
      <div className="doc doc-mail" style={{"--r":"-3deg"}}>
        <div className="mail-head"><span className="mail-dot"/>RE: which number is right?</div>
        <div className="doc-lines"><i style={{width:"95%"}}/><i style={{width:"60%"}}/></div>
      </div>
      {/* native tool export */}
      <div className="doc doc-tool" style={{"--r":"8deg"}}>
        <div className="doc-top"><span className="doc-badge tool">CRM</span><span className="doc-name">export.csv</span></div>
        <div className="tool-bars"><span style={{height:"40%"}}/><span style={{height:"70%"}}/><span style={{height:"30%"}}/><span style={{height:"85%"}}/><span style={{height:"55%"}}/></div>
      </div>
      {/* sticky note */}
      <div className="doc doc-note" style={{"--r":"-11deg"}}>ask Dana<br/>for the<br/>real totals?</div>
    </div>
  );
}

Object.assign(window, { useInView, CountUp, FloatShapes, DashboardMockup, PersonaViz, StepViz, ChaosStack });
