/* global React, Icon, Btn, Reveal */
/* ──────────────────────────────────────────────────────────────
   tech-solutions.jsx — data, scrollspy pill-nav, solution sections
   ────────────────────────────────────────────────────────────── */
const { useState: useStateS, useEffect: useEffectS, useRef: useRefS } = React;

const SOLUTIONS = [
  {
    id: 'modernize', pill: 'Modernization', icon: 'layers',
    overline: 'App Modernization',
    title: ['AI-driven application', 'modernization'],
    blurb: 'Turn decades of legacy systems into clean, maintainable services — automatically translated, decomposed, and documented.',
    features: [
      { icon: 'code',  title: 'Legacy code translation', desc: 'Automated COBOL-to-Java conversion with semantic equivalence checks.' },
      { icon: 'split', title: 'Monolith deconstruction', desc: 'AI identifies clean microservice boundaries from tangled codebases.' },
      { icon: 'gauge', title: 'Technical debt reduction', desc: 'Continuous refactoring removes duplication and dead paths.' },
      { icon: 'map',   title: 'Architecture mapping', desc: 'Instant, living documentation of legacy systems and dependencies.' },
    ],
  },
  {
    id: 'qa', pill: 'QA Automation', icon: 'shield',
    overline: 'QA Automation',
    title: ['Next-gen QA', 'automation'],
    blurb: 'Tests that fix themselves, data that generates itself, and defects caught before a single line is run.',
    features: [
      { icon: 'flask', title: 'Self-healing test scripts', desc: 'AI repairs broken selectors automatically as the UI evolves.' },
      { icon: 'layers',title: 'Synthetic data generation', desc: 'Instant creation of compliant, realistic test datasets.' },
      { icon: 'bug',   title: 'Predictive defect analysis', desc: 'Pinpoints high-risk code before testing even begins.' },
      { icon: 'msg',   title: 'Natural language testing', desc: 'Plain-English prompts generate full test suites.' },
    ],
  },
  {
    id: 'mobile', pill: 'Mobile', icon: 'phone',
    overline: 'Mobile Development',
    title: ['Intelligent mobile', 'app development'],
    blurb: 'One spec, every platform. Generate, migrate, and optimize native apps with an AI that understands the edge.',
    features: [
      { icon: 'split', title: 'Cross-platform code gen', desc: 'Swift and Kotlin generated simultaneously from one source.' },
      { icon: 'sync',  title: 'Automated SDK updates', desc: 'AI migrates breaking API changes without manual rewrites.' },
      { icon: 'cpu',   title: 'On-device AI optimization', desc: 'Compresses models for fast, private edge execution.' },
      { icon: 'target',title: 'Context-aware features', desc: 'Predictive user actions enable look-ahead loading.' },
    ],
  },
  {
    id: 'ux', pill: 'UI/UX Design', icon: 'pen',
    overline: 'UI/UX Design',
    title: ['AI-powered', 'UI/UX design'],
    blurb: 'From sketch to shipped interface — designs that build themselves, adapt to users, and stay accessible by default.',
    features: [
      { icon: 'code', title: 'Wireframe-to-code', desc: 'Sketches instantly become functional, production frontend.' },
      { icon: 'user', title: 'Dynamic personalization', desc: 'Interfaces adapt in real time to user behavior.' },
      { icon: 'eye',  title: 'Accessibility auditing', desc: 'Continuous WCAG compliance scanning as you design.' },
      { icon: 'wave', title: 'Predictive heatmaps', desc: 'AI simulates user attention before a single user arrives.' },
    ],
  },
];

