// Farmer.jsx — Pamoja dMRV Farmer portal (mobile-first)
// One household, one stove card, traffic-light status, plain-language prompts.
// Trilingual: Kinyarwanda (rw) / Kiswahili (sw) / English (en). Default rw.

const FARMER_C = {
  bg: '#F6F8F7',
  ink: '#022C28',
  paper: '#FFFFFF',
  line: '#E5E7EB',
  mute: '#6B7280',
  faint: '#9CA3AF',
  forest: '#022C28',
  gold: '#F4C300',
  green: '#2BC48A',
  greenDeep: '#0E8C5A',
  amber: '#F59E0B',
  red: '#DC2626',
  paperWarm: '#FBF9F2',
};

// ─── Strings ──────────────────────────────────────────────────────
const S = {
  rw: {
    greeting: 'Mwaramutse, Marie', sub: 'Imbabura yawe yiteguye',
    myStove: 'Imbabura yanjye', household: 'Urugo 0421 · Rwamagana',
    statusGood: 'Byose biri neza',
    lastVisit: 'Uruzinduko ruheruka', daysAgo: 'iminsi 12 ishize',
    nextVisit: 'Uruzinduko rukurikira', inDays: 'mu minsi 18',
    quickCheck: 'Subiza ibibazo 3 by\u2019uyu munsi',
    q1: 'Wakoresheje imbabura uyu munsi?',
    q2: 'Yashyushye neza?',
    q3: 'Hari ibibazo?',
    yes: 'Yego', no: 'Oya', notSure: 'Sinzi',
    submit: 'Ohereza',
    photo: 'Ohereza ifoto', photoSub: 'Igikoni · imbabura igaragara',
    problem: 'Mvuga ikibazo', problemSub: 'Niba imbabura idakora',
    history: 'Amateka', historySub: 'Reba uruzinduko n\u2019ibyabaye',
    settings: 'Igenamiterere', signedTamper: 'Byanditse · bishyizweho umukono',
    welcome: 'Murakaza neza', languagePick: 'Hitamo ururimi',
    learnMore: 'Iyi mbabura igabanya isuri', learnSub: 'Niba ukoresha buri munsi, ufasha ishyamba.',
    syncOk: 'Byohererejwe · 09:42', syncOffline: 'Nta murongo · bizohererezwa nyuma',
    appName: 'Pamoja Imbabura',
    creditsThis: 'Iki gihembwe', credits: 'Tani 0.18 CO\u2082e', creditsNote: 'Ufashe ishyamba',
    today: 'Uyu munsi', period: 'Iki gihembwe', visits: 'uruzinduko',
    reportTitle: 'Mvuga ikibazo', whatHappened: 'Ni iki kibaye?',
    optSmoke: 'Umwotsi mwinshi', optBroken: 'Yangiritse', optHot: 'Iratwika cyane', optOther: 'Ikindi',
    send: 'Ohereza', cancel: 'Hagarika',
    voiceHint: 'Cyangwa kanda kuvuga',
    consent: 'Amakuru yanjye ni ayanjye. Pamoja iyakoresha kuva 2024.',
  },
  sw: {
    greeting: 'Habari, Marie', sub: 'Jiko lako liko tayari',
    myStove: 'Jiko langu', household: 'Kaya 0421 · Rwamagana',
    statusGood: 'Yote ni sawa',
    lastVisit: 'Ziara ya mwisho', daysAgo: 'siku 12 zilizopita',
    nextVisit: 'Ziara ijayo', inDays: 'baada ya siku 18',
    quickCheck: 'Jibu maswali 3 ya leo',
    q1: 'Umetumia jiko leo?',
    q2: 'Lilipata moto vizuri?',
    q3: 'Kuna shida yoyote?',
    yes: 'Ndiyo', no: 'Hapana', notSure: 'Sijui',
    submit: 'Tuma',
    photo: 'Tuma picha', photoSub: 'Jikoni · jiko linaonekana',
    problem: 'Ripoti tatizo', problemSub: 'Ikiwa jiko halifanyi kazi',
    history: 'Historia', historySub: 'Tazama ziara na matukio',
    settings: 'Mipangilio', signedTamper: 'Imesainiwa · salama',
    welcome: 'Karibu', languagePick: 'Chagua lugha',
    learnMore: 'Jiko hili linapunguza ukataji', learnSub: 'Ukilitumia kila siku, unasaidia msitu.',
    syncOk: 'Imetumwa · 09:42', syncOffline: 'Hakuna mtandao · itatumwa baadaye',
    appName: 'Pamoja Jiko',
    creditsThis: 'Kipindi hiki', credits: 'Tani 0.18 CO\u2082e', creditsNote: 'Umesaidia msitu',
    today: 'Leo', period: 'Kipindi hiki', visits: 'ziara',
    reportTitle: 'Ripoti tatizo', whatHappened: 'Nini kimetokea?',
    optSmoke: 'Moshi mwingi', optBroken: 'Imevunjika', optHot: 'Inawaka sana', optOther: 'Nyingine',
    send: 'Tuma', cancel: 'Ghairi',
    voiceHint: 'Au bonyeza kusema',
    consent: 'Data yangu ni yangu. Pamoja inaitumia tangu 2024.',
  },
  en: {
    greeting: 'Good morning, Marie', sub: 'Your stove is ready',
    myStove: 'My stove', household: 'Household 0421 · Rwamagana',
    statusGood: 'Everything looks good',
    lastVisit: 'Last visit', daysAgo: '12 days ago',
    nextVisit: 'Next visit', inDays: 'in 18 days',
    quickCheck: 'Answer 3 quick questions',
    q1: 'Did you use the stove today?',
    q2: 'Did it heat well?',
    q3: 'Any problems?',
    yes: 'Yes', no: 'No', notSure: 'Not sure',
    submit: 'Send',
    photo: 'Send a photo', photoSub: 'Kitchen · stove visible',
    problem: 'Report a problem', problemSub: 'If the stove isn\u2019t working',
    history: 'History', historySub: 'See visits and events',
    settings: 'Settings', signedTamper: 'Signed · tamper-evident',
    welcome: 'Welcome', languagePick: 'Pick a language',
    learnMore: 'This stove reduces deforestation', learnSub: 'When you use it daily, you help the forest.',
    syncOk: 'Sent · 09:42', syncOffline: 'No signal · will send later',
    appName: 'Pamoja Stove',
    creditsThis: 'This period', credits: '0.18 t CO\u2082e', creditsNote: 'You helped the forest',
    today: 'Today', period: 'This period', visits: 'visits',
    reportTitle: 'Report a problem', whatHappened: 'What\u2019s happening?',
    optSmoke: 'Too much smoke', optBroken: 'Broken', optHot: 'Burns too hot', optOther: 'Something else',
    send: 'Send', cancel: 'Cancel',
    voiceHint: 'Or tap to speak',
    consent: 'My data is mine. Pamoja has used it since 2024.',
  },
};

