/* ============================================================
   Lima Android — device shell: status bar, app bar, bottom nav
   ============================================================ */

/* ---------- status bar (Lima tinted) ---------- */
function StatusBar({dark=false}){
  const c = dark ? '#ffffff' : 'var(--ink)';
  return (
    <div style={{height:34,flex:'0 0 auto',display:'flex',alignItems:'center',justifyContent:'space-between',
      padding:'0 18px 0 20px',position:'relative',fontFamily:'Roboto, system-ui, sans-serif',background:'transparent'}}>
      <span style={{fontSize:14,fontWeight:600,letterSpacing:.2,color:c}}>9:30</span>
      <div style={{position:'absolute',left:'50%',top:7,transform:'translateX(-50%)',width:22,height:22,borderRadius:100,background:'#1a1a1a'}}></div>
      <div style={{display:'flex',alignItems:'center',gap:6,color:c}}>
        <svg width="17" height="13" viewBox="0 0 17 13" fill="currentColor"><rect x="0" y="8" width="3" height="5" rx="1"/><rect x="4.5" y="5" width="3" height="8" rx="1"/><rect x="9" y="2.5" width="3" height="10.5" rx="1"/><rect x="13.5" y="0" width="3" height="13" rx="1"/></svg>
        <svg width="16" height="13" viewBox="0 0 16 13" fill="currentColor"><path d="M8 12.5 .4 4.8a10.6 10.6 0 0115.2 0L8 12.5z"/></svg>
        <svg width="24" height="13" viewBox="0 0 24 13"><rect x="1" y="1.4" width="20" height="10.2" rx="2.6" fill="none" stroke="currentColor" strokeWidth="1.3" opacity="0.5"/><rect x="2.6" y="3" width="15" height="7" rx="1.4" fill="currentColor"/><rect x="22" y="4.5" width="1.6" height="4" rx="0.8" fill="currentColor" opacity="0.6"/></svg>
      </div>
    </div>
  );
}

/* ---------- top app bar ---------- */
function AppBar({variant='home', title, onBack, onBell, prov, onProv, scrolled}){
  if(variant==='back'){
    return <div style={{flex:'0 0 auto',display:'flex',alignItems:'center',gap:6,padding:'6px 8px 6px 4px',height:56,
      background: scrolled?'var(--paper)':'transparent',borderBottom:scrolled?'1px solid var(--line)':'1px solid transparent',transition:'.18s'}}>
      <button onClick={onBack} style={iconBtn}><Icon name="back" size={23}/></button>
      <span className="serif" style={{flex:1,fontSize:19,fontWeight:700,color:'var(--ink)',opacity:scrolled?1:0,transition:'.18s',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{title}</span>
      {onBell && <button onClick={onBell} style={iconBtn}><Icon name="bell" size={21}/></button>}
    </div>;
  }
  // home variant: logo + bell
  return <div style={{flex:'0 0 auto',display:'flex',alignItems:'center',gap:11,padding:'8px 12px 8px 16px',height:58,
    background: scrolled?'var(--paper)':'transparent',borderBottom:scrolled?'1px solid var(--line)':'1px solid transparent',transition:'.18s'}}>
    <LogoMark size={32}/>
    <Wordmark size={19} sub={false}/>
    {prov && <button onClick={onProv} style={{marginLeft:'auto',display:'inline-flex',alignItems:'center',gap:5,padding:'7px 12px',borderRadius:999,
      border:'1.5px solid var(--line-d)',background:'var(--paper)',color:'var(--ink)',fontWeight:700,fontSize:13}}>
      <Icon name="pin" size={15} style={{color:'var(--green)'}}/>{prov}<Icon name="chev" size={15} style={{color:'var(--ink-faint)'}}/>
    </button>}
    <button onClick={onBell} style={{...iconBtn, marginLeft: prov?0:'auto'}}><Icon name="bell" size={21}/></button>
  </div>;
}
const iconBtn={width:44,height:44,borderRadius:999,border:'none',background:'transparent',color:'var(--ink)',display:'grid',placeItems:'center',flex:'0 0 auto',cursor:'pointer'};

/* ---------- news ticker (compact, mobile) ---------- */
function NewsTickerM({go}){
  const feeds=useNewsFeeds();
  const trackRef=useRef(null);
  const movers=D.market_prices.filter(m=>m.price_zmw_per_kg!=null).sort((a,b)=>Math.abs(b.change_pct)-Math.abs(a.change_pct)).slice(0,4);
  const tag=t=><b className={'tkm-src tkm-src-'+t.replace(/\s/g,'').toLowerCase()}>[{t}]</b>;
  const items=[];
  feeds.items.forEach((n,i)=>items.push(<span key={'r'+i} className="tkm-item">{tag(n.tag)}{n.title}</span>));
  D.news.slice(0,3).forEach((n,i)=>items.push(<span key={'n'+i} className="tkm-item">{tag('KU-LIMA')}{n.title}</span>));
  movers.forEach((m,i)=>{const col=m.trend==='up'?'#8fdcab':m.trend==='down'?'#f0a99e':'#cdd6e6';const ar=m.trend==='up'?'▲':m.trend==='down'?'▼':'▬';
    items.push(<span key={'m'+i} className="tkm-item">{tag('KU-LIMA')}{m.crop} <b>{ZMW(m.price_zmw_per_kg,2)}</b>/kg <span style={{color:col,fontWeight:700}}>{ar} {m.change_pct>0?'+':''}{m.change_pct}%</span></span>);});
  const woven=[];items.forEach((it,i)=>{woven.push(it);woven.push(<span key={'s'+i} className="tkm-sep">◆</span>);});
  const track=[0,1].map(cp=>woven.map((n,i)=>React.cloneElement(n,{key:cp+'-'+i})));
  const dur=useTickerSpeed(trackRef,35,[feeds.items.length]);
  return <button onClick={()=>go('news')} aria-label="Open farming news" className="tkm" style={{flex:'0 0 auto',display:'flex',alignItems:'center',height:32,width:'100%',border:'none',padding:0,background:'var(--green-d)',color:'#e3ede7',overflow:'hidden',textAlign:'left'}}>
    <span style={{flex:'0 0 auto',display:'inline-flex',alignItems:'center',gap:5,background:'var(--gold)',color:'#fff',height:'100%',padding:'0 10px',fontSize:10,fontWeight:800,letterSpacing:'.08em',zIndex:2}}>NEWS</span>
    <span style={{flex:1,overflow:'hidden',position:'relative',height:'100%',display:'flex',alignItems:'center'}}><span ref={trackRef} className="tkm-track" style={{animationDuration:dur+'s'}}>{track}</span></span>
    <style>{`.tkm-track{display:inline-flex;align-items:center;white-space:nowrap;will-change:transform;animation:tkmmove 90s linear infinite}.tkm:active .tkm-track{animation-play-state:paused}@keyframes tkmmove{from{transform:translateX(0)}to{transform:translateX(-50%)}}@media(prefers-reduced-motion:reduce){.tkm-track{animation:none}}.tkm-item{display:inline-flex;align-items:center;gap:5px;padding:0 12px;font-size:12.5px;flex:0 0 auto}.tkm-item b{color:#fff;font-weight:700}.tkm-src{font-size:10px;letter-spacing:.06em;color:var(--gold-l)!important;margin-right:2px}.tkm-src-fao{color:#9fd7ff!important}.tkm-src-fewsnet{color:#ffd28a!important}.tkm-sep{flex:0 0 auto;color:rgba(255,255,255,.28);font-size:7px}`}</style>
  </button>;
}

/* ---------- bottom navigation (Material 3) ---------- */
const NAV_ITEMS=[
  {id:'home',   label:'Grow',    icon:'sprout'},
  {id:'market', label:'Market',  icon:'chart'},
  {id:'weather',label:'Weather & Risk', icon:'cloud'},
];
function BottomNav({page, go}){
  const cur = page==='report' ? 'home' : (page==='rain'||page==='elnino') ? 'weather' : page;
  return <div style={{flex:'0 0 auto',display:'flex',alignItems:'stretch',justifyContent:'space-around',height:74,
    background:'var(--paper)',borderTop:'1px solid var(--line)',paddingTop:6,zIndex:40}}>
    {NAV_ITEMS.map(it=>{
      const on=cur===it.id;
      return <button key={it.id} onClick={()=>go(it.id)} style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',gap:4,
        border:'none',background:'transparent',cursor:'pointer',padding:'2px 0'}}>
        <span style={{width:60,height:30,borderRadius:999,display:'grid',placeItems:'center',transition:'.18s',
          background:on?'rgba(46,125,79,.16)':'transparent',color:on?'var(--green-d)':'var(--ink-faint)'}}>
          <Icon name={it.icon} size={23} sw={on?2.1:1.8} fill={on?'rgba(46,125,79,.12)':'none'}/>
        </span>
        <span style={{fontSize:11.5,fontWeight:on?800:600,color:on?'var(--green-d)':'var(--ink-faint)',letterSpacing:'.01em'}}>{it.label}</span>
      </button>;
    })}
  </div>;
}

