// Norton-Gauss · Value-first sections
// ─────────────────────────────────────────────────────────────
// Replaces the two abstract visuals with commercially clear,
// premium-interactive sections:
//   • CostOfManual   — "The Cost of Manual Operations" (before/after)
//   • CapabilityPanels — four large interactive capability panels
//   • WhatWeBuild    — recognizable use-case showcase
// Loaded after sections.jsx; consumed by app.jsx.

const { useState: vS, useEffect: vE, useRef: vR } = React;

// ─── self-contained icons (Babel scripts don't share scope) ──────
const VArr = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none" aria-hidden="true">
    <path d="M5 11L11 5M11 5H6.5M11 5V9.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);
const VCheck = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 14 14" fill="none" aria-hidden="true">
    <path d="M2.5 7.5L6 11L11.5 3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

// ─── easing + animated counter ───────────────────────────────────
const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);

function VCounter({ value, dec = 0, suffix = '' }) {
  const [disp, setDisp] = vS(value);
  const fromRef = vR(value);
  const rafRef = vR(0);
  const toutRef = vR(0);
  const genRef = vR(0);

  vE(() => {
    const gen = ++genRef.current;            // invalidate any in-flight frames
    const from = fromRef.current;
    const to = value;
    fromRef.current = to;
    if (from === to) { setDisp(to); return; }
    const dur = 900;
    const start = performance.now();
    const tick = (now) => {
      if (gen !== genRef.current) return;     // a newer toggle superseded us
      const p = Math.min(1, (now - start) / dur);
      setDisp(p >= 1 ? to : from + (to - from) * easeOutCubic(p));
      if (p < 1) rafRef.current = requestAnimationFrame(tick);
    };
    cancelAnimationFrame(rafRef.current);
    rafRef.current = requestAnimationFrame(tick);
    // Safety net for throttled tabs: snap to target and stop any late frames.
    clearTimeout(toutRef.current);
    toutRef.current = setTimeout(() => {
      if (gen !== genRef.current) return;
      cancelAnimationFrame(rafRef.current);
      setDisp(to);
    }, dur + 160);
    return () => { cancelAnimationFrame(rafRef.current); clearTimeout(toutRef.current); };
  }, [value, dec]);

  const text = dec > 0 ? disp.toFixed(dec) : Math.round(disp).toString();
  return <span>{text}<span className="vc-suffix">{suffix}</span></span>;
}