// ─── Shared chrome ────────────────────────────────────────────────
function StatusBar() {
  return (
    <div style={{height:34, background:FARMER_C.forest, color:'#fff', display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 18px', fontSize:13, fontWeight:500, fontFamily:'Roboto, system-ui, sans-serif'}}>
      <span>09:42</span>
      <span style={{display:'inline-flex',gap:6,alignItems:'center'}}>
        <svg width="13" height="13" viewBox="0 0 16 16"><path d="M8 13.3L.67 5.97a10.37 10.37 0 0114.66 0L8 13.3z" fill="#fff" opacity="0.4"/></svg>
        <svg width="13" height="13" viewBox="0 0 16 16"><path d="M14.67 14.67V1.33L1.33 14.67h13.34z" fill="#fff"/></svg>
        <span style={{fontSize:11,opacity:0.85}}>62%</span>
        <svg width="14" height="14" viewBox="0 0 16 16"><rect x="3.75" y="2" width="8.5" height="13" rx="1.5" fill="#fff"/></svg>
      </span>
    </div>
  );
}

function NavPill() {
  return (
    <div style={{height:18,background:'#fff',display:'flex',alignItems:'center',justifyContent:'center'}}>
      <div style={{width:108,height:4,borderRadius:2,background:FARMER_C.forest,opacity:0.3}}/>
    </div>
  );
}

// Stove illustration — simple line drawing (no emoji, no clip-art)
function StoveGlyph({size=68, status='good'}) {
  const ring = status==='good' ? FARMER_C.green : status==='warn' ? FARMER_C.amber : FARMER_C.red;
  return (
    <svg width={size} height={size} viewBox="0 0 80 80" fill="none">
      <circle cx="40" cy="40" r="38" fill="#fff" stroke={ring} strokeWidth="3"/>
      {/* stove body */}
      <rect x="22" y="36" width="36" height="26" rx="3" fill={FARMER_C.forest}/>
      <rect x="26" y="40" width="28" height="14" rx="2" fill={FARMER_C.gold}/>
      {/* flame */}
      <path d="M40 24 C 36 30, 34 34, 36 38 C 38 36, 39 34, 40 32 C 41 35, 43 37, 44 38 C 46 34, 44 30, 40 24 Z" fill={FARMER_C.gold}/>
      {/* legs */}
      <rect x="24" y="62" width="3" height="6" fill={FARMER_C.forest}/>
      <rect x="53" y="62" width="3" height="6" fill={FARMER_C.forest}/>
    </svg>
  );
}

// Traffic-light dot
function StatusDot({color, size=10}) {
  return <span style={{width:size,height:size,borderRadius:'50%',background:color,display:'inline-block'}}/>;
}

// ─── Language picker (welcome screen) ─────────────────────────────
function LanguagePicker({onPick}) {
  const langs = [
    {code:'rw', name:'Kinyarwanda', greeting:'Murakaza neza'},
    {code:'sw', name:'Kiswahili', greeting:'Karibu'},
    {code:'en', name:'English', greeting:'Welcome'},
  ];
  return (
    <div style={{padding:'40px 24px 24px',display:'flex',flexDirection:'column',height:'100%',background:FARMER_C.paperWarm}}>
      <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:36}}>
        <img src="../../assets/logo-mark.svg" alt="" style={{height:28}}/>
        <div style={{fontSize:14,fontWeight:800,color:FARMER_C.forest,letterSpacing:'-0.01em'}}>Pamoja</div>
      </div>
      <div style={{fontSize:28,fontWeight:900,color:FARMER_C.forest,letterSpacing:'-0.02em',lineHeight:1.15,marginBottom:6}}>Hitamo ururimi</div>
      <div style={{fontSize:14,color:FARMER_C.mute,marginBottom:32}}>Choose a language · Chagua lugha</div>
      <div style={{display:'flex',flexDirection:'column',gap:12}}>
        {langs.map(l => (
          <button key={l.code} onClick={()=>onPick(l.code)} style={{
            background:'#fff', border:`1px solid ${FARMER_C.line}`, borderRadius:14,
            padding:'18px 20px', textAlign:'left', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'space-between',
          }}>
            <div>
              <div style={{fontSize:18,fontWeight:800,color:FARMER_C.forest,letterSpacing:'-0.01em'}}>{l.greeting}</div>
              <div style={{fontSize:13,color:FARMER_C.mute,marginTop:2}}>{l.name}</div>
            </div>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={FARMER_C.forest} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
          </button>
        ))}
      </div>
      <div style={{marginTop:'auto',fontSize:11,color:FARMER_C.faint,fontFamily:"'JetBrains Mono', monospace",letterSpacing:'0.02em',textAlign:'center'}}>
        pamojadmrv.earth · Household v0.4.0-beta
      </div>
    </div>
  );
}

