/* ============================================================
   Lima Android — SMS alerts: coming-soon (default) or two-step signup
   ============================================================ */
const SMS_CONSENT='By subscribing you agree to receive Ku-Lima SMS alerts about rain and weather on this number. Messages come from sender ID “Ku-Lima” on Airtel and MTN. Reply STOP at any time. Standard SMS rates may apply. Alerts are automated advice, not official warnings.';

function CodeInput({value,onChange}){
  return <input value={value} onChange={e=>onChange(e.target.value.replace(/\D/g,'').slice(0,6))} inputMode="numeric" autoComplete="one-time-code" maxLength={6} placeholder="••••••" aria-label="6-digit code"
    className="mono" style={{...inp,fontSize:26,letterSpacing:'.35em',textAlign:'center',fontWeight:700,padding:'14px 10px'}}/>;
}

function AlertsScreen({prov, defaultProvince}){
  const [step,setStep]=useState('form'); // form | code | done
  const [phone,setPhone]=useState('');
  const [p,setP]=useState(defaultProvince||prov||'');
  const [crop,setCrop]=useState('');
  const [code,setCode]=useState('');
  const [err,setErr]=useState('');
  const [busy,setBusy]=useState(false);
  const [wait,setWait]=useState(0);
  const [provOpen,setProvOpen]=useState(false);
  const [cropOpen,setCropOpen]=useState(false);
  const valid=/^(0|\+?26)?\d{8,10}$/.test(phone.replace(/\s/g,''));
  const selCrop=crop?cropByName(crop):null;
  const normPhone=()=>{const n=phone.replace(/\D/g,'');return '+260'+n.replace(/^(260|0)/,'');};
  useEffect(()=>{ if(wait<=0) return; const t=setTimeout(()=>setWait(w=>w-1),1000); return ()=>clearTimeout(t); },[wait]);

  const requestCode=()=>{
    if(!valid){setErr('Enter a valid Zambian number, e.g. 097 123 4567');return;}
    if(!p){setErr('Please choose your province');return;}
    setErr(''); setBusy(true);
    setTimeout(()=>{ setBusy(false); setStep('code'); setCode(''); setWait(60); },600); // prototype: stands in for POST /sms → 202
  };
  const verify=()=>{
    if(!/^\d{6}$/.test(code)){setErr('Enter the 6-digit code we sent you.');return;}
    setErr(''); setBusy(true);
    setTimeout(()=>{ setBusy(false); if(code==='000000'){setErr('That code is not valid or has expired. Please request a new one.');return;} setStep('done'); },600); // prototype: POST /sms/verify
  };

  const Hero=({title,sub,icon='phone'})=><div style={{position:'relative',overflow:'hidden',borderRadius:22,padding:'22px',color:'#fff',background:'linear-gradient(150deg,var(--green-l),var(--green-d))',marginTop:2}}>
    <div style={{position:'absolute',top:-30,right:-20,width:140,height:140,borderRadius:'50%',background:'radial-gradient(circle,rgba(201,151,43,.3),transparent 70%)'}}></div>
    <div style={{position:'relative',display:'flex',alignItems:'center',gap:13}}>
      <span style={{width:48,height:48,borderRadius:13,background:'rgba(255,255,255,.18)',display:'grid',placeItems:'center',flex:'0 0 auto'}}><Icon name={icon} size={24}/></span>
      <div><h2 className="serif" style={{margin:0,fontSize:21,fontWeight:800}}>{title}</h2><p style={{margin:'3px 0 0',fontSize:13,opacity:.92,lineHeight:1.4}}>{sub}</p></div>
    </div>
  </div>;
  const Planned=()=><React.Fragment>
    <div style={{marginTop:20,padding:'0 2px 10px'}}><h3 className="serif" style={{margin:0,fontSize:17,fontWeight:700}}>What you'll get</h3></div>
    <div style={{display:'flex',flexDirection:'column',gap:10}}>
      {[['rain','Heavy-rain alerts','When 20 mm+ per day is forecast for your province','navy'],
        ['sun','Dry-spell alerts','When 5+ dry days are forecast during the season','gold']].map(([ic,t,d,tone],i)=>{
        const cm={gold:'var(--gold-d)',navy:'var(--navy)'}[tone], bm={gold:'rgba(201,151,43,.14)',navy:'rgba(27,58,107,.1)'}[tone];
        return <div key={i} style={{display:'flex',alignItems:'center',gap:13,padding:'13px 15px',borderRadius:16,background:'var(--paper)',border:'1px solid var(--line)'}}>
          <span style={{width:40,height:40,borderRadius:11,background:bm,color:cm,display:'grid',placeItems:'center',flex:'0 0 auto'}}><Icon name={ic} size={20}/></span>
          <div><div style={{fontWeight:700,fontSize:14}}>{t}</div><div style={{fontSize:12.5,color:'var(--ink-soft)',marginTop:2,lineHeight:1.4}}>{d}</div></div>
        </div>;})}
    </div>
    <SenderCard/>
    <p style={{margin:'14px 2px 0',fontSize:11.5,color:'var(--ink-faint)',lineHeight:1.5}}>Alerts are based on MET Norway forecasts and are automated advice, not official warnings. Ku-Lima is a free public service operated by Akili Ventures Limited.</p>
  </React.Fragment>;
  const SenderCard=()=><div style={{marginTop:12,display:'flex',flexDirection:'column',gap:10}}>
    <div style={{display:'flex',alignItems:'center',gap:13,padding:'13px 15px',borderRadius:16,background:'var(--paper)',border:'1px solid var(--line)'}}>
      <span style={{width:40,height:40,borderRadius:11,background:'rgba(46,125,79,.12)',color:'var(--green-d)',display:'grid',placeItems:'center',flex:'0 0 auto'}}><Icon name="shield" size={20}/></span>
      <div style={{flex:1,minWidth:0}}>
        <div style={{display:'flex',alignItems:'center',gap:8,flexWrap:'wrap'}}><span style={{fontWeight:700,fontSize:14}}>Texts come from “{SMS_SENDER}”</span><LiveDot/></div>
        <div style={{fontSize:12.5,color:'var(--ink-soft)',marginTop:2,lineHeight:1.4}}>Registered sender ID on Airtel and MTN Zambia. Ignore alerts from any other name.</div>
      </div>
    </div>
    <div style={{display:'flex',alignItems:'center',gap:13,padding:'13px 15px',borderRadius:16,background:'var(--paper)',border:'1px solid var(--line)'}}>
      <span style={{width:40,height:40,borderRadius:11,background:'rgba(201,151,43,.14)',color:'var(--gold-d)',display:'grid',placeItems:'center',flex:'0 0 auto'}}><Icon name="phone" size={20}/></span>
      <div style={{flex:1,minWidth:0}}>
        <div style={{display:'flex',alignItems:'center',gap:8,flexWrap:'wrap'}}><span style={{fontWeight:700,fontSize:14}}>USSD access</span><LiveDot soon label="Launching soon"/></div>
        <div style={{fontSize:12.5,color:'var(--ink-soft)',marginTop:2,lineHeight:1.4}}>Soon you’ll reach Ku-Lima by dialling a short code on any phone — no internet needed.</div>
      </div>
    </div>
  </div>;

  if(!D.sms_enabled) return <div className="screen-pad">
    <Hero title="SMS alerts are coming soon" sub="Rain and dry-spell alerts for your province, on any phone. Check the Rain tab in the meantime." icon="bell"/>
    <Planned/>
  </div>;

  if(step==='done') return <div className="screen-pad" style={{display:'flex',flexDirection:'column',minHeight:'100%'}}>
    <div style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',textAlign:'center',padding:'30px 10px'}}>
      <div style={{width:74,height:74,borderRadius:'50%',background:'rgba(46,125,79,.13)',color:'var(--green)',display:'grid',placeItems:'center',marginBottom:18}}><Icon name="check" size={40} sw={2.4}/></div>
      <h2 className="serif" style={{margin:'0 0 10px',fontSize:24,fontWeight:800}}>You're subscribed.</h2>
      <p style={{margin:0,maxWidth:300,color:'var(--ink-soft)',fontSize:14.5,lineHeight:1.55}}>“{SMS_SENDER}” will text <strong>{normPhone()}</strong> if heavy rain or a dry spell is forecast for <strong>{p}</strong>{selCrop&&<span> ({selCrop.name})</span>}.</p>
      <div style={{marginTop:22,width:'100%',maxWidth:300}}><MButton tone="outline" full onClick={()=>{setStep('form');setCode('');}}>Change details</MButton></div>
    </div>
  </div>;

  if(step==='code') return <div className="screen-pad">
    <Hero title="Enter your code" sub={`We sent a 6-digit code to ${normPhone()}. It expires in 10 minutes.`} icon="phone"/>
    <div style={{marginTop:16,display:'flex',flexDirection:'column',gap:14}}>
      <div><label style={lbl}><Icon name="shield" size={14}/> Verification code</label><CodeInput value={code} onChange={v=>{setCode(v);setErr('');}}/></div>
      {err && <p role="alert" style={{color:'var(--clay)',fontSize:13,fontWeight:600,margin:0}}>{err}</p>}
      <MButton onClick={verify} tone="green" size="lg" full disabled={busy||code.length<6}>{busy?'Checking…':'Confirm'}</MButton>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:10}}>
        <button onClick={()=>{setStep('form');setErr('');}} style={{border:'none',background:'transparent',color:'var(--green-d)',fontWeight:700,fontSize:13.5,padding:'8px 2px'}}>Change number</button>
        <button onClick={()=>{if(wait>0)return;requestCode();}} disabled={wait>0} style={{border:'none',background:'transparent',color:wait>0?'var(--ink-faint)':'var(--green-d)',fontWeight:700,fontSize:13.5,padding:'8px 2px',cursor:wait>0?'default':'pointer'}}>{wait>0?`Resend code in ${wait}s`:'Resend code'}</button>
      </div>
      <p style={{textAlign:'center',margin:0,fontSize:11.5,color:'var(--ink-faint)'}}>5 attempts per code. Wrong or expired codes: request a new one.</p>
    </div>
  </div>;

  return <div className="screen-pad">
    <Hero title="Free SMS rain alerts" sub="Heavy-rain and dry-spell alerts for your province — on any Airtel or MTN phone, from “Ku-Lima”."/>
    <div style={{marginTop:16,display:'flex',flexDirection:'column',gap:14}}>
      <div>
        <label style={lbl} htmlFor="sms-phone"><Icon name="phone" size={14}/> Mobile number</label>
        <input id="sms-phone" value={phone} onChange={e=>{setPhone(e.target.value);setErr('');}} inputMode="tel" autoComplete="tel" placeholder="097 123 4567" style={inp}/>
      </div>
      <div>
        <label style={lbl}><Icon name="pin" size={14}/> Province</label>
        <button onClick={()=>setProvOpen(true)} style={{...inp,display:'flex',alignItems:'center',justifyContent:'space-between',textAlign:'left',cursor:'pointer'}}>
          <span style={{color:p?'var(--ink)':'var(--ink-faint)',fontWeight:p?700:400}}>{p||'Choose your province'}</span><Icon name="chev" size={18} style={{color:'var(--ink-faint)'}}/>
        </button>
      </div>
      <div>
        <label style={lbl}><Icon name="leaf" size={14}/> Crop <span style={{fontWeight:500,color:'var(--ink-faint)',textTransform:'none',letterSpacing:0}}>· optional</span></label>
        <button onClick={()=>setCropOpen(true)} style={{...inp,display:'flex',alignItems:'center',justifyContent:'space-between',textAlign:'left',cursor:'pointer'}}>
          <span style={{display:'flex',alignItems:'center',gap:9,color:selCrop?'var(--ink)':'var(--ink-faint)',fontWeight:selCrop?700:400}}>{selCrop&&<span style={{fontSize:20}}>{selCrop.emoji}</span>}{selCrop?selCrop.name:'All crops in my area'}</span><Icon name="chev" size={18} style={{color:'var(--ink-faint)'}}/>
        </button>
      </div>
      <div style={{height:66,borderRadius:12,border:'1px dashed var(--line-d)',background:'var(--cream-2)',display:'grid',placeItems:'center'}}><span className="mono" style={{fontSize:11,color:'var(--ink-faint)',letterSpacing:'.04em',textTransform:'uppercase'}}>Security check (Turnstile)</span></div>
      {err && <p role="alert" style={{color:'var(--clay)',fontSize:13,fontWeight:600,margin:0}}>{err}</p>}
      <p style={{margin:0,fontSize:11.5,color:'var(--ink-soft)',lineHeight:1.5}}>{SMS_CONSENT}</p>
      <MButton onClick={requestCode} tone="green" size="lg" full disabled={busy}>{busy?'Sending…':'Send me a code'}</MButton>
    </div>
    <Planned/>
    <ProvincePickerSheet open={provOpen} onClose={()=>setProvOpen(false)} value={p} onChange={setP}/>
    <CropPickerSheet open={cropOpen} onClose={()=>setCropOpen(false)} value={crop} onChange={setCrop}/>
  </div>;
}
const lbl={display:'flex',alignItems:'center',gap:6,fontSize:11.5,fontWeight:800,color:'var(--ink-soft)',marginBottom:8,letterSpacing:'.04em',textTransform:'uppercase',whiteSpace:'nowrap'};
const inp={width:'100%',padding:'14px 15px',borderRadius:14,border:'1.5px solid var(--line-d)',fontSize:16,background:'var(--paper)',outline:'none',fontFamily:'inherit',color:'var(--ink)'};

Object.assign(window, { AlertsScreen });
