// Reforestation.jsx — Reforestation methodology workspace.
//
// One of the methodologies inside the Pamoja Field app. Mounted by
// PamojaField.jsx (Layer-2 shell) when the agent picks Reforestation
// at launch (or switches to it mid-shift via the floating switcher).
//
// At the visit/brief level, the workspace branches on visit.workflow:
//   CENSUS  → CensusSiteBrief  + planting-unit capture (ReforestationCensus.jsx)
//   AREA    → AreaPlotBrief    + sampling-plot inventory (ReforestationArea.jsx)
// Project configuration sets workflow at the project level; agents
// never pick the workflow.
//
// This file does NOT own methodology selection, the workspace picker,
// or the workspace switcher — PamojaField.jsx handles all of that.

function ReforestationApp() {
  const [t, setTweak] = useTweaks(window.__TWEAK_DEFAULTS);
  const [tab, setTab] = React.useState('today');
  const [screen, setScreen] = React.useState('queue');
  const [visitId, setVisitId] = React.useState(null);
  const [visitData, setVisitData] = React.useState({});
  const [unitsBySite, setUnitsBySite] = React.useState(() => {
    const seed = {};
    Object.keys(SAMPLE_UNITS).forEach(k => { seed[k] = [...SAMPLE_UNITS[k]].reverse(); });
    return seed;
  });
  const [stemsByPlot, setStemsByPlot] = React.useState(() => {
    const seed = {};
    Object.keys(SAMPLE_STEMS).forEach(k => { seed[k] = [...SAMPLE_STEMS[k]]; });
    return seed;
  });
  const [recentSpecies, setRecentSpecies] = React.useState(['sp_bbalcooa']);
  const [toast, setToast] = React.useState(null);

  const visit = VISITS.find(v => v.id === visitId) || null;
  const data = visitData[visitId] || {};
  const units = unitsBySite[visitId] || [];
  const stems = stemsByPlot[visitId] || [];

  const flash = (msg) => { setToast(msg); setTimeout(() => setToast(null), 1800); };
  const openVisit = (id) => {
    const v = VISITS.find(x => x.id === id);
    setVisitId(id);
    setScreen(v?.workflow === 'area' ? 'plotbrief' : 'brief');
  };
  const goTask = (s) => setScreen(s);
  const updateVisit = (patch) => setVisitData(d => ({ ...d, [visitId]: { ...(d[visitId]||{}), ...patch } }));

  const saveUnit = (newUnit, speciesId) => {
    setUnitsBySite(s => ({ ...s, [visitId]: [newUnit, ...(s[visitId]||[])] }));
    setRecentSpecies(rs => {
      const next = [speciesId, ...rs.filter(x=>x!==speciesId)];
      return next.slice(0,5);
    });
  };

  const saveStem = (newStem, speciesId) => {
    setStemsByPlot(s => ({ ...s, [visitId]: [...(s[visitId]||[]), newStem] }));
    setRecentSpecies(rs => {
      const next = [speciesId, ...rs.filter(x=>x!==speciesId)];
      return next.slice(0,5);
    });
  };

  const switchTab = (next) => {
    setTab(next);
    if (next === 'today') setScreen('queue');
    else setScreen(next);
  };

  const backFromSub = () => {
    const censusSubs = ['location','owner','stand','measure','photos','review','census'];
    const areaSubs   = ['plotlocate','plotinventory','plotobs','plotphotos','plotreview','plotcapture'];
    if      (areaSubs.includes(screen))   setScreen('plotbrief');
    else if (censusSubs.includes(screen)) setScreen('brief');
    else if (['brief','plotbrief'].includes(screen)) { setScreen('queue'); setVisitId(null); }
    else setScreen('queue');
  };

  return (
    <div style={{height:'100%',display:'flex',flexDirection:'column',background:'#F6F8F7',fontFamily:"'Satoshi', system-ui, sans-serif",color:'#022C28',position:'relative'}}>
      <RefoFAHeader screen={screen} visit={visit} onBack={backFromSub}/>
      <div style={{flex:1,overflowY:'auto'}}>
        {screen === 'queue'      && <RefoTodayQueue onOpen={openVisit} unitsBySite={unitsBySite} stemsByPlot={stemsByPlot} compact={t.compactList}/>}

        {/* CENSUS branch */}
        {screen === 'brief'      && visit && <CensusSiteBrief visit={visit} data={data} units={units} onTask={goTask} onCensus={()=>setScreen('census')} showMethodologyTags={t.showMethodologyTags} densityLimit={t.densityLimit||50}/>}
        {screen === 'census'     && visit && <CensusCapture site={visit} units={units} recentSpecies={recentSpecies} onSaveUnit={saveUnit} onExit={()=>{flash(`${units.length} units captured · saved locally`); setScreen('brief');}} densityLimit={t.densityLimit||50} autoAdvance={t.autoAdvance!==false}/>}
        {screen === 'location'   && visit && <LocationTask visit={visit} data={data} update={updateVisit} onDone={()=>{flash('Location confirmed'); setScreen('brief');}} ai={t.showAiHints}/>}
        {screen === 'owner'      && visit && <OwnerTask    visit={visit} data={data} update={updateVisit} onDone={()=>{flash('Owner & consent saved'); setScreen('brief');}}/>}
        {screen === 'stand'      && visit && <StandTask    visit={visit} data={data} update={updateVisit} onDone={()=>{flash('Stand details saved'); setScreen('brief');}} defaultKind={t.defaultStandKind}/>}
        {screen === 'measure'    && visit && <MeasureTask  visit={visit} data={data} update={updateVisit} onDone={()=>{flash('Measurements saved'); setScreen('brief');}} defaultGeom={t.geometryDefault}/>}
        {screen === 'photos'     && visit && <PhotosTask   visit={visit} data={data} update={updateVisit} onDone={()=>{flash('Photos attached'); setScreen('brief');}} ai={t.showAiHints}/>}
        {screen === 'review'     && visit && <ReviewTask   visit={visit} data={data} onSubmit={()=>{flash('Visit submitted · queued for sync'); setScreen('queue'); setVisitId(null);}}/>}

        {/* AREA branch */}
        {screen === 'plotbrief'    && visit && <AreaPlotBrief    visit={visit} data={data} stems={stems} onTask={goTask} onInventory={()=>setScreen('plotinventory')} showMethodologyTags={t.showMethodologyTags}/>}
        {screen === 'plotlocate'   && visit && <PlotLocateTask   visit={visit} data={data} update={updateVisit} onDone={()=>{flash('Plot centre confirmed'); setScreen('plotbrief');}} ai={t.showAiHints}/>}
        {screen === 'plotinventory'&& visit && <PlotInventory    plot={visit} stems={stems} recentSpecies={recentSpecies} onSaveStem={saveStem} onExit={()=>{flash(`${stems.length} stems recorded · saved locally`); setScreen('plotbrief');}}/>}
        {screen === 'plotobs'      && visit && <PlotObsTask      visit={visit} data={data} update={updateVisit} onDone={()=>{flash('Observations saved'); setScreen('plotbrief');}}/>}
        {screen === 'plotphotos'   && visit && <PlotPhotosTask   visit={visit} data={data} update={updateVisit} onDone={()=>{flash('Cardinal photos attached'); setScreen('plotbrief');}} ai={t.showAiHints}/>}
        {screen === 'plotreview'   && visit && <PlotReviewTask   visit={visit} data={data} stems={stems} onSubmit={()=>{flash('Plot submitted · queued for sync'); setScreen('queue'); setVisitId(null);}}/>}

        {/* Shell tabs */}
        {screen === 'map'      && <RefoRouteMap onOpen={openVisit}/>}
        {screen === 'capture'  && <CaptureHub onPhoto={()=>flash('Quick photo saved · attach to a visit')} onScan={()=>flash('Scanned · attach to a visit')}/>}
        {screen === 'qa'       && <RefoQAScreen/>}
        {screen === 'profile'  && <RefoProfileScreen onSync={()=>flash('Sync queued · waiting for Wi‑Fi')}/>}
      </div>
      <RefoFANav active={tab} onNav={switchTab}/>
      {toast && (
        <div style={{position:'absolute',left:16,right:16,bottom:84,background:'#022C28',color:'#fff',padding:'12px 16px',borderRadius:10,fontSize:14,fontWeight:600,boxShadow:'0 8px 24px rgba(2,44,40,0.3)',display:'flex',alignItems:'center',gap:10,zIndex:10}}>
          <span style={{width:8,height:8,borderRadius:'50%',background:'#2BC48A'}}/>{toast}
        </div>
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Demo · jump to a visit"/>
        <TweakSelect label="Open visit on tap" value={t.demoVisitId}
          options={VISITS.map(v => `${v.id} · ${v.workflow}`)}
          onChange={(v)=>{ const id = v.split(' · ')[0]; setTweak('demoVisitId', id); openVisit(id); }}/>
        <TweakSection label="Census workflow"/>
        <TweakNumber label="Density limit (units/ha)" value={t.densityLimit||50} min={10} max={100} step={5}
          onChange={(v)=>setTweak('densityLimit', v)}/>
        <TweakToggle label="Auto-advance to next unit" value={t.autoAdvance !== false}
          onChange={(v)=>setTweak('autoAdvance', v)}/>
        <TweakSelect label="Default plant type" value={t.defaultStandKind}
          options={['Tree','Bamboo','Mixed','Shrub']}
          onChange={(v)=>setTweak('defaultStandKind', v)}/>
        <TweakRadio label="Site shape default" value={t.geometryDefault}
          options={['Point','Polygon']}
          onChange={(v)=>setTweak('geometryDefault', v)}/>
        <TweakSection label="Area workflow"/>
        <TweakNumber label="Plot radius (m)" value={t.plotRadiusM||14} min={5} max={25} step={1}
          onChange={(v)=>setTweak('plotRadiusM', v)}/>
        <TweakSection label="Display"/>
        <TweakToggle label="AI hints" value={t.showAiHints}
          onChange={(v)=>setTweak('showAiHints', v)}/>
        <TweakToggle label="Show methodology tags" value={t.showMethodologyTags}
          onChange={(v)=>setTweak('showMethodologyTags', v)}/>
        <TweakToggle label="Compact site list" value={t.compactList}
          onChange={(v)=>setTweak('compactList', v)}/>
      </TweaksPanel>
    </div>
  );
}

// ─────────────────────────── HEADER ───────────────────────────
function RefoFAHeader({ screen, visit, onBack }) {
  const censusTitles = {
    queue:'Today', brief: visit?.id || 'Site',
    census: visit ? `Census · ${visit.id}` : 'Census',
    location:'Where is the site?', owner:'Who owns it?',
    stand:'What grows here', measure:'Site area', photos:'Site photos', review:'Review & submit',
  };
  const areaTitles = {
    plotbrief: visit?.id || 'Plot',
    plotlocate:'Walk to plot centre',
    plotinventory: visit ? `Plot inventory · ${visit.id}` : 'Plot inventory',
    plotobs:'Plot observations',
    plotphotos:'Cardinal photos',
    plotreview:'Review & submit',
  };
  const cookTitles = {
    household: visit?.id || 'Household',
    kitchenphoto:'Kitchen photo',
    cookinterview:'Primary cook',
    cooksync:'Sync status',
  };
  const titles = { ...censusTitles, ...areaTitles, ...cookTitles, map:'Route', capture:'Quick capture', qa:'My QA', profile:'Mary W.' };

  const eyebrows = {
    queue: 'Mary W. · Busia route',
    brief: visit ? `${visit.type} · ${({Tree:'Trees',Bamboo:'Bamboo',Mixed:'Mixed',Shrub:'Shrubs'})[visit.standKind]||visit.standKind}` : 'Pamoja dMRV',
    census:'Census-based · VM0047',
    location:'GPS · site polygon', owner:'Identity · land rights · consent',
    stand:'What kind · species', measure:'Hectares · boundary walk',
    photos:'Site overview · paper', review:'Readiness check',
    plotbrief: visit ? `Stratum ${visit.stratum} · ${visit.stratumName}` : 'Pamoja dMRV',
    plotlocate:'Walk to designed centre · drop pin',
    plotinventory:'Every stem inside the plot',
    plotobs:'Cover · regen · disturbance',
    plotphotos:'4 cardinals + plot centre',
    plotreview:'Readiness check',
    household: visit ? `${visit.village || ''}` : 'Pamoja dMRV',
    kitchenphoto:'Wide shot · stove visible · GPS auto',
    cookinterview:'5 quick yes / no questions',
    cooksync:'Records pending Wi‑Fi',
    map:'5 visits · 8.4 km',
    capture:'Scratchpad photo & QR', qa:'This monitoring period',
    profile:'Field agent · since Aug 2024',
  };
  const subTaskScreens = ['brief','plotbrief','household','location','owner','stand','measure','photos','review','plotlocate','plotinventory','plotobs','plotphotos','plotreview','census','kitchenphoto','cookinterview','cooksync'];
  const showBack = subTaskScreens.includes(screen);
  const hideHeader = ['census','plotinventory','kitchenphoto','photos','plotphotos'].includes(screen);
  if (hideHeader) return null;

  return (
    <div style={{background:'#022C28',color:'#fff',padding:'14px 18px',display:'flex',alignItems:'center',gap:12,flexShrink:0}}>
      {showBack
        ? <button onClick={onBack} style={{background:'none',border:'none',color:'#fff',padding:6,marginLeft:-6,cursor:'pointer'}} aria-label="Back">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
          </button>
        : <div style={{width:30,height:30,borderRadius:'50%',background:'#F4C300',color:'#022C28',display:'flex',alignItems:'center',justifyContent:'center',fontWeight:900,fontSize:13}}>MW</div>}
      <div style={{flex:1,minWidth:0}}>
        <div style={{fontSize:11,fontWeight:700,letterSpacing:'0.08em',textTransform:'uppercase',color:'rgba(255,255,255,0.6)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',marginBottom:2}}>{eyebrows[screen]||'Pamoja dMRV'}</div>
        <div style={{fontSize:18,fontWeight:900,letterSpacing:'-0.01em',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{titles[screen]}</div>
      </div>
      <div style={{display:'flex',alignItems:'center',gap:6,fontSize:10,fontWeight:700,color:'rgba(255,255,255,0.7)',fontFamily:"'JetBrains Mono', monospace"}}>
        <span style={{width:7,height:7,borderRadius:'50%',background:'#F59E0B'}}/>Offline
      </div>
    </div>
  );
}

// ─────────────────────────── TODAY QUEUE ───────────────────────────
function RefoTodayQueue({ onOpen, unitsBySite, stemsByPlot, compact }) {
  const counts = VISITS.reduce((a,v)=>{ a[v.status]=(a[v.status]||0)+1; return a; }, {});
  const censusVisits = VISITS.filter(v=>v.workflow==='census');
  const areaVisits   = VISITS.filter(v=>v.workflow==='area');

  return (
    <div style={{padding:'16px 18px 24px',display:'flex',flexDirection:'column',gap:14}}>
      {/* Greeting + purpose + next action */}
      {(() => {
        const nextCritical = VISITS.find(v => v.status === 'critical') || VISITS[0];
        const projectsCount = new Set(VISITS.map(v => v.project.split('·')[0].trim())).size;
        return (
          <div style={{background:'#022C28',color:'#fff',borderRadius:14,padding:'18px',display:'flex',flexDirection:'column',gap:14,position:'relative',overflow:'hidden'}}>
            <div style={{position:'absolute',inset:0,background:'radial-gradient(ellipse 80% 60% at 90% 0%, rgba(244,195,0,0.12), transparent 70%)',pointerEvents:'none'}}/>
            <div style={{position:'relative'}}>
              <div style={{fontSize:10,fontWeight:800,letterSpacing:'0.12em',color:'#F4C300',fontFamily:"'JetBrains Mono', monospace"}}>GOOD MORNING · MARY</div>
              <div style={{fontSize:19,fontWeight:900,letterSpacing:'-0.01em',marginTop:6,lineHeight:1.3}}>
                You're checking on <span style={{color:'#F4C300'}}>{VISITS.length} sites</span> across Busia for <span style={{color:'#F4C300'}}>{projectsCount} projects</span> today.
              </div>
              <div style={{fontSize:13,color:'rgba(255,255,255,0.75)',marginTop:8,lineHeight:1.5}}>
                You are the eyes on the ground — what you record here is the truth of what's growing in Busia. Verifiers and buyers can only trust the credits if they can trust your measurements, so take your time, capture each tree and plot carefully, and flag anything that doesn't look right.
              </div>
            </div>
            <button onClick={()=>onOpen(nextCritical.id)} style={{position:'relative',display:'flex',alignItems:'center',gap:10,padding:'12px 14px',background:'rgba(244,195,0,0.10)',border:'1px solid rgba(244,195,0,0.22)',borderRadius:10,cursor:'pointer',fontFamily:'inherit',textAlign:'left',width:'100%'}}>
              <div style={{width:30,height:30,borderRadius:8,background:'#F4C300',color:'#022C28',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polygon points="3 11 22 2 13 21 11 13 3 11"/></svg>
              </div>
              <div style={{flex:1,minWidth:0}}>
                <div style={{fontSize:10,fontWeight:800,letterSpacing:'0.1em',color:'rgba(244,195,0,0.85)',fontFamily:"'JetBrains Mono', monospace"}}>NEXT STOP · {nextCritical.distance.toUpperCase()}</div>
                <div style={{fontSize:14,fontWeight:800,color:'#fff',letterSpacing:'-0.01em',marginTop:2,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{nextCritical.participant} · {nextCritical.workflow==='area' ? `Plot ${nextCritical.id.replace('PLT-','')}` : nextCritical.plotLabel}</div>
              </div>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#F4C300" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0}}><polyline points="9 18 15 12 9 6"/></svg>
            </button>
          </div>
        );
      })()}

      {/* RefoKPI strip */}
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:8}}>
        <RefoKPI label="Critical" value={counts.critical||0} color="#DC2626"/>
        <RefoKPI label="Partial"  value={counts.partial ||0} color="#F59E0B"/>
        <RefoKPI label="Ready"    value={counts.ready   ||0} color="#059669"/>
      </div>

      {/* Mini map */}
      <div style={{position:'relative',borderRadius:12,overflow:'hidden',height:120,background:'linear-gradient(135deg,#0d3934 0%,#022C28 100%)',cursor:'pointer'}}>
        <svg width="100%" height="100%" viewBox="0 0 360 120" style={{position:'absolute',inset:0}}>
          <defs><pattern id="qgrid" width="20" height="20" patternUnits="userSpaceOnUse"><path d="M 20 0 L 0 0 0 20" fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="0.5"/></pattern></defs>
          <rect width="360" height="120" fill="url(#qgrid)"/>
          <path d="M0,75 Q80,65 160,72 T360,68" stroke="rgba(43,196,138,0.18)" strokeWidth="2.5" fill="none"/>
          <path d="M0,40 L360,55" stroke="rgba(244,195,0,0.18)" strokeWidth="3" fill="none"/>
          {/* Stratum patches (area sites) */}
          <ellipse cx="220" cy="55" rx="55" ry="22" fill="rgba(43,196,138,0.12)" stroke="rgba(43,196,138,0.3)" strokeWidth="1" strokeDasharray="3 3"/>
          {/* Route line through ordered visits */}
          <path d="M30,85 L80,72 L160,78 L220,55 L260,62 L310,80" stroke="rgba(244,195,0,0.4)" strokeWidth="1.5" fill="none" strokeDasharray="3 4"/>
          {/* Mixed icons: square = census, circle with ring = area */}
          {[[30,85,'census'],[80,72,'census'],[160,78,'area'],[220,55,'area'],[260,62,'area'],[310,80,'census']].map(([x,y,kind],i)=>(
            <g key={i} transform={`translate(${x},${y})`}>
              {kind==='area' && <circle r="9" fill="none" stroke="rgba(244,195,0,0.5)" strokeWidth="1" strokeDasharray="2 2"/>}
              <circle r="5" fill="#F4C300"/>
            </g>
          ))}
        </svg>
        <div style={{position:'absolute',top:10,left:12,right:12,fontSize:10,fontWeight:800,letterSpacing:'0.1em',textTransform:'uppercase',color:'#F4C300',fontFamily:"'JetBrains Mono', monospace",whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>Route · {VISITS.length} visits · 8.4 km</div>
        <div style={{position:'absolute',bottom:10,right:12,fontSize:11,color:'rgba(255,255,255,0.8)',fontWeight:700,background:'rgba(2,28,24,0.7)',padding:'5px 9px',borderRadius:6,fontFamily:"'JetBrains Mono', monospace"}}>Open map</div>
      </div>

      {/* Census section */}
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginTop:4,gap:8}}>
        <div style={{display:'flex',alignItems:'baseline',gap:8,minWidth:0}}>
          <div style={{fontSize:14,fontWeight:900,letterSpacing:'-0.01em',whiteSpace:'nowrap'}}>Census sites</div>
          <span style={{fontSize:9,fontWeight:800,letterSpacing:'0.08em',padding:'2px 6px',borderRadius:4,background:'#FFF8E0',color:'#B8960A',fontFamily:"'JetBrains Mono', monospace",flexShrink:0}}>{censusVisits.length}</span>
        </div>
        <div style={{fontSize:11,color:'#6B7280',fontFamily:"'JetBrains Mono', monospace",fontWeight:700,whiteSpace:'nowrap'}}>One per plant</div>
      </div>
      <div style={{display:'flex',flexDirection:'column',gap:8}}>
        {censusVisits.map(v => <VisitRow key={v.id} v={v} progress={progressOf(v, unitsBySite, stemsByPlot)} onOpen={()=>onOpen(v.id)} compact={compact}/>)}
      </div>

      {/* Area section */}
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginTop:8,gap:8}}>
        <div style={{display:'flex',alignItems:'baseline',gap:8,minWidth:0}}>
          <div style={{fontSize:14,fontWeight:900,letterSpacing:'-0.01em',whiteSpace:'nowrap'}}>Sampling plots</div>
          <span style={{fontSize:9,fontWeight:800,letterSpacing:'0.08em',padding:'2px 6px',borderRadius:4,background:'#E6FBF3',color:'#059669',fontFamily:"'JetBrains Mono', monospace",flexShrink:0}}>{areaVisits.length}</span>
        </div>
        <div style={{fontSize:11,color:'#6B7280',fontFamily:"'JetBrains Mono', monospace",fontWeight:700,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',maxWidth:140}}>Sambia Hills ARR</div>
      </div>
      <div style={{display:'flex',flexDirection:'column',gap:8}}>
        {areaVisits.map(v => <VisitRow key={v.id} v={v} progress={progressOf(v, unitsBySite, stemsByPlot)} onOpen={()=>onOpen(v.id)} compact={compact}/>)}
      </div>

      <div style={{marginTop:6,padding:'12px 14px',background:'#fff',border:'1px solid #E5E7EB',borderRadius:10,display:'flex',alignItems:'center',gap:10,fontSize:12,color:'#6B7280',lineHeight:1.5}}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#F59E0B" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0}}><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
        <span>{`Offline mode · ${VISITS.length} records held locally · auto-syncs on Wi‑Fi`}</span>
      </div>
    </div>
  );
}

function progressOf(v, unitsBySite, stemsByPlot) {
  if (v.workflow === 'census') {
    const captured = (unitsBySite[v.id]||[]).length;
    return { captured, target: v.targetUnits, kind: 'census' };
  } else {
    const captured = (stemsByPlot[v.id]||[]).length;
    return { captured, target: null, kind: 'area' };
  }
}

function RefoKPI({ label, value, color }) {
  return (
    <div style={{background:'#fff',border:'1px solid #E5E7EB',borderRadius:10,padding:'10px 12px'}}>
      <div style={{fontSize:24,fontWeight:900,color,letterSpacing:'-0.02em',lineHeight:1}}>{value}</div>
      <div style={{fontSize:10,fontWeight:800,letterSpacing:'0.08em',textTransform:'uppercase',color:'#6B7280',marginTop:6}}>{label}</div>
    </div>
  );
}

function VisitRow({ v, progress, onOpen, compact }) {
  const colors = { critical:'#DC2626', partial:'#F59E0B', ready:'#059669', callback:'#7C3AED' };
  const labels = { critical:'NOT STARTED', partial:'IN PROGRESS', ready:'READY', callback:'CALLBACK' };
  const c = colors[v.status]; const l = labels[v.status];
  const isArea = v.workflow === 'area';

  const KindIcon = () => {
    if (isArea) {
      // sampling plot glyph
      return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="9" strokeDasharray="2 2"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/></svg>;
    }
    const d = {
      Tree:   'M12 22V14 M8 14l4-4 4 4 M6 10l6-7 6 7',
      Bamboo: 'M9 22V3 M15 22V3 M9 8h6 M9 13h6 M9 18h6',
      Mixed:  'M6 22V11 L9 8 L12 11 V22 M14 22V14 L17 11 L20 14 V22 M3 22h18',
      Shrub:  'M5 22c0-4 3-7 7-7s7 3 7 7 M12 15V8 M9 11l3-3 3 3',
    }[v.standKind];
    return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d={d}/></svg>;
  };

  const kindLabel = isArea
    ? `Stratum ${v.stratum}`
    : ({Tree:'Trees',Bamboo:'Bamboo',Mixed:'Mixed',Shrub:'Shrubs'})[v.standKind] || v.standKind;

  return (
    <button onClick={onOpen} style={{textAlign:'left',background:'#fff',border:'1px solid #E5E7EB',borderRadius:12,padding: compact ? '10px 12px 10px 14px' : '14px 14px 14px 16px',display:'flex',gap:12,alignItems:'center',cursor:'pointer',fontFamily:'inherit',position:'relative',overflow:'hidden'}}>
      <div style={{position:'absolute',top:0,bottom:0,left:0,width:4,background:c}}/>
      <div style={{flex:1,minWidth:0}}>
        <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:3,flexWrap:'wrap'}}>
          <div style={{fontSize:10,fontWeight:800,letterSpacing:'0.08em',color:c,fontFamily:"'JetBrains Mono', monospace",whiteSpace:'nowrap'}}>{v.id}</div>
          <div style={{fontSize:9,fontWeight:800,letterSpacing:'0.1em',padding:'2px 6px',borderRadius:4,background:`${c}15`,color:c,whiteSpace:'nowrap'}}>{l}</div>
          <div style={{display:'inline-flex',alignItems:'center',gap:4,fontSize:10,fontWeight:700,color: isArea ? '#059669' : '#6B7280',padding:'2px 6px',borderRadius:4,background: isArea ? '#E6FBF3' : '#F3F4F6',whiteSpace:'nowrap'}}>
            <KindIcon/>{kindLabel}
          </div>
        </div>
        <div style={{fontSize:15,fontWeight:800,letterSpacing:'-0.01em',color:'#022C28'}}>{v.participant}</div>
        {!compact && <div style={{fontSize:12,color:'#6B7280',marginTop:2}}>{v.village} · {v.plotLabel}</div>}
        <div style={{fontSize:12,color:'#022C28',marginTop:6,fontWeight:700,display:'flex',alignItems:'center',gap:6}}>
          {progress.kind === 'census' ? (() => {
            const { captured, target } = progress;
            if (captured >= target) return <span style={{color:'#059669'}}>✓ Census complete · {captured}/{target} units</span>;
            if (captured === 0)      return <span>Census not started · {target} units to capture</span>;
            const pct = Math.round(captured/target*100);
            return <>
              <span>{captured}/{target} units</span>
              <div style={{flex:1,maxWidth:100,height:4,background:'#F3F4F6',borderRadius:2,overflow:'hidden'}}>
                <div style={{height:'100%',width:`${pct}%`,background:c,borderRadius:2}}/>
              </div>
              <span style={{color:'#6B7280',fontFamily:"'JetBrains Mono', monospace",fontSize:10}}>{pct}%</span>
            </>;
          })() : (() => {
            const { captured } = progress;
            if (v.status === 'ready') return <span style={{color:'#059669'}}>✓ Plot complete · {captured} stems inventoried</span>;
            if (captured === 0)       return <span>Plot inventory pending</span>;
            return <span>{captured} stems · {v.missing} task{v.missing>1?'s':''} left</span>;
          })()}
        </div>
      </div>
      <div style={{textAlign:'right',display:'flex',flexDirection:'column',alignItems:'flex-end',gap:4}}>
        <div style={{fontSize:11,fontWeight:700,color:'#6B7280',fontFamily:"'JetBrains Mono', monospace"}}>{v.distance}</div>
        <div style={{fontSize:10,fontWeight:800,letterSpacing:'0.06em',color: v.due==='Callback' ? '#7C3AED' : '#022C28'}}>{v.due.toUpperCase()}</div>
      </div>
    </button>
  );
}

// ─────────────────────────── CENSUS SITE BRIEF ───────────────────────────
function CensusSiteBrief({ visit, data, units, onTask, onCensus, showMethodologyTags, densityLimit = 50 }) {
  const [setupOpen, setSetupOpen] = React.useState(false);

  const captured = units.length;
  const target   = visit.targetUnits;
  const pct      = Math.min(100, Math.round(captured/target*100));
  const density  = visit.siteAreaHa ? captured/visit.siteAreaHa : 0;
  const overDensity = density > densityLimit;
  const nearDensity = density > densityLimit*0.85 && !overDensity;
  const densColor = overDensity ? '#DC2626' : nearDensity ? '#D97706' : '#2BC48A';

  const isLocationDone = !!data.locationConfirmed;
  const isOwnerDone    = !!data.ownerConfirmed;
  const isStandDone    = !!data.standConfirmed;
  const isMeasureDone  = !!data.measureConfirmed;
  const isPhotosDone   = !!data.photosConfirmed;
  const setupTasks = [
    { id:'location', icon:'pin',  title:'Where is the site?',     sub:'Site polygon · GPS confirmed',         done:isLocationDone, mtag:'M3 §4.1' },
    { id:'owner',    icon:'user', title:'Who owns the land?',     sub:'Name · phone · land rights · consent', done:isOwnerDone,    mtag:'M3 §5.2' },
    { id:'stand',    icon:'leaf', title:'What grows here?',       sub:'Plant type · planting arrangement',     done:isStandDone,    mtag:'M3 §6.1' },
    { id:'measure',  icon:'ruler',title:'Site area',              sub:'Boundary walk · hectares',              done:isMeasureDone,  mtag:'M3 §7.1' },
    { id:'photos',   icon:'cam',  title:'Site photos & paper',    sub:'Wide overview · land document',         done:isPhotosDone,   mtag:'M3 §8.1' },
  ];
  const setupDone = setupTasks.filter(t=>t.done).length;
  const setupMissing = setupTasks.length - setupDone;
  const censusComplete = captured >= target;
  const canSubmit = setupMissing === 0 && censusComplete && !overDensity;

  return (
    <div style={{padding:'14px 16px 24px',display:'flex',flexDirection:'column',gap:12}}>
      {/* Compact site header */}
      <div style={{background:'#fff',border:'1px solid #E5E7EB',borderRadius:12,padding:'12px 14px'}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',gap:10}}>
          <div style={{minWidth:0,flex:1}}>
            <div style={{fontSize:10,fontWeight:800,letterSpacing:'0.1em',color:'#B8960A',fontFamily:"'JetBrains Mono', monospace"}}>{visit.id} · CENSUS · {visit.type.toUpperCase()}</div>
            <div style={{fontSize:17,fontWeight:900,letterSpacing:'-0.01em',color:'#022C28',marginTop:2}}>{visit.participant}</div>
            <div style={{fontSize:12,color:'#6B7280',marginTop:1}}>{visit.village}</div>
          </div>
          <div style={{textAlign:'right',flexShrink:0}}>
            <div style={{fontSize:10,fontWeight:800,letterSpacing:'0.06em',color:'#6B7280'}}>{({Tree:'TREES',Bamboo:'BAMBOO',Mixed:'MIXED',Shrub:'SHRUBS'})[visit.standKind] || visit.standKind.toUpperCase()}</div>
            <div style={{fontSize:13,fontWeight:800,color:'#022C28',marginTop:1,fontFamily:"'JetBrains Mono', monospace"}}>{visit.siteAreaHa} ha</div>
            <div style={{fontSize:10,color:'#6B7280',fontFamily:"'JetBrains Mono', monospace",marginTop:1}}>{visit.project.split('·')[1]?.trim()}</div>
          </div>
        </div>
      </div>

      {/* CENSUS HERO */}
      <div style={{background:'#022C28',color:'#fff',borderRadius:14,padding:'16px',display:'flex',flexDirection:'column',gap:14,position:'relative',overflow:'hidden'}}>
        <div style={{position:'absolute',inset:0,background:'radial-gradient(ellipse 70% 50% at 80% 0%, rgba(244,195,0,0.12), transparent 70%)',pointerEvents:'none'}}/>
        <div style={{position:'relative',display:'flex',justifyContent:'space-between',alignItems:'flex-start',gap:10}}>
          <div style={{flex:1,minWidth:0}}>
            <div style={{fontSize:10,fontWeight:800,letterSpacing:'0.1em',color:'#F4C300',fontFamily:"'JetBrains Mono', monospace"}}>CENSUS · PLANTING UNITS</div>
            <div style={{display:'flex',alignItems:'baseline',gap:6,marginTop:6}}>
              <div style={{fontSize:38,fontWeight:900,color:'#fff',letterSpacing:'-0.03em',lineHeight:1}}>{captured}</div>
              <div style={{fontSize:14,color:'rgba(255,255,255,0.55)',fontWeight:700,fontFamily:"'JetBrains Mono', monospace"}}>/ {target}</div>
            </div>
            <div style={{fontSize:12,color:'rgba(255,255,255,0.7)',marginTop:2}}>
              {censusComplete ? 'Census complete · ready for submit' : captured===0 ? `Walk the site and tap each ${visit.standKind==='Bamboo'?'clump':'tree'}` : `${target - captured} ${visit.standKind==='Bamboo'?'clumps':'trees'} left`}
            </div>
          </div>
          <div style={{textAlign:'right',background:'rgba(255,255,255,0.06)',padding:'10px 12px',borderRadius:10,minWidth:108}}>
            <div style={{fontSize:9,fontWeight:800,letterSpacing:'0.08em',color:'rgba(255,255,255,0.55)',fontFamily:"'JetBrains Mono', monospace"}}>DENSITY</div>
            <div style={{display:'flex',alignItems:'baseline',gap:3,marginTop:2,justifyContent:'flex-end'}}>
              <span style={{fontSize:22,fontWeight:900,color:densColor,letterSpacing:'-0.02em',lineHeight:1}}>{density.toFixed(0)}</span>
              <span style={{fontSize:10,color:'rgba(255,255,255,0.55)',fontWeight:700}}>/ha</span>
            </div>
            <div style={{fontSize:9,fontWeight:800,letterSpacing:'0.06em',color:densColor,marginTop:3,fontFamily:"'JetBrains Mono', monospace"}}>≤{densityLimit}/HA · {overDensity?'OVER':nearDensity?'NEAR':'OK'}</div>
          </div>
        </div>

        <div style={{position:'relative',height:6,background:'rgba(255,255,255,0.08)',borderRadius:3,overflow:'hidden'}}>
          <div style={{position:'absolute',left:0,top:0,bottom:0,width:`${pct}%`,background:'#F4C300',borderRadius:3,transition:'width .3s'}}/>
        </div>

        {captured > 0 && (
          <div style={{display:'flex',gap:4,overflowX:'auto',scrollbarWidth:'none',position:'relative'}}>
            {units.slice(0,8).map(u => (
              <div key={u.id} style={{flexShrink:0,background:'rgba(244,195,0,0.12)',border:'1px solid rgba(244,195,0,0.25)',borderRadius:6,padding:'4px 7px',fontSize:9,color:'#F4C300',fontFamily:"'JetBrains Mono', monospace",fontWeight:800,letterSpacing:'0.04em'}}>
                {u.id.replace('PU-','#')}
              </div>
            ))}
            {captured > 8 && <div style={{flexShrink:0,padding:'4px 7px',fontSize:9,color:'rgba(255,255,255,0.55)',fontFamily:"'JetBrains Mono', monospace",fontWeight:700}}>+{captured-8} more</div>}
          </div>
        )}

        <button onClick={onCensus} style={{padding:'14px',background:'#F4C300',color:'#022C28',border:'none',borderRadius:12,fontWeight:900,fontSize:15,cursor:'pointer',fontFamily:'inherit',letterSpacing:'-0.01em',display:'flex',alignItems:'center',justifyContent:'center',gap:8,boxShadow:'0 8px 24px rgba(244,195,0,0.25)'}}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3"/></svg>
          {captured===0 ? `Start census · ${target} ${visit.standKind==='Bamboo'?'clumps':'trees'}` : censusComplete ? 'Open census map' : `Continue census · ${target-captured} left`}
        </button>
      </div>

      {/* Site setup */}
      <button onClick={()=>setSetupOpen(o=>!o)} style={{background:'#fff',border:'1px solid #E5E7EB',borderRadius:12,padding:'12px 14px',display:'flex',alignItems:'center',gap:12,cursor:'pointer',fontFamily:'inherit',textAlign:'left'}}>
        <div style={{width:34,height:34,borderRadius:8,background:setupMissing===0?'#ECFDF5':'#FFF8E0',color:setupMissing===0?'#059669':'#B8960A',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
          {setupMissing===0
            ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>}
        </div>
        <div style={{flex:1,minWidth:0}}>
          <div style={{fontSize:14,fontWeight:900,color:'#022C28',letterSpacing:'-0.01em'}}>Site setup{setupMissing===0?' · complete':''}</div>
          <div style={{fontSize:11,color:'#6B7280',marginTop:1}}>{setupMissing===0 ? `All ${setupTasks.length} items captured · done once per site` : `${setupDone} of ${setupTasks.length} complete · owner, area, papers`}</div>
        </div>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#9CA3AF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0,transform: setupOpen?'rotate(90deg)':'none',transition:'transform .2s'}}><polyline points="9 18 15 12 9 6"/></svg>
      </button>

      {setupOpen && (
        <div style={{display:'flex',flexDirection:'column',gap:8,marginTop:-4}}>
          {setupTasks.map(tk => <RefoTaskTile key={tk.id} t={{...tk, critical:true}} onOpen={()=>onTask(tk.id)} showMtag={showMethodologyTags}/>)}
        </div>
      )}

      <button onClick={()=>onTask('review')}
        style={{marginTop:4,padding:'14px',background: canSubmit ? '#F4C300':'#022C28',color: canSubmit ? '#022C28':'#fff',border:'none',borderRadius:12,fontWeight:900,fontSize:15,cursor:'pointer',fontFamily:'inherit',letterSpacing:'-0.01em',opacity: canSubmit ? 1 : 0.55}}
        disabled={!canSubmit}>
        {canSubmit ? `Submit ${captured} units & site setup ✓` : !censusComplete ? `Submit · finish census first` : setupMissing>0 ? `Submit · ${setupMissing} setup item${setupMissing>1?'s':''} left` : 'Submit · density over VM0047 limit'}
      </button>
    </div>
  );
}

function RefoTaskTile({ t, onOpen, showMtag }) {
  const ICON = {
    pin:'M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z',
    user:'M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z',
    leaf:'M11 20A7 7 0 0 1 4 13 7 7 0 0 1 11 6h9v3a11 11 0 0 1-9 11z M2 22c0-7 5-12 12-12',
    ruler:'M21 6L6 21l-3-3L18 3z M9 9l1 1 M12 12l1 1 M15 15l1 1',
    cam:'M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2zM12 13a4 4 0 1 0 0 0z',
    plot:'M12 2v4 M12 18v4 M2 12h4 M18 12h4 M12 12m-9 0a9 9 0 1 1 18 0 9 9 0 0 1 -18 0',
    stems:'M3 21h18 M6 21V10 M10 21V14 M14 21V8 M18 21V12',
    eye:'M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z',
  };
  return (
    <button onClick={onOpen} style={{textAlign:'left',background:t.done?'#F6F8F7':'#fff',border:`1px solid ${t.done?'#D1FAE5':'#E5E7EB'}`,borderRadius:12,padding:'14px',display:'flex',gap:12,alignItems:'flex-start',cursor:'pointer',fontFamily:'inherit',width:'100%'}}>
      <div style={{width:36,height:36,borderRadius:8,background:t.done?'#059669':(t.critical?'#FFF8E0':'#F6F8F7'),color:t.done?'#fff':(t.critical?'#B8960A':'#022C28'),display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
        {t.done
          ? <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
          : <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d={ICON[t.icon]}/></svg>}
      </div>
      <div style={{flex:1,minWidth:0}}>
        <div style={{display:'flex',alignItems:'center',gap:8,flexWrap:'wrap'}}>
          <div style={{fontSize:15,fontWeight:800,color:'#022C28',letterSpacing:'-0.01em'}}>{t.title}</div>
          {!t.done && t.critical && <div style={{fontSize:9,fontWeight:800,letterSpacing:'0.08em',padding:'2px 6px',borderRadius:4,background:'#FEF2F2',color:'#DC2626'}}>REQUIRED</div>}
          {showMtag && t.mtag && <div style={{fontSize:9,fontWeight:800,letterSpacing:'0.06em',padding:'2px 6px',borderRadius:4,background:'#EEF2FF',color:'#4338CA',fontFamily:"'JetBrains Mono', monospace"}}>{t.mtag}</div>}
        </div>
        <div style={{fontSize:12,color:'#6B7280',marginTop:3}}>{t.sub}</div>
      </div>
      {!t.done && <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#9CA3AF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0,marginTop:8}}><polyline points="9 18 15 12 9 6"/></svg>}
    </button>
  );
}

// ─────────────────────────── BOTTOM NAV ───────────────────────────
function RefoFANav({ active, onNav }) {
  const items = [
    { id:'today',   l:'Today',   i:'M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2zM9 22V12h6v10' },
    { id:'map',     l:'Map',     i:'M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z M12 13a3 3 0 1 0 0 0z' },
    { id:'capture', l:'Capture', i:'M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2zM12 13a4 4 0 1 0 0 0z' },
    { id:'qa',      l:'QA',      i:'M9 12l2 2 4-4 M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z' },
    { id:'profile', l:'Me',      i:'M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2 M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z' },
  ];
  return (
    <div style={{background:'#fff',borderTop:'1px solid #E5E7EB',display:'flex',padding:'8px 4px 12px',flexShrink:0}}>
      {items.map(it => {
        const isActive = it.id===active;
        return (
          <button key={it.id} onClick={()=>onNav(it.id)} style={{flex:1,background:'none',border:'none',padding:'6px 4px',display:'flex',flexDirection:'column',alignItems:'center',gap:4,cursor:'pointer',fontFamily:'inherit'}}>
            <div style={{padding:'4px 14px',borderRadius:14,background:isActive?'#FFF8E0':'transparent'}}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={isActive?'#022C28':'#9CA3AF'} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d={it.i}/></svg>
            </div>
            <div style={{fontSize:11,fontWeight:isActive?800:600,color:isActive?'#022C28':'#9CA3AF',letterSpacing:'0.02em'}}>{it.l}</div>
          </button>
        );
      })}
    </div>
  );
}

window.ReforestationApp = ReforestationApp;
window.RefoKPI = RefoKPI;
window.RefoTaskTile = RefoTaskTile;
