// ISTOK Group — section components

// --- Logo (inline) ---
const Logo = ({ size = 36 }) => (
  <span className="logo-lockup">
    <img className="mark" src="site/assets/istok-logo-mark.svg" alt="" style={{ width: size }} />
    <span style={{ fontFamily: 'Michroma', fontSize: size * 0.36, letterSpacing: '0.04em', color: '#fff', fontWeight: 400 }}>ISTOK<span style={{ color: 'var(--ink-2)', marginLeft: 6, fontWeight: 300 }}>Group</span></span>
  </span>
);

// --- Reveal-on-scroll hook ---
const useReveal = () => {
  React.useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(en => {
        if (en.isIntersecting) {
          en.target.classList.add('in');
          io.unobserve(en.target);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -60px 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
};

// --- Nav ---
const Nav = ({ t, lang, onLang }) => {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll); onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className="nav" style={{
      background: scrolled ? 'rgba(5,7,26,0.85)' : 'rgba(5,7,26,0.45)',
      borderColor: scrolled ? 'rgba(212,222,249,0.18)' : 'rgba(212,222,249,0.08)',
    }}>
      <a href="#top" className="nav-logo"><Logo size={28} /></a>
      <div className="nav-links">
        {t.nav.links.map(l => <a key={l.href} href={l.href}>{l.label}</a>)}
      </div>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <button
          onClick={() => onLang(lang === 'en' ? 'ru' : 'en')}
          style={{
            fontFamily: 'Michroma', fontSize: 10, letterSpacing: '0.18em',
            color: 'var(--ink-2)', padding: '8px 12px', border: '1px solid var(--hairline)', borderRadius: 999,
          }}
          title="Switch language"
        >
          {lang === 'en' ? 'EN ↔ RU' : 'RU ↔ EN'}
        </button>
        <a href="#contact" className="nav-cta">{t.nav.cta}</a>
      </div>
    </nav>
  );
};

// --- Hero ---
const Hero = ({ t }) => {
  React.useEffect(() => {
    const cv = document.getElementById('hero-canvas');
    if (cv && window.startHeroCanvas) {
      const dispose = window.startHeroCanvas(cv);
      return dispose;
    }
  }, []);
  return (
    <section id="top" className="hero" data-screen-label="01 Hero">
      <div className="hero-rack"></div>
      <canvas id="hero-canvas" className="hero-canvas"></canvas>
      <div className="hero-orb"></div>
      <div className="section-inner hero-content">
        <div className="hero-eyebrow reveal">
          <span className="dot"></span>
          <span className="tech-label">{t.hero.eyebrow}</span>
        </div>
        <h1 className="display-1 hero-headline reveal d1">
          {t.hero.headline[0]} <em>{t.hero.headline[1]}</em><br />
          {t.hero.headline[2]}
        </h1>
        <p className="body-lg hero-sub reveal d2">{t.hero.sub}</p>
        <div className="hero-meta reveal d3">
          {t.hero.meta.map((m, i) => (
            <div className="hero-meta-item" key={i}>
              <div className="num">{m.num}</div>
              <div className="lbl">{m.lbl}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// --- Ticker ---
const Ticker = ({ items }) => (
  <div className="ticker" aria-hidden="true">
    <div className="ticker-track">
      {[...items, ...items, ...items].map((it, i) => (
        <span className="ticker-item" key={i}>{it}</span>
      ))}
    </div>
  </div>
);

// --- About ---
const About = ({ t }) => (
  <section id="about" className="about" data-screen-label="02 About">
    <div className="section-inner">
      <div className="section-header reveal">
        <span className="tech-label">{t.about.label}</span>
        <span className="tech-label">ISTOK / 2026</span>
      </div>
      <div className="about-grid">
        <div className="reveal d1">
          <h2 className="display-2">{t.about.title}</h2>
        </div>
        <div className="reveal d2">
          <p className="lead">{t.about.lead}</p>
          <p className="body-md" style={{ marginTop: 24 }}>{t.about.body}</p>
          <div className="partner-card">
            <div className="tech-label">{t.about.partner.label}</div>
            <h4>{t.about.partner.title}</h4>
            <p className="body-md" style={{ color: 'var(--ink-2)', margin: 0 }}>{t.about.partner.body}</p>
          </div>
        </div>
      </div>
    </div>
  </section>
);

// --- Service icons (simple stroke SVGs) ---
const ServiceIcon = ({ idx }) => {
  const a = 'rgb(71,158,254)';
  const w = 'rgba(212,222,249,0.7)';
  const common = { width: 56, height: 56, viewBox: '0 0 56 56', fill: 'none' };
  switch (idx) {
    case 0: // Rack build
      return (
        <svg {...common}>
          <rect x="10" y="6" width="36" height="44" stroke={w} strokeWidth="1.2" />
          {[10, 16, 22, 28, 34, 40].map(y => <line key={y} x1="14" y1={y} x2="42" y2={y} stroke={w} strokeWidth="1" />)}
          <circle cx="38" cy="13" r="1.6" fill={a} />
          <circle cx="38" cy="19" r="1.6" fill={a} />
        </svg>
      );
    case 1: // Labeling
      return (
        <svg {...common}>
          <path d="M8 14 L8 42 L24 42 L36 28 L36 14 Z" stroke={w} strokeWidth="1.2" />
          <line x1="14" y1="22" x2="30" y2="22" stroke={a} strokeWidth="1.4" />
          <line x1="14" y1="28" x2="26" y2="28" stroke={a} strokeWidth="1.4" />
          <line x1="14" y1="34" x2="22" y2="34" stroke={a} strokeWidth="1.4" />
        </svg>
      );
    case 2: // Cable pulling — spool
      return (
        <svg {...common}>
          <circle cx="22" cy="28" r="14" stroke={w} strokeWidth="1.2" />
          <circle cx="22" cy="28" r="6" stroke={w} strokeWidth="1.2" />
          <path d="M36 28 Q44 28, 48 18" stroke={a} strokeWidth="1.4" />
          <circle cx="48" cy="18" r="2" fill={a} />
        </svg>
      );
    case 3: // Patching
      return (
        <svg {...common}>
          <rect x="6" y="20" width="20" height="16" stroke={w} strokeWidth="1.2" />
          <rect x="30" y="20" width="20" height="16" stroke={w} strokeWidth="1.2" />
          <path d="M16 28 Q22 36, 40 28" stroke={a} strokeWidth="1.4" />
          <circle cx="16" cy="28" r="1.6" fill={a} />
          <circle cx="40" cy="28" r="1.6" fill={a} />
        </svg>
      );
    case 4: // Cable test — pass
      return (
        <svg {...common}>
          <rect x="12" y="6" width="24" height="38" rx="3" stroke={w} strokeWidth="1.2" />
          <circle cx="24" cy="22" r="6" stroke={a} strokeWidth="1.4" />
          <path d="M21 22 L23.5 24.5 L28 19.5" stroke={a} strokeWidth="1.4" fill="none" />
          <line x1="36" y1="14" x2="46" y2="14" stroke={w} strokeWidth="1" />
          <path d="M46 14 Q50 18, 46 22" stroke={a} strokeWidth="1.2" fill="none" />
        </svg>
      );
    case 5: // Troubleshooting — wrench
      return (
        <svg {...common}>
          <path d="M10 46 L24 32 M22 30 L28 24 A8 8 0 1 1 36 16 L30 22 L34 26 L40 20 A8 8 0 0 0 28 18" stroke={w} strokeWidth="1.2" fill="none" />
          <circle cx="40" cy="20" r="2" fill={a} />
        </svg>
      );
    case 6: // Cable dressing — vertical lines bundled
      return (
        <svg {...common}>
          {[14, 20, 26, 32, 38, 44].map(x => <line key={x} x1={x} y1="8" x2={x} y2="48" stroke={w} strokeWidth="1.2" />)}
          <rect x="10" y="18" width="38" height="3" stroke={a} strokeWidth="1" fill="none" />
          <rect x="10" y="34" width="38" height="3" stroke={a} strokeWidth="1" fill="none" />
        </svg>
      );
    case 7: // Lift / scissor
      return (
        <svg {...common}>
          <rect x="10" y="44" width="36" height="4" stroke={w} strokeWidth="1.2" />
          <rect x="14" y="10" width="28" height="6" stroke={a} strokeWidth="1.2" />
          <path d="M14 16 L42 44 M42 16 L14 44 M22 16 L34 44 M34 16 L22 44" stroke={w} strokeWidth="1" />
        </svg>
      );
    default: return null;
  }
};

// --- Services ---
const Services = ({ t }) => {
  useTileGlow();
  return (
    <section id="services" className="services" data-screen-label="03 Capabilities">
      <div className="section-inner">
        <div className="section-header reveal">
          <span className="tech-label">{t.services.label}</span>
          <span className="tech-label">8 / Disciplines</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, marginBottom: 56 }} className="reveal d1">
          <h2 className="display-2">{t.services.title}</h2>
          <p className="body-lg" style={{ alignSelf: 'end' }}>{t.services.sub}</p>
        </div>
        <div className="services-grid reveal d2">
          {t.services.items.map((it, i) => (
            <div className="service-tile" key={i}>
              <div className="service-glow"></div>
              <div className="num">{it.num} / 08</div>
              <div className="icon"><ServiceIcon idx={i} /></div>
              <div className="title">{it.title}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const useTileGlow = () => {
  React.useEffect(() => {
    const tiles = document.querySelectorAll('.service-tile');
    const handlers = [];
    tiles.forEach(tile => {
      const onMove = (e) => {
        const r = tile.getBoundingClientRect();
        tile.style.setProperty('--mx', ((e.clientX - r.left) / r.width * 100) + '%');
        tile.style.setProperty('--my', ((e.clientY - r.top) / r.height * 100) + '%');
      };
      tile.addEventListener('mousemove', onMove);
      handlers.push([tile, onMove]);
    });
    return () => handlers.forEach(([t, h]) => t.removeEventListener('mousemove', h));
  }, []);
};

// --- Animated number ---
const AnimatedNumber = ({ value }) => {
  // Parse leading number + suffix (e.g. ">400", "100,000", "24/7")
  const m = /^([>\d,\s\u00A0]+)(.*)$/.exec(value);
  if (!m) return <>{value}</>;
  const targetStr = m[1].replace(/\s|\u00A0|,/g, '').replace(/^>/, '');
  const target = parseInt(targetStr, 10);
  const suffix = m[2];
  const prefix = m[1].trim().startsWith('>') ? '>' : '';
  const [current, setCurrent] = React.useState(0);
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (isNaN(target)) return;
    const io = new IntersectionObserver(([en]) => {
      if (en.isIntersecting) {
        const dur = 1400;
        const t0 = performance.now();
        const raf = (now) => {
          const k = Math.min(1, (now - t0) / dur);
          const eased = 1 - Math.pow(1 - k, 3);
          setCurrent(Math.round(eased * target));
          if (k < 1) requestAnimationFrame(raf);
        };
        requestAnimationFrame(raf);
        io.disconnect();
      }
    }, { threshold: 0.4 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [target]);

  if (isNaN(target)) return <span ref={ref}>{value}</span>;
  const formatted = current.toLocaleString('en-US');
  return <span ref={ref}>{prefix}{formatted}{suffix}</span>;
};

// --- Numbers ---
const Numbers = ({ t }) => (
  <section id="numbers" className="numbers" data-screen-label="04 Numbers">
    <div className="section-inner">
      <div className="section-header reveal">
        <span className="tech-label">{t.numbers.label}</span>
        <span className="tech-label">As of Q2 / 2026</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, marginBottom: 56 }} className="reveal d1">
        <h2 className="display-2">{t.numbers.title}</h2>
        <p className="body-lg" style={{ alignSelf: 'end' }}>{t.numbers.sub}</p>
      </div>
      <div className="numbers-grid reveal d2">
        {t.numbers.stats.map((s, i) => (
          <div className="stat" key={i}>
            <div className="big">
              <AnimatedNumber value={s.big} />
              {s.light && <span className="light">{s.light}</span>}
            </div>
            <div className="lbl">{s.lbl}</div>
            <div className="desc">{s.desc}</div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// --- Expertise ---
const Expertise = ({ t }) => (
  <section id="expertise" className="expertise" data-screen-label="05 Expertise">
    <div className="section-inner">
      <div className="section-header reveal">
        <span className="tech-label">{t.expertise.label}</span>
        <span className="tech-label">Stack & Vendors</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 60 }}>
        <div className="reveal d1">
          <h2 className="display-2">{t.expertise.title}</h2>
        </div>
        <div className="reveal d2">
          <p className="body-lg">{t.expertise.body}</p>
          <div className="vendor-row">
            {t.expertise.vendors.map((v, i) => <span className="vendor-chip" key={i}>{v}</span>)}
          </div>
        </div>
      </div>
    </div>
  </section>
);

// --- Planning ---
const Planning = ({ t }) => (
  <section id="planning" className="planning" data-screen-label="06 Planning">
    <div className="section-inner">
      <div className="section-header reveal">
        <span className="tech-label">{t.planning.label}</span>
        <span className="tech-label">5-stage flow</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 60 }}>
        <div className="reveal d1">
          <h2 className="display-2">{t.planning.title}</h2>
        </div>
        <div className="reveal d2">
          <p className="body-lg">{t.planning.body}</p>
        </div>
      </div>
      <div className="steps reveal d3">
        {t.planning.steps.map((s, i) => (
          <div className="step" key={i}>
            <div className="num">{s.num} / 05</div>
            <div className="title">{s.title}</div>
            <div className="desc">{s.desc}</div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// --- Work gallery ---
const Work = ({ t }) => {
  const layouts = [
    { src: 'site/assets/work-01.jpg', cls: 's-5-3' },
    { src: 'site/assets/work-02.jpg', cls: 's-4-3' },
    { src: 'site/assets/work-08.jpg', cls: 's-3-3' },
    { src: 'site/assets/work-03.jpg', cls: 's-3-2' },
    { src: 'site/assets/work-05.jpg', cls: 's-4-2' },
    { src: 'site/assets/work-04.jpg', cls: 's-3-2' },
    { src: 'site/assets/work-06.jpg', cls: 's-6-2' },
    { src: 'site/assets/work-07.jpg', cls: 's-6-2' },
  ];
  return (
    <section id="work" className="work" data-screen-label="07 Work">
      <div className="section-inner">
        <div className="section-header reveal">
          <span className="tech-label">{t.work.label}</span>
          <span className="tech-label">Selected · 29 programs total</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, marginBottom: 0 }} className="reveal d1">
          <h2 className="display-2">{t.work.title}</h2>
          <p className="body-lg" style={{ alignSelf: 'end' }}>{t.work.sub}</p>
        </div>
        <div className="work-grid reveal d2">
          {layouts.map((l, i) => (
            <div key={i} className={"work-cell " + l.cls}>
              <img src={l.src} alt={t.work.tags[i]} loading="lazy" />
              <span className="meta">{String(i + 1).padStart(2, '0')} · {t.work.tags[i]}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// --- Why Us ---
const Why = ({ t }) => (
  <section id="why" className="why" data-screen-label="08 Why us">
    <div className="section-inner">
      <div className="section-header reveal">
        <span className="tech-label">{t.why.label}</span>
        <span className="tech-label">Reasons / 08</span>
      </div>
      <h2 className="display-2 reveal d1" style={{ maxWidth: 900 }}>{t.why.title}</h2>
      <div className="why-grid reveal d2">
        {t.why.items.map((it, i) => (
          <div className="why-cell" key={i}>
            <span className="icon-dot"></span>
            <div className="ttl">{it.ttl}</div>
            <div className="desc">{it.desc}</div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// --- Contact ---
const Contact = ({ t }) => (
  <section id="contact" className="contact" data-screen-label="09 Contact">
    <div className="grid-bg"></div>
    <div className="section-inner contact-inner">
      <div className="divider-with-num reveal">{t.contact.label}</div>
      <h2 className="display-1 reveal d1" style={{ marginTop: 32 }}>{t.contact.title}</h2>
      <p className="body-lg reveal d2" style={{ margin: '32px auto 48px', maxWidth: 720 }}>{t.contact.sub}</p>
      <a href={`mailto:${t.contact.email}`} className="btn-primary reveal d2">
        <span>{t.contact.cta}</span>
        <svg className="arrow" width="18" height="14" viewBox="0 0 18 14" fill="none"><path d="M1 7 H16 M11 2 L16 7 L11 12" stroke="currentColor" strokeWidth="1.6" fill="none" /></svg>
      </a>
      <div className="contact-grid reveal d3">
        <div className="contact-block">
          <span className="tech-label">Email</span>
          <span className="val"><a href={`mailto:${t.contact.email}`}>{t.contact.email}</a></span>
        </div>
        <div className="contact-block">
          <span className="tech-label">Phone</span>
          {t.contact.phones.map((p, i) => (
            <span className="val" key={i}><a href={`tel:${p.replace(/[^\d+]/g, '')}`}>{p}</a></span>
          ))}
        </div>
      </div>
    </div>
  </section>
);

// --- Footer ---
const Footer = ({ t }) => (
  <footer className="footer">
    <Logo size={22} />
    <span className="tech-label">{t.footer}</span>
  </footer>
);

// Expose
Object.assign(window, {
  Logo, Nav, Hero, Ticker, About, Services, Numbers, Expertise, Planning, Work, Why, Contact, Footer,
  useReveal,
});