// ── Sticky scroll-spy pill nav ───────────────────────────────────
const SolutionsNav = ({ active, onJump }) => (
  <div id="solutions" style={{ position: 'sticky', top: 64, zIndex: 40, background: 'rgba(13,21,37,0.85)',
    backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)', borderBottom: '1px solid var(--border-subtle)' }}>
    <div className="wrap" style={{ display: 'flex', alignItems: 'center', gap: 6, height: 58, overflowX: 'auto' }}>
      {SOLUTIONS.map((s) => (
        <button key={s.id} className={`solpill ${active === s.id ? 'active' : ''}`} onClick={() => onJump(s.id)}>
          <Icon name={s.icon} size={15}/>{s.pill}
        </button>
      ))}
    </div>
  </div>
);

// ── Per-solution ambient visual ──────────────────────────────────
const SolutionVisual = ({ id }) => {
  if (id === 'modernize') {
    const rows = [{ w: 92, c: 'debt' }, { w: 64, c: 'debt' }, { w: 38, c: 'ok' }, { w: 22, c: 'ok' }];
    return (
      <VisualShell label="technical-debt.scan" badge="−74% debt">
        <div style={{ display: 'grid', gap: 14 }}>
          {rows.map((r, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span className="mono" style={{ fontSize: 11, color: 'var(--fg-4)', width: 54 }}>mod-{i + 1}</span>
              <div style={{ flex: 1, height: 12, background: 'var(--neutral-100)', borderRadius: 9999, overflow: 'hidden' }}>
                <div style={{ height: '100%', width: `${r.w}%`, borderRadius: 9999,
                  background: r.c === 'debt' ? 'linear-gradient(90deg,#fca5a5,var(--error))' : 'linear-gradient(90deg,var(--primary-300),var(--accent))',
                  animation: `tk-rise .8s var(--ease-out) both`, animationDelay: `${i * 0.12}s` }}/>
              </div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 18, display: 'flex', gap: 8, alignItems: 'center', fontSize: 12.5, color: 'var(--fg-2)' }}>
          <Icon name="bolt" size={15} style={{ color: 'var(--accent)' }}/> Refactoring 1,204 duplicated blocks…
        </div>
      </VisualShell>
    );
  }
  if (id === 'qa') {
    const tests = [
      { n: 'checkout.spec', s: 'pass' }, { n: 'auth-flow.spec', s: 'heal' },
      { n: 'cart.spec', s: 'pass' }, { n: 'search.spec', s: 'pass' },
    ];
    return (
      <VisualShell label="suite · 318 tests" badge="0 flaky">
        <div style={{ display: 'grid', gap: 8 }}>
          {tests.map((t, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', borderRadius: 10, border: '1px solid var(--border-subtle)', background: 'var(--neutral-50)' }}>
              <span style={{ width: 22, height: 22, borderRadius: 7, display: 'grid', placeItems: 'center',
                background: t.s === 'heal' ? 'var(--warning-bg)' : 'var(--success-bg)', color: t.s === 'heal' ? '#fbbf24' : '#4ade80' }}>
                <Icon name={t.s === 'heal' ? 'refresh' : 'check'} size={13} style={t.s === 'heal' ? { animation: 'tk-spin 2s linear infinite' } : null}/>
              </span>
              <span className="mono" style={{ fontSize: 12.5, color: 'var(--fg-1)' }}>{t.n}</span>
              <span style={{ marginLeft: 'auto', fontSize: 11.5, fontWeight: 600, color: t.s === 'heal' ? '#fbbf24' : '#4ade80' }}>
                {t.s === 'heal' ? 'self-healing selector' : 'passed'}
              </span>
            </div>
          ))}
        </div>
      </VisualShell>
    );
  }
  if (id === 'mobile') {
    return (
      <VisualShell label="build · one spec" badge="iOS + Android">
        <div style={{ display: 'flex', gap: 18, justifyContent: 'center', alignItems: 'center' }}>
          {[{ n: 'Swift', c: 'var(--accent)' }, { n: 'Kotlin', c: 'var(--primary-700)' }].map((p, i) => (
            <div key={p.n} style={{ width: 96, height: 168, borderRadius: 18, border: '2px solid var(--border-strong)', background: 'var(--bg-inverse)', padding: 8, position: 'relative', animation: 'tk-float 4.5s ease-in-out infinite', animationDelay: `${i * 0.6}s` }}>
              <div style={{ height: 5, width: 28, borderRadius: 9, background: '#334155', margin: '2px auto 8px' }}/>
              <div style={{ display: 'grid', gap: 5 }}>
                <div style={{ height: 26, borderRadius: 6, background: p.c }}/>
                {[1,2,3].map((k) => <div key={k} style={{ height: 9, borderRadius: 4, background: 'rgba(255,255,255,0.14)', width: `${90 - k*12}%` }}/>)}
                <div style={{ height: 9, borderRadius: 4, background: 'rgba(51,181,245,0.5)', width: '60%', marginTop: 4 }}/>
              </div>
              <span className="mono" style={{ position: 'absolute', bottom: 7, left: 0, right: 0, textAlign: 'center', fontSize: 9.5, color: '#7e8ba3' }}>{p.n}</span>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 16, textAlign: 'center', fontSize: 12.5, color: 'var(--fg-2)' }}>Generated simultaneously from a single definition</div>
      </VisualShell>
    );
  }
  // ux
  return (
    <VisualShell label="wireframe → frontend" badge="WCAG AA">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', gap: 14, alignItems: 'center' }}>
        <div style={{ border: '1.5px dashed var(--border-strong)', borderRadius: 12, padding: 12, display: 'grid', gap: 8, background: 'var(--neutral-50)' }}>
          <div style={{ height: 14, background: 'var(--neutral-200)', borderRadius: 4, width: '70%' }}/>
          <div style={{ height: 32, background: 'var(--neutral-200)', borderRadius: 6 }}/>
          <div style={{ height: 8, background: 'var(--neutral-200)', borderRadius: 4 }}/>
          <div style={{ height: 8, background: 'var(--neutral-200)', borderRadius: 4, width: '80%' }}/>
          <div style={{ height: 22, background: 'var(--neutral-300)', borderRadius: 6, width: '50%' }}/>
        </div>
        <div style={{ width: 34, height: 34, borderRadius: 10, background: 'var(--accent)', color: '#fff', display: 'grid', placeItems: 'center', boxShadow: 'var(--shadow-glow)' }}><Icon name="arrowRight" size={18}/></div>
        <div style={{ border: '1px solid var(--border-default)', borderRadius: 12, padding: 12, display: 'grid', gap: 8, background: 'var(--bg-surface)', boxShadow: 'var(--shadow-sm)' }}>
          <div style={{ height: 14, background: 'var(--fg-2)', borderRadius: 4, width: '70%' }}/>
          <div style={{ height: 32, background: 'var(--primary-50)', border: '1px solid var(--primary-200)', borderRadius: 6 }}/>
          <div style={{ height: 8, background: 'var(--neutral-200)', borderRadius: 4 }}/>
          <div style={{ height: 8, background: 'var(--neutral-200)', borderRadius: 4, width: '80%' }}/>
          <div style={{ height: 22, background: 'var(--accent)', borderRadius: 6, width: '50%' }}/>
        </div>
      </div>
    </VisualShell>
  );
};

const VisualShell = ({ label, badge, children }) => (
  <div style={{ position: 'relative' }}>
    <div className="dotgrid" style={{ position: 'absolute', inset: '-20px', opacity: 0.5, borderRadius: 24, maskImage: 'radial-gradient(circle at 50% 50%, #000 45%, transparent 80%)', WebkitMaskImage: 'radial-gradient(circle at 50% 50%, #000 45%, transparent 80%)' }}/>
    <div style={{ position: 'relative', background: 'var(--bg-surface)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', padding: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
        <span className="mono" style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{label}</span>
        <span style={{ marginLeft: 'auto', fontSize: 11, fontWeight: 700, color: 'var(--accent)', background: 'var(--primary-50)', border: '1px solid var(--primary-100)', borderRadius: 9999, padding: '4px 10px' }}>{badge}</span>
      </div>
      {children}
    </div>
  </div>
);

// ── Solution section ─────────────────────────────────────────────
const SolutionSection = ({ sol, index, registerRef, onLearn, onDemo }) => {
  const ref = useRefS(null);
  useEffectS(() => registerRef(sol.id, ref.current), []);
  const reversed = index % 2 === 1;
  const alt = index % 2 === 1;
  return (
    <section id={`sec-${sol.id}`} ref={ref} data-screen-label={sol.overline}
      style={{ background: alt ? 'var(--bg-surface)' : 'transparent', borderTop: '1px solid var(--border-subtle)',
        padding: 'clamp(28px, 4vw, 52px) 0', scrollMarginTop: 130 }}>
      <div className="wrap">
        <div className={`sol-grid ${reversed ? 'rev' : ''}`}>
          <div>
            <Reveal className="overline" style={{ color: 'var(--accent)', display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--primary-50)', border: '1px solid var(--primary-100)', display: 'grid', placeItems: 'center' }}><Icon name={sol.icon} size={15}/></span>
              {sol.overline}
            </Reveal>
            <Reveal as="h2" delay={1} style={{ fontFamily: 'var(--font-display)', fontWeight: 800, color: 'var(--brand-ink)',
              fontSize: 'clamp(30px, 4.2vw, 46px)', lineHeight: 1.06, letterSpacing: '-0.025em', margin: '18px 0 0' }}>
              {sol.title[0]}<br/>{sol.title[1]}
            </Reveal>
            <Reveal as="p" delay={2} style={{ fontSize: 'clamp(15px, 1.3vw, 18px)', lineHeight: 1.55, color: 'var(--fg-2)', maxWidth: 480, marginTop: 18 }}>{sol.blurb}</Reveal>
            <Reveal delay={3} style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginTop: 28 }}>
              <Btn icon="arrowRight" onClick={() => onLearn(sol.id)}>Learn more</Btn>
              <Btn variant="ghost" icon="play" onClick={() => onDemo(sol.id)}>See demo</Btn>
            </Reveal>
          </div>
          <Reveal delay={2}><SolutionVisual id={sol.id}/></Reveal>
        </div>

        {/* feature cards */}
        <div className="feat-grid" style={{ marginTop: 'clamp(36px, 5vw, 56px)' }}>
          {sol.features.map((f, i) => (
            <Reveal key={f.title} delay={(i % 4) + 1} className="fcard">
              <div className="ficon" style={{ transition: 'background var(--duration-base), color var(--duration-base)' }}><Icon name={f.icon} size={22}/></div>
              <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, color: 'var(--fg-1)', margin: '0 0 6px' }}>{f.title}</h3>
              <p style={{ fontSize: 14.5, lineHeight: 1.55, color: 'var(--fg-3)', margin: 0 }}>{f.desc}</p>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
};

// ── Section group with scrollspy ─────────────────────────────────
const Solutions = ({ onLearn, onDemo }) => {
  const [active, setActive] = useStateS('modernize');
  const refs = useRefS({});
  const registerRef = (id, el) => { if (el) refs.current[id] = el; };
  useEffectS(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) setActive(e.target.id.replace('sec-', '')); });
    }, { rootMargin: '-45% 0px -50% 0px', threshold: 0 });
    Object.values(refs.current).forEach((el) => el && obs.observe(el));
    return () => obs.disconnect();
  }, []);
  const jump = (id) => {
    const el = refs.current[id];
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 118, behavior: 'smooth' });
  };
  return (
    <>
      <SolutionsNav active={active} onJump={jump}/>
      {SOLUTIONS.map((s, i) => (
        <SolutionSection key={s.id} sol={s} index={i} registerRef={registerRef} onLearn={onLearn} onDemo={onDemo}/>
      ))}
    </>
  );
};

Object.assign(window, { Solutions, SOLUTIONS });