// ─── Top app bar (home) ───────────────────────────────────────────
function TopBar({t, lang, onLang}) {
  const [open, setOpen] = React.useState(false);
  const langName = lang==='rw' ? 'RW' : lang==='sw' ? 'SW' : 'EN';
  return (
    <div style={{padding:'14px 18px 10px',background:FARMER_C.paperWarm,position:'relative'}}>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
        <div style={{display:'flex',alignItems:'center',gap:10}}>
          <img src="../../assets/logo-mark.svg" alt="" style={{height:24}}/>
          <div style={{fontSize:13,fontWeight:800,color:FARMER_C.forest,letterSpacing:'-0.01em'}}>{t.appName}</div>
        </div>
        <button onClick={()=>setOpen(!open)} style={{
          background:'#fff',border:`1px solid ${FARMER_C.line}`,borderRadius:999,padding:'5px 11px',
          fontSize:12,fontWeight:700,color:FARMER_C.forest,fontFamily:"'JetBrains Mono', monospace",cursor:'pointer',
          display:'inline-flex',alignItems:'center',gap:6,
        }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={FARMER_C.forest} strokeWidth="2"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18"/></svg>
          {langName}
        </button>
      </div>
      {open && (
        <div style={{position:'absolute',right:18,top:48,zIndex:10,background:'#fff',border:`1px solid ${FARMER_C.line}`,borderRadius:10,boxShadow:'0 12px 28px rgba(2,44,40,0.18)',overflow:'hidden',minWidth:160}}>
          {[['rw','Kinyarwanda'],['sw','Kiswahili'],['en','English']].map(([code,name]) => (
            <button key={code} onClick={()=>{onLang(code); setOpen(false);}} style={{
              display:'block',width:'100%',textAlign:'left',padding:'12px 14px',background:lang===code?FARMER_C.paperWarm:'#fff',
              border:'none',borderBottom:`1px solid ${FARMER_C.line}`,fontSize:13,fontWeight:lang===code?800:600,color:FARMER_C.forest,cursor:'pointer',
            }}>{name}</button>
          ))}
        </div>
      )}
      <div style={{marginTop:14,fontSize:22,fontWeight:900,color:FARMER_C.forest,letterSpacing:'-0.02em',lineHeight:1.15}}>{t.greeting}</div>
      <div style={{fontSize:13,color:FARMER_C.mute,marginTop:2}}>{t.sub}</div>
    </div>
  );
}

// ─── Home screen ──────────────────────────────────────────────────
function Home({t, onOpen}) {
  return (
    <div style={{padding:'4px 16px 24px',display:'flex',flexDirection:'column',gap:14}}>
      {/* Stove card — hero */}
      <div style={{
        background:'#fff', borderRadius:18, padding:'18px 18px 18px',
        border:`1px solid ${FARMER_C.line}`, boxShadow:'0 1px 0 rgba(2,44,40,0.04)',
      }}>
        <div style={{display:'flex',alignItems:'center',gap:14}}>
          <StoveGlyph status="good"/>
          <div style={{flex:1,minWidth:0}}>
            <div style={{fontSize:11,fontWeight:800,letterSpacing:'0.12em',color:FARMER_C.greenDeep,textTransform:'uppercase',fontFamily:"'JetBrains Mono', monospace"}}>{t.myStove}</div>
            <div style={{fontSize:18,fontWeight:900,color:FARMER_C.forest,letterSpacing:'-0.015em',marginTop:2,lineHeight:1.2}}>{t.statusGood}</div>
            <div style={{fontSize:12,color:FARMER_C.mute,marginTop:3}}>{t.household}</div>
          </div>
        </div>
      </div>

      {/* Quick check tile */}
      <button onClick={()=>onOpen('check')} style={{
        background:FARMER_C.forest,color:'#fff',border:'none',borderRadius:18,padding:'18px 20px',
        textAlign:'left',cursor:'pointer',display:'flex',alignItems:'center',gap:14,
      }}>
        <div style={{flex:1}}>
          <div style={{fontSize:11,fontWeight:800,letterSpacing:'0.12em',color:FARMER_C.gold,textTransform:'uppercase',fontFamily:"'JetBrains Mono', monospace"}}>3 · 1 min</div>
          <div style={{fontSize:17,fontWeight:900,letterSpacing:'-0.015em',marginTop:4,lineHeight:1.2}}>{t.quickCheck}</div>
        </div>
        <div style={{width:38,height:38,borderRadius:'50%',background:FARMER_C.gold,display:'flex',alignItems:'center',justifyContent:'center'}}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={FARMER_C.forest} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
        </div>
      </button>

      {/* Credits card */}
      <div style={{background:FARMER_C.paperWarm,border:`1px solid ${FARMER_C.line}`,borderRadius:14,padding:'14px 16px',display:'flex',alignItems:'center',gap:14}}>
        <div style={{width:44,height:44,borderRadius:12,background:'#fff',border:`1px solid ${FARMER_C.line}`,display:'flex',alignItems:'center',justifyContent:'center'}}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={FARMER_C.greenDeep} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2L4 5v6c0 5 3.4 9.4 8 11 4.6-1.6 8-6 8-11V5l-8-3z"/><polyline points="9 12 11 14 15 10"/></svg>
        </div>
        <div style={{flex:1,minWidth:0}}>
          <div style={{fontSize:11,fontWeight:700,letterSpacing:'0.08em',color:FARMER_C.mute,textTransform:'uppercase',fontFamily:"'JetBrains Mono', monospace"}}>{t.creditsThis}</div>
          <div style={{fontSize:17,fontWeight:900,color:FARMER_C.forest,letterSpacing:'-0.015em',marginTop:2}}>{t.credits}</div>
          <div style={{fontSize:12,color:FARMER_C.mute,marginTop:1}}>{t.creditsNote}</div>
        </div>
      </div>

      {/* Action tiles */}
      <ActionTile onClick={()=>onOpen('photo')} title={t.photo} sub={t.photoSub} icon={
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={FARMER_C.forest} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"/><circle cx="12" cy="13" r="4"/></svg>
      }/>
      <ActionTile onClick={()=>onOpen('problem')} title={t.problem} sub={t.problemSub} accent={FARMER_C.amber} icon={
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={FARMER_C.amber} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
      }/>
      <ActionTile onClick={()=>onOpen('history')} title={t.history} sub={t.historySub} icon={
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={FARMER_C.forest} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
      }/>

      {/* Learn / consent strip */}
      <div style={{marginTop:6,background:'#fff',border:`1px dashed ${FARMER_C.line}`,borderRadius:12,padding:'12px 14px'}}>
        <div style={{fontSize:13,fontWeight:800,color:FARMER_C.forest,letterSpacing:'-0.01em'}}>{t.learnMore}</div>
        <div style={{fontSize:12,color:FARMER_C.mute,marginTop:2,lineHeight:1.45}}>{t.learnSub}</div>
      </div>

      {/* Sync / tamper-evident footer */}
      <div style={{marginTop:4,display:'flex',alignItems:'center',justifyContent:'space-between',gap:10,padding:'10px 4px 0'}}>
        <div style={{display:'flex',alignItems:'center',gap:8}}>
          <StatusDot color={FARMER_C.green}/>
          <span style={{fontSize:11,fontFamily:"'JetBrains Mono', monospace",color:FARMER_C.mute,letterSpacing:'0.02em'}}>{t.syncOk}</span>
        </div>
        <span style={{fontSize:11,fontFamily:"'JetBrains Mono', monospace",color:FARMER_C.faint,letterSpacing:'0.02em'}}>{t.signedTamper}</span>
      </div>
    </div>
  );
}

function MiniStat({label, value, dot}) {
  return (
    <div style={{background:FARMER_C.paperWarm,borderRadius:10,padding:'9px 10px'}}>
      <div style={{display:'flex',alignItems:'center',gap:6}}>
        <StatusDot color={dot} size={8}/>
        <span style={{fontSize:10,fontWeight:700,letterSpacing:'0.06em',color:FARMER_C.mute,textTransform:'uppercase',fontFamily:"'JetBrains Mono', monospace"}}>{label}</span>
      </div>
      <div style={{fontSize:13,fontWeight:800,color:FARMER_C.forest,marginTop:3,letterSpacing:'-0.01em'}}>{value}</div>
    </div>
  );
}

function ActionTile({title, sub, icon, onClick, accent}) {
  return (
    <button onClick={onClick} style={{
      background:'#fff',border:`1px solid ${FARMER_C.line}`,borderRadius:14,
      padding:'14px 16px',textAlign:'left',cursor:'pointer',display:'flex',alignItems:'center',gap:14,width:'100%',
    }}>
      <div style={{width:42,height:42,borderRadius:12,background:FARMER_C.paperWarm,border:`1px solid ${FARMER_C.line}`,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
        {icon}
      </div>
      <div style={{flex:1,minWidth:0}}>
        <div style={{fontSize:15,fontWeight:800,color:accent||FARMER_C.forest,letterSpacing:'-0.01em'}}>{title}</div>
        <div style={{fontSize:12,color:FARMER_C.mute,marginTop:2}}>{sub}</div>
      </div>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={FARMER_C.faint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0}}><polyline points="9 18 15 12 9 6"/></svg>
    </button>
  );
}

// ─── Quick check (3 questions) ────────────────────────────────────
function QuickCheck({t, onBack}) {
  const [a, setA] = React.useState({});
  const qs = [
    {k:'q1', q:t.q1},
    {k:'q2', q:t.q2},
    {k:'q3', q:t.q3},
  ];
  const allAnswered = qs.every(q => a[q.k]);

  return (
    <div style={{padding:'14px 18px 24px'}}>
      <BackBar t={t} onBack={onBack} title={t.quickCheck}/>
      <div style={{display:'flex',flexDirection:'column',gap:14,marginTop:18}}>
        {qs.map((q, i) => (
          <div key={q.k} style={{background:'#fff',border:`1px solid ${FARMER_C.line}`,borderRadius:14,padding:'16px 18px'}}>
            <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:12}}>
              <div style={{width:24,height:24,borderRadius:'50%',background:FARMER_C.paperWarm,color:FARMER_C.forest,fontSize:12,fontWeight:800,display:'flex',alignItems:'center',justifyContent:'center',fontFamily:"'JetBrains Mono', monospace"}}>{i+1}</div>
              <div style={{fontSize:15,fontWeight:800,color:FARMER_C.forest,letterSpacing:'-0.01em'}}>{q.q}</div>
            </div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
              {[['yes',t.yes,FARMER_C.green],['no',t.no,FARMER_C.red]].map(([v,label,c]) => {
                const sel = a[q.k]===v;
                return (
                  <button key={v} onClick={()=>setA({...a,[q.k]:v})} style={{
                    padding:'10px 6px',borderRadius:10,
                    border:sel?`2px solid ${c}`:`1px solid ${FARMER_C.line}`,
                    background:sel?`${c}15`:'#fff',
                    color:sel?c:FARMER_C.ink,fontSize:13,fontWeight:sel?800:700,cursor:'pointer',
                  }}>{label}</button>
                );
              })}
            </div>
          </div>
        ))}
      </div>
      <button disabled={!allAnswered} onClick={onBack} style={{
        marginTop:20,width:'100%',background:allAnswered?FARMER_C.forest:FARMER_C.line,
        color:allAnswered?'#fff':FARMER_C.faint,border:'none',borderRadius:12,padding:'15px',
        fontSize:15,fontWeight:800,letterSpacing:'-0.01em',cursor:allAnswered?'pointer':'not-allowed',
      }}>{t.submit}</button>
      <div style={{marginTop:14,fontSize:11,color:FARMER_C.faint,fontFamily:"'JetBrains Mono', monospace",textAlign:'center',letterSpacing:'0.02em'}}>
        {t.voiceHint}
      </div>
    </div>
  );
}