// ─── metric iconography (line icons, stroke = currentColor) ──────
function CostIcon({ name }) {
  const p = { fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  let body;
  if (name === 'handoff') {
    body = <g {...p}><path d="M4 8h11l-3-3M20 16H9l3 3" /></g>;
  } else if (name === 'systems') {
    body = <g {...p}><rect x="3" y="4" width="7" height="7" rx="1.3" /><rect x="14" y="13" width="7" height="7" rx="1.3" /><path d="M10 7.5h2.5a2 2 0 0 1 2 2V13" strokeDasharray="2 2.4" /></g>;
  } else if (name === 'proposal') {
    body = <g {...p}><path d="M6 3h8l4 4v14H6z" /><path d="M14 3v4h4" /><path d="M9 12h6M9 15.5h6M9 8.5h2" /></g>;
  } else if (name === 'spreadsheet') {
    body = <g {...p}><rect x="3.5" y="4" width="17" height="16" rx="1.4" /><path d="M3.5 9.5h17M3.5 15h17M9 4v16M15 4v16" /></g>;
  } else { // support
    body = <g {...p}><path d="M4 12a8 8 0 0 1 16 0v4a3 3 0 0 1-3 3h-2" /><rect x="3" y="12" width="3.5" height="6" rx="1.2" /><rect x="17.5" y="12" width="3.5" height="6" rx="1.2" /></g>;
  }
  return <svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true">{body}</svg>;
}

// ═══════════════════════════════════════════════════════════════
// THE COST OF MANUAL OPERATIONS  — before / after
// ═══════════════════════════════════════════════════════════════
function CostOfManual() {
  const c = window.NG.costOfManual;
  const [after, setAfter] = vS(false);
  const secRef = vR(null);
  const firedRef = vR(false);

  // Auto-reveal the payoff once when the section scrolls into view.
  vE(() => {
    const el = secRef.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((en) => {
        if (en.isIntersecting && !firedRef.current) {
          firedRef.current = true;
          setTimeout(() => setAfter(true), 900);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  return (
    <section className="section-pad com-section" ref={secRef} data-anim="cost">
      <div className="section-tag">
        <span><span className="num">01</span> · The problem</span>
        <span>The cost of manual operations</span>
      </div>
      <div className="container">
        <div className="section-head" style={{ marginBottom: 40 }}>
          <h2 className="display-2xl">
            {c.h2A}<em className="serif-em" style={{ color: 'var(--ng-lime)' }}>{c.h2Em}</em>
          </h2>
          <p className="right">{c.sub}</p>
        </div>

        {/* segmented toggle */}
        <div className="com-toggle" role="tablist" aria-label="Operating mode">
          <span className="com-thumb" data-after={after ? '1' : '0'} aria-hidden="true" />
          <button role="tab" aria-selected={!after} className={'com-tab' + (!after ? ' is-on' : '')} onClick={() => setAfter(false)}>
            {c.toggle.a}
          </button>
          <button role="tab" aria-selected={after} className={'com-tab' + (after ? ' is-on' : '')} onClick={() => setAfter(true)}>
            {c.toggle.b}
          </button>
        </div>

        {/* metric cards */}
        <div className={'com-stage' + (after ? ' is-after' : '')}>
          <div className="com-grid">
            {c.metrics.map((m, i) => {
              const val = after ? m.after : m.before;
              const dec = after && m.dec ? m.dec : 0;
              return (
                <div key={i} className={'com-card' + (after ? ' is-after' : '')}>
                  <span className="com-ico"><CostIcon name={m.icon} /></span>
                  <div className="com-num">
                    <VCounter value={val} dec={dec} suffix={m.suffix || ''} />
                  </div>
                  <div className="com-k">{m.k}</div>
                  <div className="com-status">
                    <span className="com-dot" />
                    <span className="com-status-t">{after ? m.outcome : 'Manual today'}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* outcomes strip */}
        <div className={'com-outcomes' + (after ? ' is-after' : '')}>
          <span className="com-outcomes-label">What changes</span>
          <div className="com-outcomes-row">
            {c.outcomes.map((o, i) => (
              <span key={i} className="com-chip" style={{ transitionDelay: (after ? i * 70 : 0) + 'ms' }}>
                <VCheck size={13} />{o}
              </span>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ═══════════════════════════════════════════════════════════════
// CAPABILITY PANELS — four large interactive panels (accordion)
// ═══════════════════════════════════════════════════════════════
function CapabilityPanels({ setRoute }) {
  const caps = window.NG.capabilities;
  const [active, setActive] = vS(0);
  const [paused, setPaused] = vS(false);
  const [progress, setProgress] = vS(0);
  const canvasRef = vR(null);
  const ctrlRef = vR(null);

  // mount the signature animation stage
  vE(() => {
    if (canvasRef.current && window.initCapabilityStage) {
      ctrlRef.current = window.initCapabilityStage(canvasRef.current);
    }
    return () => { if (ctrlRef.current) ctrlRef.current.destroy(); ctrlRef.current = null; };
  }, []);
  vE(() => { if (ctrlRef.current) ctrlRef.current.setActive(active); }, [active]);

  // gentle auto-advance so all four showcase themselves; pauses on interaction
  vE(() => {
    if (paused) return;
    const dur = 5200; const start = performance.now(); let raf;
    const tick = (now) => {
      const p = Math.min(1, (now - start) / dur);
      setProgress(p);
      if (p >= 1) { setActive((a) => (a + 1) % caps.length); return; }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => raf && cancelAnimationFrame(raf);
  }, [active, paused, caps.length]);

  const select = (i) => { setPaused(true); setActive(i); setProgress(0); };
  const cap = caps[active];

  return (
    <section className="section-pad-sm" id="capabilities" data-anim="caps">
      <div className="section-tag">
        <span><span className="num">02</span> · Capabilities</span>
        <span>Four pillars · One operating model</span>
      </div>
      <div className="container">
        <div className="section-head">
          <h2 className="display-2xl">
            How we help your <span className="serif-em" style={{ color: 'var(--ng-lime)' }}>operation.</span>
          </h2>
          <p className="right">
            Four capabilities, one operating model. Hyper-Automation and Agentic AI lead; Cloud &amp; Edge and Custom Software &amp; Operations Transformation give them a foundation to run on. Select a capability to see it work.
          </p>
        </div>

        <div className="capx" onMouseEnter={() => setPaused(true)}>
          {/* selectable rail */}
          <div className="capx-rail" role="tablist" aria-label="Capabilities">
            {caps.map((c, i) => (
              <button
                key={c.id}
                role="tab"
                aria-selected={active === i}
                className={'capx-row' + (active === i ? ' is-active' : '')}
                onClick={() => select(i)}
              >
                <span className="capx-row-ix">{c.num}</span>
                <span className="capx-row-main">
                  <span className="capx-row-name">{c.title}</span>
                  <span className="capx-row-msg">{c.message}</span>
                </span>
                <span className="capx-row-bar" aria-hidden="true">
                  <span className="capx-row-fill" style={{ transform: `scaleX(${active === i && !paused ? progress : active === i ? 1 : 0})` }} />
                </span>
              </button>
            ))}
          </div>

          {/* animated stage */}
          <div className="capx-stage">
            <canvas className="capx-canvas" ref={canvasRef} aria-hidden="true" />
            <div className="capx-stage-grain" aria-hidden="true" />
            <div className="capx-stage-inner" key={active}>
              <div className="capx-kicker">{cap.num} · Capability</div>
              <h3 className="capx-title">{cap.title}</h3>
              <p className="capx-msg">{cap.message}</p>
              <div className="capx-cols">
                <div className="capx-col">
                  <span className="capx-col-label">Focus</span>
                  <ul className="capx-focus">
                    {cap.focus.map((f, k) => <li key={k} style={{ transitionDelay: (60 + k * 45) + 'ms' }}>{f}</li>)}
                  </ul>
                </div>
                <div className="capx-col">
                  <span className="capx-col-label">Business outcomes</span>
                  <div className="capx-chips">
                    {cap.outcomes.map((o, k) => <span key={k} className="capx-chip" style={{ transitionDelay: (120 + k * 55) + 'ms' }}>{o}</span>)}
                  </div>
                </div>
              </div>
              <button className="capx-cta" onClick={() => setRoute && setRoute('services')}>
                <VArr size={15} />Explore this capability
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ═══════════════════════════════════════════════════════════════
// WHAT WE BUILD — recognizable use-case showcase
// ═══════════════════════════════════════════════════════════════
function WhatWeBuild({ setRoute }) {
  const w = window.NG.whatWeBuild;
  const caps = ['All', 'Hyper-Automation', 'Agentic AI', 'Cloud & Edge', 'Custom Software', 'Ops Transformation'];
  const [filter, setFilter] = vS('All');
  const items = filter === 'All' ? w.items : w.items.filter((it) => it.cap === filter);

  return (
    <section className="section-pad-sm wb-section" data-anim="wb">
      <div className="section-tag">
        <span><span className="num">08</span> · What we build</span>
        <span>Recognizable initiatives</span>
      </div>
      <div className="container">
        <div className="section-head">
          <h2 className="display-2xl">
            {w.h2A}<em className="serif-em" style={{ color: 'var(--ng-lime)' }}>{w.h2Em}</em>
          </h2>
          <p className="right">{w.sub}</p>
        </div>

        <div className="wb-filters">
          {caps.map((c) => (
            <button key={c} className={'wb-filter' + (filter === c ? ' is-on' : '')} onClick={() => setFilter(c)}>
              {c}
            </button>
          ))}
        </div>

        <div className="wb-grid">
          {items.map((it, i) => (
            <article key={it.t} className="wb-card" onClick={() => setRoute && setRoute('book')}>
              <div className="wb-cap">{it.cap}</div>
              <h3 className="wb-title">{it.t}</h3>
              <p className="wb-desc">{it.d}</p>
              <span className="wb-go"><VArr size={15} /></span>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { CostOfManual, CapabilityPanels, WhatWeBuild });
