// ui.jsx — shared UI primitives for the Khail app
(function(){
  const { useState, useRef, useLayoutEffect } = React;
  const Icon = window.Icon;

  // ── Screen header (RTL: back on the right) ──
  function Header({ title, onBack, right }){
    return (
      <div className="hdr">
        {onBack
          ? <button className="hdr-btn" onClick={onBack} aria-label="رجوع"><Icon name="chevron-r" size={22} sw={2.2}/></button>
          : <div style={{width:40}} />}
        <div className="hdr-title ar">{title}</div>
        {right || <div style={{width:40}} />}
      </div>
    );
  }

  // ── Status badge ──
  function Badge({ status }){
    const s = window.DATA.feedStatus[status] || status;
    const cls = s.cls || 'ok';
    return <span className={'badge '+cls}><span className="dot"/>{s.label}</span>;
  }

  // ── Animated segmented control ──
  function Segmented({ items, value, onChange }){
    const wrapRef = useRef(null);
    const [thumb,setThumb] = useState({right:4,width:0});
    useLayoutEffect(()=>{
      const wrap = wrapRef.current; if(!wrap) return;
      const idx = items.findIndex(i=>i.id===value);
      const el = wrap.querySelectorAll('.seg-item')[idx];
      if(el) setThumb({ right: el.offsetLeft + (wrap.clientWidth - el.offsetLeft - el.offsetWidth), width: el.offsetWidth });
    },[value,items]);
    // RTL: compute right offset directly
    useLayoutEffect(()=>{
      const wrap = wrapRef.current; if(!wrap) return;
      const idx = items.findIndex(i=>i.id===value);
      const el = wrap.querySelectorAll('.seg-item')[idx];
      if(el) setThumb({ right: wrap.clientWidth - el.offsetLeft - el.offsetWidth, width: el.offsetWidth });
    },[value,items]);
    return (
      <div className="seg" ref={wrapRef}>
        <div className="seg-thumb" style={{ right:thumb.right, width:thumb.width }}/>
        {items.map(i=>(
          <button key={i.id} className={'seg-item ar '+(i.id===value?'on':'')} onClick={()=>onChange(i.id)}>{i.label}</button>
        ))}
      </div>
    );
  }

  // ── Horse avatar placeholder (circular) ──
  function HorseAvatar({ size=72, ring=true, label='صورة الحصان' }){
    const img = (
      <div className="ph" style={{ width:size, height:size, borderRadius:'50%' }}>
        <span className="ph-label">{label}</span>
      </div>
    );
    return ring ? <div className="avatar-ring" style={{width:size+6,height:size+6}}>{img}</div> : img;
  }

  // ── Product / feed-bag thumbnail placeholder ──
  function ProductThumb({ size=52, tone='#3C5C3F', radius=13, label, ratio=1 }){
    const fluid = size === '100%';
    const box = fluid
      ? { width:'100%', aspectRatio:'1 / '+ratio }
      : { width:size, height:size };
    const fs = fluid ? 11 : Math.max(7,size*0.13);
    return (
      <div className="ph" style={{ ...box, borderRadius:radius,
        backgroundImage:`repeating-linear-gradient(135deg, ${tone}22 0 7px, ${tone}05 7px 14px)` }}>
        <span className="ph-label" style={{color:tone, fontSize:fs}}>
          {label ? label : <React.Fragment>كيس<br/>علف</React.Fragment>}
        </span>
      </div>
    );
  }

  // ── Spec table (الاسم / العمر …) ──
  function SpecRow({ k, v }){
    return (
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'7px 0'}}>
        <span className="ar t-mut t-sm" style={{fontWeight:700}}>{k}</span>
        <span className="ar lead" style={{fontSize:15.5,color:'var(--ink)'}}>{v}</span>
      </div>
    );
  }

  // ── Small key/value used in summaries ──
  function KV({ k, v, strong, accent }){
    return (
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'6px 0'}}>
        <span className={'ar '+(strong?'lead':'t-mut')} style={{fontSize:strong?15:13.5}}>{k}</span>
        <span className={(strong?'price':'num')} style={{fontSize:strong?17:14, color:accent||(strong?'var(--green)':'var(--ink)'), fontWeight:strong?700:600}}>{v}</span>
      </div>
    );
  }

  // ── Security footer note ──
  function SecureNote({ text='جميع البيانات محفوظة وآمنة.' }){
    return (
      <div style={{display:'flex', alignItems:'center', justifyContent:'center', gap:7, padding:'18px 0 6px', color:'var(--muted)'}}>
        <Icon name="shield" size={15} sw={1.7}/>
        <span className="ar" style={{fontSize:12.5, fontWeight:700}}>{text}</span>
      </div>
    );
  }

  // ── Section label ──
  function SectionTitle({ children, icon }){
    return (
      <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:12}}>
        {icon && <span style={{color:'var(--green)'}}><Icon name={icon} size={18}/></span>}
        <h3 className="ar lead" style={{margin:0, fontSize:16, color:'var(--ink)'}}>{children}</h3>
      </div>
    );
  }

  // ── Bottom tab bar ──
  const TABS = [
    { id:'home',      label:'الرئيسية', icon:'home' },
    { id:'feed',      label:'المتجر',   icon:'bag' },
    { id:'vet',       label:'البيطري',  icon:'stetho' },
    { id:'transport', label:'النقل',    icon:'truck' },
    { id:'more',      label:'المزيد',   icon:'dots' },
  ];
  function TabBar({ active, onTab, cartCount=0 }){
    return (
      <div className="tabbar">
        <div className="tabbar-inner">
          {TABS.map(t=>{
            const badge = t.id==='feed' && cartCount>0 ? cartCount : null;
            return (
              <button key={t.id} className={'tab '+(active===t.id?'on':'')} onClick={()=>onTab(t.id)}>
                <span className="ic">
                  <Icon name={t.icon} size={23} sw={active===t.id?2.1:1.8}/>
                  {badge && <span className="tab-badge num">{badge}</span>}
                </span>
                <span>{t.label}</span>
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  // ── Star rating inline ──
  function Stars({ value }){
    return (
      <span style={{display:'inline-flex', alignItems:'center', gap:4, color:'var(--gold)'}}>
        <Icon name="star" size={15} fill="var(--gold)"/>
        <span className="num" style={{fontWeight:700, fontSize:13, color:'var(--ink)'}}>{value}</span>
      </span>
    );
  }

  Object.assign(window, { Header, Badge, Segmented, HorseAvatar, ProductThumb, SpecRow, KV, SecureNote, SectionTitle, TabBar, Stars });
})();