// ─── Problem report ───────────────────────────────────────────────
function Problem({t, onBack}) {
  const [sel, setSel] = React.useState(null);
  const opts = [
    ['smoke', t.optSmoke, '#F59E0B'],
    ['broken', t.optBroken, '#DC2626'],
    ['hot', t.optHot, '#F59E0B'],
    ['other', t.optOther, '#6B7280'],
  ];
  return (
    <div style={{padding:'14px 18px 24px'}}>
      <BackBar t={t} onBack={onBack} title={t.reportTitle}/>
      <div style={{fontSize:13,color:FARMER_C.mute,marginTop:14,marginBottom:14}}>{t.whatHappened}</div>
      <div style={{display:'flex',flexDirection:'column',gap:10}}>
        {opts.map(([k,label,color]) => {
          const isSel = sel===k;
          return (
            <button key={k} onClick={()=>setSel(k)} style={{
              background:'#fff',border:isSel?`2px solid ${color}`:`1px solid ${FARMER_C.line}`,borderRadius:12,
              padding:'14px 16px',textAlign:'left',cursor:'pointer',display:'flex',alignItems:'center',gap:12,
            }}>
              <span style={{width:14,height:14,borderRadius:'50%',background:color,flexShrink:0}}/>
              <span style={{fontSize:15,fontWeight:isSel?800:700,color:FARMER_C.forest,letterSpacing:'-0.01em'}}>{label}</span>
            </button>
          );
        })}
      </div>
      {/* Voice hint */}
      <div style={{marginTop:18,background:FARMER_C.paperWarm,border:`1px dashed ${FARMER_C.line}`,borderRadius:12,padding:'12px 14px',display:'flex',alignItems:'center',gap:12}}>
        <div style={{width:36,height:36,borderRadius:'50%',background:'#fff',border:`1px solid ${FARMER_C.line}`,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={FARMER_C.forest} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3z"/><path d="M19 10v2a7 7 0 01-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/></svg>
        </div>
        <div style={{fontSize:12,color:FARMER_C.mute,lineHeight:1.4}}>{t.voiceHint}</div>
      </div>
      <div style={{display:'grid',gridTemplateColumns:'1fr 2fr',gap:10,marginTop:20}}>
        <button onClick={onBack} style={{background:'#fff',border:`1px solid ${FARMER_C.line}`,borderRadius:12,padding:'14px',fontSize:14,fontWeight:700,color:FARMER_C.forest,cursor:'pointer'}}>{t.cancel}</button>
        <button disabled={!sel} onClick={onBack} style={{
          background:sel?FARMER_C.forest:FARMER_C.line,color:sel?'#fff':FARMER_C.faint,border:'none',borderRadius:12,padding:'14px',
          fontSize:14,fontWeight:800,letterSpacing:'-0.01em',cursor:sel?'pointer':'not-allowed',
        }}>{t.send}</button>
      </div>
    </div>
  );
}

// ─── Photo capture ────────────────────────────────────────────────
function Photo({t, onBack}) {
  return (
    <div style={{padding:'14px 18px 24px'}}>
      <BackBar t={t} onBack={onBack} title={t.photo}/>
      <div style={{marginTop:16,borderRadius:16,overflow:'hidden',background:FARMER_C.forest,position:'relative',aspectRatio:'3/4'}}>
        {/* Mock viewfinder */}
        <div style={{position:'absolute',inset:0,background:'linear-gradient(180deg,#1a3d39 0%,#0e2825 100%)'}}/>
        {/* Stove silhouette */}
        <div style={{position:'absolute',left:'50%',top:'58%',transform:'translate(-50%,-50%)',opacity:0.45}}>
          <StoveGlyph size={140} status="good"/>
        </div>
        {/* Corner brackets */}
        {[['top',16,'left',16,'corner-tl'],['top',16,'right',16,'corner-tr'],['bottom',16,'left',16,'corner-bl'],['bottom',16,'right',16,'corner-br']].map(([y,yv,x,xv,k]) => (
          <div key={k} style={{position:'absolute',[y]:yv,[x]:xv,width:22,height:22,borderTop:y==='top'?`2px solid ${FARMER_C.gold}`:'none',borderBottom:y==='bottom'?`2px solid ${FARMER_C.gold}`:'none',borderLeft:x==='left'?`2px solid ${FARMER_C.gold}`:'none',borderRight:x==='right'?`2px solid ${FARMER_C.gold}`:'none'}}/>
        ))}
        {/* Hint top */}
        <div style={{position:'absolute',top:16,left:0,right:0,textAlign:'center',color:'#fff',fontSize:12,fontWeight:700,letterSpacing:'0.02em'}}>{t.photoSub}</div>
        {/* Shutter */}
        <div style={{position:'absolute',bottom:20,left:0,right:0,display:'flex',justifyContent:'center'}}>
          <div style={{width:64,height:64,borderRadius:'50%',background:'rgba(255,255,255,0.2)',border:'3px solid #fff',display:'flex',alignItems:'center',justifyContent:'center'}}>
            <div style={{width:50,height:50,borderRadius:'50%',background:FARMER_C.gold}}/>
          </div>
        </div>
      </div>
      <div style={{marginTop:14,background:FARMER_C.paperWarm,border:`1px solid ${FARMER_C.line}`,borderRadius:12,padding:'12px 14px',display:'flex',alignItems:'center',gap:10}}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={FARMER_C.greenDeep} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="8 12 11 15 16 9"/></svg>
        <span style={{fontSize:12,color:FARMER_C.mute,lineHeight:1.4}}>GPS · -1.948, 30.435 · 09:42</span>
      </div>
    </div>
  );
}

// ─── History ──────────────────────────────────────────────────────
function History({t, onBack}) {
  const items = [
    {date:'14 Apr', kind:'visit', label:t.lastVisit, who:'Joseph M.', tone:'good'},
    {date:'02 Apr', kind:'photo', label:t.photo, who:'Marie U.', tone:'good'},
    {date:'18 Mar', kind:'check', label:t.quickCheck, who:'Marie U.', tone:'good'},
    {date:'02 Mar', kind:'visit', label:t.lastVisit, who:'Joseph M.', tone:'good'},
    {date:'15 Feb', kind:'install', label:'Install', who:'Joseph M.', tone:'good'},
  ];
  return (
    <div style={{padding:'14px 18px 24px'}}>
      <BackBar t={t} onBack={onBack} title={t.history}/>
      <div style={{marginTop:14,background:'#fff',border:`1px solid ${FARMER_C.line}`,borderRadius:14,overflow:'hidden'}}>
        {items.map((it, i) => (
          <div key={i} style={{padding:'14px 16px',borderBottom:i<items.length-1?`1px solid ${FARMER_C.line}`:'none',display:'flex',alignItems:'center',gap:14}}>
            <div style={{width:42,textAlign:'center'}}>
              <div style={{fontSize:11,fontWeight:700,color:FARMER_C.mute,fontFamily:"'JetBrains Mono', monospace",letterSpacing:'0.04em'}}>{it.date.split(' ')[0]}</div>
              <div style={{fontSize:9,fontWeight:700,color:FARMER_C.faint,fontFamily:"'JetBrains Mono', monospace",letterSpacing:'0.06em',textTransform:'uppercase'}}>{it.date.split(' ')[1]}</div>
            </div>
            <div style={{width:1,alignSelf:'stretch',background:FARMER_C.line}}/>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:14,fontWeight:800,color:FARMER_C.forest,letterSpacing:'-0.01em'}}>{it.label}</div>
              <div style={{fontSize:12,color:FARMER_C.mute,marginTop:1}}>{it.who}</div>
            </div>
            <StatusDot color={FARMER_C.green}/>
          </div>
        ))}
      </div>
      <div style={{marginTop:14,fontSize:11,color:FARMER_C.faint,fontFamily:"'JetBrains Mono', monospace",textAlign:'center',letterSpacing:'0.02em',lineHeight:1.5,padding:'0 12px'}}>
        {t.consent}
      </div>
    </div>
  );
}