/* ---------- the device frame ---------- */
const LIMA_NATIVE = /[?&]native\b/.test(location.search) || window.LIMA_NATIVE || (window.innerWidth<600 && matchMedia('(pointer:coarse)').matches);
function Frame({children, statusDark}){
  if(LIMA_NATIVE) return <div style={{position:'fixed',inset:0,background:'var(--cream)',display:'flex',flexDirection:'column',paddingTop:'env(safe-area-inset-top)',paddingBottom:'env(safe-area-inset-bottom)'}}>{children}</div>;
  return (
    <div style={{width:412,height:892,borderRadius:46,overflow:'hidden',position:'relative',
      background:'var(--cream)',border:'11px solid #14130f',
      boxShadow:'0 40px 90px rgba(20,28,24,.4), 0 0 0 2px rgba(255,255,255,.06) inset',
      display:'flex',flexDirection:'column'}}>
      {children}
    </div>
  );
}

/* ---------- scaling stage (fits any viewport, letterboxes) ---------- */
function DeviceStage({children}){
  if(LIMA_NATIVE) return children;
  const ref=useRef(null);
  const [scale,setScale]=useState(1);
  useEffect(()=>{
    const fit=()=>{
      const pad=40;
      const sw=(window.innerWidth-pad)/412;
      const sh=(window.innerHeight-pad)/892;
      setScale(Math.min(1.05, Math.min(sw,sh)));
    };
    fit(); window.addEventListener('resize',fit); return ()=>window.removeEventListener('resize',fit);
  },[]);
  return <div style={{position:'fixed',inset:0,background:'radial-gradient(circle at 50% 30%, #2c3a31, #15201a 70%)',display:'grid',placeItems:'center',overflow:'hidden'}}>
    <div ref={ref} style={{transform:`scale(${scale})`,transformOrigin:'center center'}}>{children}</div>
  </div>;
}

Object.assign(window, { LIMA_NATIVE, StatusBar, AppBar, BottomNav, NewsTickerM, Frame, DeviceStage, NAV_ITEMS, iconBtn });
