/* OSON — sections part 2 (Metrics, Products, Trust, News, CTA, Footer) */
const { useEffect: useEffect2, useRef: useRef2 } = React;
const D2 = window.OSON_DATA;
const { Counter, RegionChips, StoreBadges, useReveal } = window.OSON_SECTIONS_1;

/* ---------- METRICS ---------- */
function Metrics() {
  const ref = useReveal();
  return (
    <section className="metrics" ref={ref}>
      <div className="wrap">
        <div className="metrics-grid">
          {D2.METRICS.map((m, i) => (
            <div className="metric reveal" data-d={i} key={i}>
              {m.text
                ? <span className="num">{m.text}</span>
                : <Counter to={m.num} suf={m.suf}/>}
              <div className="lbl">{m.label}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- PRODUCTS ---------- */
function ProductCard({ p }) {
  return (
    <article className="prod-card" tabIndex="0" role="link"
      onClick={()=>{}} onKeyDown={e=>{if(e.key==='Enter'){}}}>
      <div className="prod-top">
        <span className="prod-ic"><Icon name={p.icon} weight="duotone"/></span>
        <span style={{display:'flex',gap:6,flexWrap:'wrap',justifyContent:'flex-end'}}><RegionChips regions={p.regions}/></span>
      </div>
      <div className="prod-name">{p.name}</div>
      <p className="prod-desc">{p.desc}</p>
      <span className="prod-more">Batafsil <Icon name="arrow"/></span>
    </article>
  );
}

function Spotlight({ p }) {
  return (
    <article className="prod-card spotlight" tabIndex="0" role="link">
      <div className="sp-body">
        <div className="prod-top">
          <span className="prod-ic"><Icon name={p.icon} weight="duotone"/></span>
          <span><RegionChips regions={p.regions}/></span>
        </div>
        <div className="prod-name">{p.name}</div>
        <p className="sp-desc">{p.desc}</p>
        <div className="sp-stats">
          <div><div className="v">170+</div><div className="k">davlat</div></div>
          <div><div className="v">5 daqiqa</div><div className="k">ulanish vaqti</div></div>
          <div><div className="v">0₸</div><div className="k">rouming uchun</div></div>
        </div>
        <a className="btn sp-btn" href="#" onClick={e=>e.preventDefault()}>eSIM olish <Icon name="arrow"/></a>
      </div>
      <div className="sp-visual">
        <svg viewBox="0 0 360 240" fill="none" style={{width:'100%',height:'100%',position:'absolute',inset:0}} aria-hidden="true">
          <g className="spin" style={{transformOrigin:'250px 120px',animationDuration:'80s'}} stroke="rgba(255,255,255,0.28)" strokeWidth="1.2">
            <circle cx="250" cy="120" r="110"/>
            <ellipse cx="250" cy="120" rx="40" ry="110"/>
            <ellipse cx="250" cy="120" rx="80" ry="110"/>
            <ellipse cx="250" cy="120" rx="110" ry="55"/>
            <line x1="140" y1="120" x2="360" y2="120"/>
          </g>
          <g fill="#9FDBFF">
            <circle className="ping" cx="180" cy="80" r="3"/>
            <circle className="ping" style={{animationDelay:'.8s'}} cx="320" cy="150" r="3"/>
            <circle className="ping" style={{animationDelay:'1.5s'}} cx="290" cy="60" r="3"/>
          </g>
        </svg>
      </div>
    </article>
  );
}

function Products() {
  const ref = useReveal();
  return (
    <section className="section products" id="products" ref={ref}>
      <div className="wrap">
        <div className="section-head reveal">
          <span className="eyebrow">Ekotizim</span>
          <h2>Bir brend — har bir moliyaviy ehtiyoj uchun</h2>
          <p>Kerakli mahsulotni 5 soniyada toping. Har bir yechim mintaqasi bilan belgilangan va o'z saytiga yo'naltiradi.</p>
        </div>
        <div className="prod-grid">
          {D2.PRODUCTS.map((p, i) => (
            <div className="reveal" data-d={(i%3)+1} key={p.id}><ProductCard p={p}/></div>
          ))}
          <div className="reveal" data-d="1" style={{gridColumn:'1 / -1'}}><Spotlight p={D2.SPOTLIGHT}/></div>
        </div>
      </div>
    </section>
  );
}

/* ---------- TRUST ---------- */
function Trust() {
  const ref = useReveal();
  const items = [
    { ic:'bank',  b:"O'zbekiston MB", s:'Litsenziya' },
    { ic:'bank',  b:"Qozog'iston Milliy banki", s:'Litsenziya' },
    { ic:'shield',b:'PCI DSS', s:'Level 1 sertifikat' },
    { ic:'star',  b:'4.8 reyting', s:'App Store · Google Play', stars:true },
  ];
  return (
    <section className="trust" ref={ref}>
      <div className="wrap">
        <div className="trust-inner reveal">
          <div className="trust-lead">Ishonch va xavfsizlik —<br/>regulyatorlar tomonidan tasdiqlangan</div>
          <div className="trust-items">
            {items.map((it,i)=>(
              <div className="trust-item" key={i}>
                <span className="ti-ic"><Icon name={it.ic}/></span>
                <span className="ti-t">
                  <b>{it.b}</b>
                  <span>{it.stars && <span className="stars">★★★★★ </span>}{it.s}</span>
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- NEWS ---------- */
function News() {
  const ref = useReveal();
  return (
    <section className="section news" id="news" ref={ref}>
      <div className="wrap">
        <div className="news-head reveal">
          <div>
            <span className="eyebrow">Yangiliklar</span>
            <h2 style={{fontSize:'40px',marginTop:'16px',lineHeight:1.1}}>OSON dunyosida nimalar yangi</h2>
          </div>
          <a className="btn btn-secondary" href="#" onClick={e=>e.preventDefault()}>Barcha yangiliklar <Icon name="arrow"/></a>
        </div>
        <div className="news-grid">
          {D2.NEWS.map((n,i)=>(
            <article className="news-card reveal" data-d={i+1} key={i} tabIndex="0">
              <div className="news-thumb">
                <span className="news-cat">{n.cat}</span>
                <div className={'ph-img' + (i===0?' brand':'')}><span className="ph-tag">rasm 16:9</span></div>
              </div>
              <div className="news-body">
                <span className="news-date">{n.date}</span>
                <h3 className="news-title">{n.title}</h3>
                <p className="news-ex">{n.ex}</p>
                <span className="news-read">O'qish <Icon name="arrow"/></span>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- CTA / DOWNLOAD ---------- */
function CtaStrip() {
  const ref = useReveal();
  return (
    <section className="ctastrip" id="download" ref={ref}>
      <div className="wrap">
        <div className="ctastrip-inner reveal">
          <h2>Butun moliya — cho'ntagingizda</h2>
          <p>OSON ilovasini yuklab oling va 3 million foydalanuvchiga qo'shiling.</p>
          <StoreBadges/>
        </div>
      </div>
    </section>
  );
}

/* ---------- FOOTER ---------- */
function Footer() {
  const cols = [
    { h:'Mahsulotlar', links:['Wallet','Terminal','OSON X','Neo','Business','eSIM','Kassa'] },
    { h:'Kompaniya', links:['Biz haqimizda','Jamoa','Litsenziyalar','Karyera','Investorlar'] },
    { h:'Resurslar', links:['Blog','Press-kit','Yordam markazi','Solutions'] },
    { h:'Yuridik', links:['Maxfiylik siyosati','Ommaviy oferta','Xavfsizlik'] },
  ];
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-top">
          <div className="footer-brand">
            <img src="assets/oson-logo-footer.svg?v=5" alt="OSON"/>
            <p>OSON — moliyaviy ko'priklar quramiz. Holding ekotizimining yagona kirish nuqtasi.</p>
            <div className="footer-social">
              {['telegram','instagram','youtube','facebook','linkedin'].map(s=>(
                <a key={s} href="#" onClick={e=>e.preventDefault()} aria-label={s}><Icon name={s}/></a>
              ))}
            </div>
          </div>
          {cols.map(c=>(
            <div className="footer-col" key={c.h}>
              <h4>{c.h}</h4>
              {c.links.map(l=><a key={l} href="#" onClick={e=>e.preventDefault()}>{l}</a>)}
            </div>
          ))}
        </div>
        <div className="footer-mid">
          <div style={{display:'flex',alignItems:'center',gap:'14px',color:'var(--gray-400)',fontSize:'14px'}}>
            <Icon name="pin" style={{width:18,height:18}}/> Toshkent, O'zbekiston
            <span style={{opacity:.4}}>·</span>
            <Icon name="mail" style={{width:18,height:18}}/> info@oson.com
          </div>
          <StoreBadges/>
        </div>
        <div className="footer-bottom">
          <div className="footer-entities">© 2026 OSON. Barcha huquqlar himoyalangan. · JSC BRIO GROUP · OSON Payments LLP</div>
        </div>
      </div>
    </footer>
  );
}

/* ---------- SECURITY — scanner card stream ----------
   Cards stream past a central scanner beam; as each crosses, its face is
   "decoded" into encrypted ASCII. Inspired by Evervault's scanner-card-stream,
   rebuilt dependency-free (canvas2d + CSS) for this no-build site. */
const SEC_FEATURES = [
  { ic:'lock',   t:'256-bit shifrlash', s:'Uchdan-uchgacha' },
  { ic:'shield', t:'PCI DSS Level 1',   s:'Sertifikatlangan' },
  { ic:'checkc', t:'3D Secure 2.0',     s:"Har bir to'lov" },
  { ic:'scan',   t:'Biometrik himoya',  s:'Face / Touch ID' },
  { ic:'repeat', t:'24/7 monitoring',   s:'AI firibgarlikka qarshi' },
  { ic:'bank',   t:'MB litsenziyasi',   s:'Tartibga solingan' },
];
const SEC_CHARS = "ABCDEF0123456789#$%&*<>{}[]/=+:abcdef";
function secAscii(cols, rows){
  let s='';
  for(let r=0;r<rows;r++){ for(let c=0;c<cols;c++){ s+=SEC_CHARS[(Math.random()*SEC_CHARS.length)|0]; } s+='\n'; }
  return s;
}

function Security(){
  const ref = useReveal();
  const stageRef = useRef2(null);
  const trackRef = useRef2(null);
  const canvasRef = useRef2(null);
  const REPEAT = 5;
  const cards = [];
  for(let i=0;i<SEC_FEATURES.length*REPEAT;i++){ cards.push({ id:i, f:SEC_FEATURES[i%SEC_FEATURES.length] }); }

  useEffect2(() => {
    const stage=stageRef.current, track=trackRef.current, canvas=canvasRef.current;
    if(!stage||!track||!canvas) return;
    const ctx=canvas.getContext('2d');
    const reduce=matchMedia('(prefers-reduced-motion: reduce)').matches;
    const cardEls=Array.from(track.querySelectorAll('.scard'));
    const normalEls=cardEls.map(el=>el.querySelector('.scard-normal'));
    const asciiEls=cardEls.map(el=>el.querySelector('.scard-ascii'));
    const preEls=cardEls.map(el=>el.querySelector('.scard-ascii pre'));

    let W=0,H=0,dpr=1,raf=0,pos=0,vel=-50,frame=0,unit=0,lastT=performance.now();
    const AUTO=-50, FR=0.90;
    let dragging=false,lastX=0,lastMoveT=0,ptrVel=0,particles=[],pmax=70;

    const measure=()=>{
      W=stage.clientWidth; H=stage.clientHeight;
      dpr=Math.min(window.devicePixelRatio||1,2);
      canvas.width=W*dpr; canvas.height=H*dpr;
      canvas.style.width=W+'px'; canvas.style.height=H+'px';
      ctx.setTransform(dpr,0,0,dpr,0,0);
      const cw=cardEls[0]?cardEls[0].offsetWidth:300;
      const gap=parseFloat(getComputedStyle(track).gap)||24;
      unit=(cw+gap)*SEC_FEATURES.length;
      if(!pos) pos=-unit;
    };
    const mkP=()=>({x:W/2+(Math.random()-0.5)*6,y:Math.random()*H,vx:Math.random()*1.1+0.25,vy:(Math.random()-0.5)*0.5,r:Math.random()*1.4+0.4,life:1,decay:Math.random()*0.013+0.004});

    const clips=()=>{
      const sr=stage.getBoundingClientRect(), scanX=sr.left+W/2;
      let scanning=false;
      for(let i=0;i<cardEls.length;i++){
        const r=cardEls[i].getBoundingClientRect();
        if(r.right<scanX){ normalEls[i].style.setProperty('--cr','100%'); asciiEls[i].style.setProperty('--cl','100%'); }
        else if(r.left>scanX){ normalEls[i].style.setProperty('--cr','0%'); asciiEls[i].style.setProperty('--cl','0%'); }
        else{
          scanning=true;
          const pct=(((scanX-r.left)/r.width)*100).toFixed(1)+'%';
          normalEls[i].style.setProperty('--cr',pct); asciiEls[i].style.setProperty('--cl',pct);
          if(frame%3===0&&preEls[i]) preEls[i].textContent=secAscii(42,12);
        }
      }
      return scanning;
    };

    const drawFX=(scanning)=>{
      ctx.clearRect(0,0,W,H);
      const target=scanning?160:75; pmax+=(target-pmax)*0.05;
      while(particles.length<pmax) particles.push(mkP());
      while(particles.length>pmax) particles.pop();
      ctx.globalCompositeOperation='lighter';
      for(const p of particles){
        p.x+=p.vx; p.y+=p.vy; p.life-=p.decay;
        if(p.life<=0||p.x>W) Object.assign(p,mkP());
        ctx.globalAlpha=Math.max(0,p.life)*0.65;
        ctx.fillStyle = p.r>1.15 ? '#8FE6FF' : '#2FB4FF';
        ctx.beginPath(); ctx.arc(p.x,p.y,p.r,0,6.2832); ctx.fill();
      }
      ctx.globalAlpha=1; ctx.globalCompositeOperation='source-over';
    };

    const tick=(t)=>{
      frame++;
      const now=t||performance.now();
      const dt=Math.min((now-lastT)/1000||0.016,0.05); lastT=now;
      if(!dragging){ vel=vel*FR+AUTO*(1-FR); }
      pos+=vel*dt;
      while(pos<=-unit) pos+=unit;
      while(pos>0) pos-=unit;
      track.style.transform='translateX('+pos+'px)';
      drawFX(clips());
      raf=requestAnimationFrame(tick);
    };

    measure();
    if(reduce){ track.style.transform='translateX('+(-unit)+'px)'; clips(); return; }

    const xOf=(e)=> e.touches ? e.touches[0].clientX : e.clientX;
    const down=(e)=>{ dragging=true; lastX=xOf(e); lastMoveT=performance.now(); ptrVel=0; stage.classList.add('grab'); };
    const move=(e)=>{ if(!dragging)return; const cx=xOf(e); const dx=cx-lastX; pos+=dx; const nt=performance.now(); const dtm=(nt-lastMoveT)/1000; if(dtm>0) ptrVel=Math.max(-1500,Math.min(1500,dx/dtm)); lastX=cx; lastMoveT=nt; };
    const up=()=>{ if(!dragging)return; dragging=false; vel=ptrVel; stage.classList.remove('grab'); };
    stage.addEventListener('mousedown',down); window.addEventListener('mousemove',move); window.addEventListener('mouseup',up);
    stage.addEventListener('touchstart',down,{passive:true}); window.addEventListener('touchmove',move,{passive:true}); window.addEventListener('touchend',up);
    let rt; const onR=()=>{ clearTimeout(rt); rt=setTimeout(measure,150); };
    window.addEventListener('resize',onR);
    raf=requestAnimationFrame(tick);
    return ()=>{ cancelAnimationFrame(raf); window.removeEventListener('resize',onR);
      stage.removeEventListener('mousedown',down); window.removeEventListener('mousemove',move); window.removeEventListener('mouseup',up);
      stage.removeEventListener('touchstart',down); window.removeEventListener('touchmove',move); window.removeEventListener('touchend',up); };
  }, []);

  return (
    <section className="security section" id="security" ref={ref}>
      <div className="wrap">
        <div className="sec-head reveal">
          <span className="sec-eyebrow"><span className="se-dot"></span>Ishonch va himoya</span>
          <h2>Bank darajasidagi <span className="grad">xavfsizlik</span></h2>
          <p>Har bir to'lov va ma'lumot bo'lagi skaner orqali o'tib, xalqaro standartlar bo'yicha real vaqtda shifrlanadi — to'xtovsiz himoya ostida.</p>
        </div>
      </div>
      <div className="scanner-stage" ref={stageRef}>
        <canvas className="scanner-fx" ref={canvasRef} aria-hidden="true"></canvas>
        <div className="scanner-track" ref={trackRef}>
          {cards.map(c => (
            <div className="scard" key={c.id}>
              <div className="scard-normal" style={{'--cr':'0%'}}>
                <span className="sc-chip"></span>
                <span className="sc-dot"></span>
                <span className="sc-ic"><Icon name={c.f.ic}/></span>
                <span className="sc-meta"><b>{c.f.t}</b><i>{c.f.s}</i></span>
              </div>
              <div className="scard-ascii" style={{'--cl':'0%'}}><pre>{secAscii(42,12)}</pre></div>
            </div>
          ))}
        </div>
        <div className="scanner-line" aria-hidden="true"></div>
      </div>
      <div className="wrap">
        <div className="sec-foot reveal">
          <span><Icon name="checkc"/> ISO 27001</span>
          <span><Icon name="checkc"/> Visa · Mastercard hamkori</span>
          <span><Icon name="checkc"/> 99.99% uptime</span>
          <span><Icon name="checkc"/> Ma'lumotlar O'zbekistonda</span>
        </div>
      </div>
    </section>
  );
}

window.OSON_SECTIONS_2 = { Metrics, Products, Trust, News, CtaStrip, Footer, Security };