function BackBar({onBack, title}) {
  return (
    <div style={{display:'flex',alignItems:'center',gap:12}}>
      <button onClick={onBack} style={{background:'#fff',border:`1px solid ${FARMER_C.line}`,borderRadius:'50%',width:36,height:36,cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',padding:0}}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={FARMER_C.forest} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
      </button>
      <div style={{fontSize:18,fontWeight:900,color:FARMER_C.forest,letterSpacing:'-0.02em'}}>{title}</div>
    </div>
  );
}

// ─── App shell ────────────────────────────────────────────────────
function FarmerApp() {
  const [lang, setLang] = React.useState(null); // null = show language picker
  const [view, setView] = React.useState('home');
  const t = lang ? S[lang] : S.rw;

  let body;
  if (!lang) {
    body = <LanguagePicker onPick={setLang}/>;
  } else if (view === 'home') {
    body = (
      <>
        <TopBar t={t} lang={lang} onLang={setLang}/>
        <Home t={t} onOpen={setView}/>
      </>
    );
  } else if (view === 'check') {
    body = <QuickCheck t={t} onBack={()=>setView('home')}/>;
  } else if (view === 'problem') {
    body = <Problem t={t} onBack={()=>setView('home')}/>;
  } else if (view === 'photo') {
    body = <Photo t={t} onBack={()=>setView('home')}/>;
  } else if (view === 'history') {
    body = <History t={t} onBack={()=>setView('home')}/>;
  }

  return (
    <div style={{height:'100%',display:'flex',flexDirection:'column',background:FARMER_C.paperWarm,overflow:'auto'}}>
      {body}
    </div>
  );
}

window.FarmerApp = FarmerApp;
