/* OSON — sections (Header, Hero variants, Metrics, Products, Trust, News, CTA, Footer) */
const { useState, useEffect, useRef } = React;
const D = window.OSON_DATA;

/* ---------- helpers ---------- */
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const els = ref.current ? ref.current.querySelectorAll('.reveal') : [];
    const io = new IntersectionObserver((ents) => {
      ents.forEach(e => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { threshold: 0.14, rootMargin: '0px 0px -8% 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
  return ref;
}

function Counter({ to, suf, dur = 1500 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  useEffect(() => {
    let raf, started = false;
    const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
    const io = new IntersectionObserver((ents) => {
      ents.forEach(e => {
        if (e.isIntersecting && !started) {
          started = true;
          if (reduce) { setVal(to); return; }
          const t0 = performance.now();
          const tick = (t) => {
            const p = Math.min((t - t0) / dur, 1);
            const eased = 1 - Math.pow(1 - p, 3);
            setVal(Math.round(eased * to));
            if (p < 1) raf = requestAnimationFrame(tick);
          };
          raf = requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.6 });
    if (ref.current) io.observe(ref.current);
    return () => { io.disconnect(); cancelAnimationFrame(raf); };
  }, [to]);
  return <span ref={ref} className="num">{val}<span className="suf">{suf}</span></span>;
}

function RegionChips({ regions }) {
  return regions.filter(r => r !== 'global').map(r => (
    <span key={r} className={'chip chip-' + r}>
      <span className="chip-dot"></span>{D.REGION_LABEL[r]}
    </span>
  ));
}

function StoreBadges({ stores = ['apple','google'] }) {
  const cfg = {
    apple:  { src:'assets/app-store-badge.svg',   alt:'Download on the App Store' },
    google: { src:'assets/google-play-badge.png', alt:'Get it on Google Play' },
  };
  return (
    <div className="store-row">
      {stores.map(s => cfg[s] ? (
        <a key={s} className={'store-badge sb-'+s} href="#" onClick={e=>e.preventDefault()} aria-label={cfg[s].alt}>
          <img src={cfg[s].src} alt={cfg[s].alt}/>
        </a>
      ) : null)}
    </div>
  );
}

/* ---------- HEADER ---------- */
function Header() {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const go = (id) => (e) => { e.preventDefault(); document.getElementById(id)?.scrollIntoView({ behavior:'smooth', block:'start' }); };
  const navTo = (id) => (e) => { e.preventDefault(); setMenuOpen(false); if (id) document.getElementById(id)?.scrollIntoView({ behavior:'smooth', block:'start' }); };
  return (
    <header className={'site-header' + (scrolled ? ' scrolled' : '')}>
      <div className="wrap">
        <nav className="nav">
          <a className="nav-logo" href="#" onClick={e=>{e.preventDefault();window.scrollTo({top:0,behavior:'smooth'});}}>
            <img src="assets/oson-logo-header.svg?v=3" alt="OSON" />
          </a>
          <div className="nav-main">
            <div className="nav-item">
              <button className="nav-link">Yechimlar <Icon name="chevron" style={{width:15,height:15}}/></button>
              <div className="dropdown">
                <div className="dropdown-inner mega">
                  {[...D.PRODUCTS, D.SPOTLIGHT].map(p => (
                    <a key={p.id} className="mega-link" href="#products" onClick={go('products')}>
                      <span className="mega-ic"><Icon name={p.icon}/></span>
                      <span><span className="mega-tt">{p.name}</span><span className="mega-ds">{p.desc}</span></span>
                    </a>
                  ))}
                </div>
              </div>
            </div>
            <div className="nav-item">
              <button className="nav-link">Kompaniya <Icon name="chevron" style={{width:15,height:15}}/></button>
              <div className="dropdown">
                <div className="dropdown-inner menu">
                  {D.COMPANY_MENU.map(m => (
                    <a key={m.t} href="#" onClick={e=>e.preventDefault()}><Icon name={m.ic}/>{m.t}</a>
                  ))}
                </div>
              </div>
            </div>
            <a className="nav-link" href="#news" onClick={go('news')}>Yangiliklar</a>
            <a className="nav-link" href="#" onClick={e=>e.preventDefault()}>Kontaktlar</a>
          </div>
          <div className="nav-right">
            <a className="btn btn-primary" href="#download" onClick={go('download')}>
              <Icon name="phone"/>Ilovani yuklab olish
            </a>
          </div>
          <button className={'nav-burger' + (menuOpen ? ' open' : '')} aria-label="Menyu" aria-expanded={menuOpen} onClick={()=>setMenuOpen(o=>!o)}>
            <span></span><span></span><span></span>
          </button>
        </nav>
      </div>
      <div className={'mobile-nav' + (menuOpen ? ' open' : '')}>
        <a href="#products" onClick={navTo('products')}>Yechimlar</a>
        <a href="#" onClick={navTo()}>Kompaniya</a>
        <a href="#news" onClick={navTo('news')}>Yangiliklar</a>
        <a href="#" onClick={navTo()}>Kontaktlar</a>
        <a className="btn btn-primary" href="#download" onClick={navTo('download')}>
          <Icon name="phone"/>Ilovani yuklab olish
        </a>
      </div>
      <div className={'nav-backdrop' + (menuOpen ? ' show' : '')} onClick={()=>setMenuOpen(false)}></div>
    </header>
  );
}

/* ---------- GLOBE (geometric) ---------- */
function Globe() {
  return (
    <svg className="globe" viewBox="0 0 640 640" fill="none" aria-hidden="true">
      <defs>
        <radialGradient id="gcore" cx="38%" cy="32%" r="75%">
          <stop offset="0%" stopColor="#3a57e8" stopOpacity="0.18"/>
          <stop offset="55%" stopColor="#000F9E" stopOpacity="0.10"/>
          <stop offset="100%" stopColor="#000F9E" stopOpacity="0"/>
        </radialGradient>
      </defs>
      <circle cx="320" cy="320" r="230" fill="url(#gcore)"/>
      <g className="spin" stroke="#000F9E" strokeOpacity="0.16" strokeWidth="1.4">
        <circle cx="320" cy="320" r="230"/>
        <ellipse cx="320" cy="320" rx="78" ry="230"/>
        <ellipse cx="320" cy="320" rx="156" ry="230"/>
        <ellipse cx="320" cy="320" rx="220" ry="230"/>
        <line x1="90" y1="320" x2="550" y2="320"/>
        <ellipse cx="320" cy="320" rx="230" ry="110"/>
        <ellipse cx="320" cy="320" rx="230" ry="200"/>
      </g>
      {/* transfer arcs */}
      <g stroke="#2FB4FF" strokeWidth="2" fill="none">
        <path className="arc" d="M150 380 Q 320 120 500 280"/>
        <path className="arc" style={{animationDelay:'0.8s'}} d="M180 230 Q 360 460 470 420"/>
        <path className="arc" style={{animationDelay:'1.6s'}} d="M250 470 Q 420 360 520 200"/>
      </g>
      <g fill="#2FB4FF">
        <circle className="ping" cx="150" cy="380" r="3.4"/>
        <circle className="ping" style={{animationDelay:'0.7s'}} cx="500" cy="280" r="3.4"/>
        <circle className="ping" style={{animationDelay:'1.2s'}} cx="470" cy="420" r="3.4"/>
        <circle className="ping" style={{animationDelay:'1.9s'}} cx="250" cy="470" r="3.4"/>
        <circle className="ping" style={{animationDelay:'2.3s'}} cx="180" cy="230" r="3.4"/>
      </g>
    </svg>
  );
}

/* ---------- NEURAL FLOW-FIELD BACKGROUND ----------
   Tuned for the LIGHT hero: transparent canvas, soft fading trails toward
   the page background, particles in brand-blue + cyan. Sits beneath the
   grid + gradient layers; mouse repels the flow. Respects reduced-motion. */
function NeuralField({ active = true }) {
  const canvasRef = useRef(null);
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (!active || reduce) return;

    const ctx = canvas.getContext('2d');
    const host = canvas.parentElement;          // .hero-bg
    let width = 0, height = 0, dpr = 1, raf = 0;
    let particles = [];
    const mouse = { x: -9999, y: -9999 };

    // muted blue palette — calm, recedes into the background (read once, rgb tuples)
    const COLORS = [
      [70, 95, 175],     // muted brand-blue
      [120, 150, 210],   // soft periwinkle-blue
      [150, 175, 215],   // light blue-grey
      [110, 135, 195],
    ];

    const isMobile = () => window.innerWidth < 760;

    class P {
      constructor() { this.reset(true); }
      reset(spread) {
        this.x = Math.random() * width;
        this.y = Math.random() * height;
        this.vx = 0; this.vy = 0;
        this.age = spread ? Math.random() * 200 : 0;
        this.life = Math.random() * 220 + 120;
        this.col = COLORS[(Math.random() * COLORS.length) | 0];
        this.sz = Math.random() < 0.22 ? 2 : 1.5;
      }
      step() {
        const a = (Math.cos(this.x * 0.0042) + Math.sin(this.y * 0.0042)) * Math.PI;
        this.vx += Math.cos(a) * 0.18;
        this.vy += Math.sin(a) * 0.18;
        const dx = mouse.x - this.x, dy = mouse.y - this.y;
        const d = Math.sqrt(dx * dx + dy * dy), R = 150;
        if (d < R) {
          const f = (R - d) / R;
          this.vx -= dx * f * 0.045;
          this.vy -= dy * f * 0.045;
        }
        this.x += this.vx; this.y += this.vy;
        this.vx *= 0.95; this.vy *= 0.95;
        if (++this.age > this.life) this.reset(false);
        if (this.x < 0) this.x = width; else if (this.x > width) this.x = 0;
        if (this.y < 0) this.y = height; else if (this.y > height) this.y = 0;
      }
      draw() {
        const fade = 1 - Math.abs(this.age / this.life - 0.5) * 2;
        ctx.globalAlpha = fade * 0.7;
        ctx.fillStyle = `rgb(${this.col[0]},${this.col[1]},${this.col[2]})`;
        // snap to whole device pixels → crisp dots, no sub-pixel blur
        ctx.fillRect(Math.round(this.x * dpr) / dpr, Math.round(this.y * dpr) / dpr, this.sz, this.sz);
      }
    }

    const setup = () => {
      width = host.clientWidth; height = host.clientHeight;
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      canvas.width = width * dpr; canvas.height = height * dpr;
      canvas.style.width = width + 'px'; canvas.style.height = height + 'px';
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      const count = isMobile() ? 220 : Math.min(600, Math.round(width * height / 2800));
      particles = Array.from({ length: count }, () => new P());
      ctx.clearRect(0, 0, width, height);
    };

    const tick = () => {
      // fade toward transparent → trails persist longer = crisper streaks
      ctx.globalAlpha = 1;
      ctx.globalCompositeOperation = 'destination-out';
      ctx.fillStyle = 'rgba(0,0,0,0.10)';
      ctx.fillRect(0, 0, width, height);
      ctx.globalCompositeOperation = 'source-over';
      for (const p of particles) { p.step(); p.draw(); }
      ctx.globalAlpha = 1;
      raf = requestAnimationFrame(tick);
    };

    const onMove = (e) => {
      const r = canvas.getBoundingClientRect();
      mouse.x = e.clientX - r.left; mouse.y = e.clientY - r.top;
    };
    const onLeave = () => { mouse.x = -9999; mouse.y = -9999; };
    let rt;
    const onResize = () => { clearTimeout(rt); rt = setTimeout(setup, 160); };

    setup(); tick();
    window.addEventListener('resize', onResize);
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseout', onLeave);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', onResize);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseout', onLeave);
    };
  }, [active]);

  return <canvas ref={canvasRef} className="hero-neural" aria-hidden="true"></canvas>;
}

/* ---------- HERO ---------- */
function HeroEyebrow() {
  return (
    <div className="hero-eyebrow">
      <span className="tag">YANGI</span>
      OSON ekotizimi — 7 ta moliyaviy mahsulot
    </div>
  );
}
function HeroNote() {
  return (
    <div className="hero-note">
      <span><Icon name="checkc"/> Markaziy bank litsenziyasi</span>
      <span><Icon name="checkc"/> PCI DSS sertifikati</span>
      <span><Icon name="checkc"/> 3 mln+ foydalanuvchi</span>
    </div>
  );
}
function HeroHeadline({ big }) {
  return (
    <h1>
      Moliyaviy <span className="grad">ko'priklar</span><br/>quramiz
    </h1>
  );
}
function HeroButtons({ scrollTo }) {
  return (
    <div className="hero-cta">
      <a className="btn btn-primary btn-lg magnetic" href="#download" onClick={scrollTo('download')}>
        <Icon name="phone"/>Ilovani yuklab olish
      </a>
      <a className="btn btn-secondary btn-lg" href="#products" onClick={scrollTo('products')}>
        Mahsulotlarni ko'rish <Icon name="arrow"/>
      </a>
    </div>
  );
}

function Hero({ variant, sub, neural = true }) {
  const SUB = sub || "Dunyoning istalgan nuqtasida qulay, tez va sodda moliyaviy xizmatlar — bitta ekotizimda.";
  const stageRef = useRef(null);
  const scrollTo = (id) => (e) => { e.preventDefault(); document.getElementById(id)?.scrollIntoView({ behavior:'smooth' }); };

  // parallax (desktop only)
  useEffect(() => {
    if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const stage = stageRef.current; if (!stage) return;
    const layers = stage.querySelectorAll('[data-px]');
    const onMove = (e) => {
      const cx = (e.clientX / window.innerWidth - 0.5);
      const cy = (e.clientY / window.innerHeight - 0.5);
      layers.forEach(l => {
        const d = parseFloat(l.dataset.px);
        l.style.transform = `translate(${cx * d}px, ${cy * d}px)`;
      });
    };
    if (window.innerWidth > 1024) window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, [variant]);

  return (
    <section className="hero" ref={stageRef}>
      <div className="hero-bg">
        <NeuralField active={neural}/>
        <div className="hero-grid-lines"></div>
        <div className="hero-gradient" data-px="-14"></div>
      </div>

      {variant === 'globe' && (
        <div className="wrap">
          <div className="globe-wrap" data-px="18"><Globe/></div>
          <div className="heroA">
            <div className="hero-inner">
              <div className="reveal in"><HeroEyebrow/></div>
              <div className="reveal in" data-d="1"><HeroHeadline/></div>
              <p className="hero-sub reveal in" data-d="2">{SUB}</p>
              <div className="reveal in" data-d="3"><HeroButtons scrollTo={scrollTo}/></div>
              <div className="reveal in" data-d="4"><HeroNote/></div>
            </div>
          </div>
        </div>
      )}

      {variant === 'split' && (
        <div className="wrap">
          <div className="heroB">
            <div>
              <div className="reveal in"><HeroEyebrow/></div>
              <div className="reveal in" data-d="1"><HeroHeadline/></div>
              <p className="hero-sub reveal in" data-d="2">{SUB}</p>
              <div className="reveal in" data-d="3"><HeroButtons scrollTo={scrollTo}/></div>
              <div className="reveal in" data-d="4"><HeroNote/></div>
            </div>
            <div className="phone-stage reveal in" data-d="2">
              <div className="phone-glow" data-px="20"></div>
              <PhoneMock/>
              <div className="float-badge fb-1" data-px="-26">
                <span className="fb-ic" style={{background:'var(--brand)'}}><Icon name="send" style={{width:16,height:16}}/></span>
                O'tkazma yuborildi
              </div>
              <div className="float-badge fb-2" data-px="-32">
                <span className="fb-ic" style={{background:'var(--success)'}}><Icon name="check" style={{width:16,height:16}}/></span>
                +1 250 000 so'm
              </div>
            </div>
          </div>
        </div>
      )}

      {variant === 'minimal' && (
        <div className="wrap">
          <div className="heroC">
            <div className="hero-inner">
              <div className="reveal in"><HeroEyebrow/></div>
              <h1 className="reveal in" data-d="1">Moliyaviy <span className="grad">ko'priklar</span> quramiz</h1>
              <p className="hero-sub reveal in" data-d="2">{SUB}</p>
              <div className="reveal in" data-d="3"><HeroButtons scrollTo={scrollTo}/></div>
              <div className="hero-marquee reveal in" data-d="4">
                {[...D.PRODUCTS, D.SPOTLIGHT].map(p => (
                  <span key={p.id} className="hero-pill"><Icon name={p.icon}/>{p.name.replace('OSON ','')}</span>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

function PhoneMock() {
  return (
    <div className="phone">
      <div className="phone-notch"></div>
      <div className="phone-screen">
        <div className="ph-app">
          <div className="ph-balcard">
            <div className="lbl">Umumiy balans</div>
            <div className="amt">12 480 500 so'm</div>
          </div>
          <div className="ph-row">
            {[['send',"O'tkazma"],['phone','To\'lov'],['swap','Ayirbosh'],['card','Karta']].map(([ic,t])=>(
              <div className="ph-act" key={t}><span className="ic"><Icon name={ic}/></span><span className="t">{t}</span></div>
            ))}
          </div>
          <div className="ph-list">
            {[['Anvar K.','Bugun, 14:20','-150 000',''],['OSON eSIM','Kecha','-89 000',''],['Maosh','24 May','+4 200 000','in']].map(([n,d,v,c])=>(
              <div className="ph-tx" key={n}>
                <span className="av"></span>
                <span className="meta"><b>{n}</b><span>{d}</span></span>
                <span className={'val '+c}>{v}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.OSON_SECTIONS_1 = { Header, Hero, StoreBadges, RegionChips, Counter, useReveal };
