// Census.jsx — VM0047 v1.1 census-based capture. The PLANTING UNIT is the atomic record.
// One tree, one bamboo clump = one PU. Four fields up front: ID, GPS, year, species.
// Everything else lives under "More details" (progressive disclosure).

function CensusCapture({ site, units, recentSpecies, onSaveUnit, onExit, densityLimit = 50, autoAdvance = true }) {
  const [sheetOpen, setSheetOpen] = React.useState(false);
  const [phase, setPhase] = React.useState('idle');   // idle | capturing
  const [pickerOpen, setPickerOpen] = React.useState(false);
  const [moreOpen, setMoreOpen] = React.useState(false);
  const [draft, setDraft] = React.useState(null);
  const [savedTick, setSavedTick] = React.useState(false);

  const nextNum = (units.length + 1).toString().padStart(5,'0');
  const nextId = `PU-${nextNum}`;
  const captured = units.length;
  const target = site.targetUnits || 100;
  const density = site.siteAreaHa ? (captured / site.siteAreaHa) : 0;
  const overDensity = density > densityLimit;
  const nearDensity = density > densityLimit * 0.85 && !overDensity;

  const startCapture = () => {
    setPhase('capturing');
    setSheetOpen(true);
    setMoreOpen(false);
    setDraft({
      id: nextId,
      lat: (0.16838 + (Math.random()-0.5) * 0.0002).toFixed(5),
      lon: (34.01646 + (Math.random()-0.5) * 0.0002).toFixed(5),
      acc: (2 + Math.random() * 3).toFixed(1),
      year: new Date().getFullYear(),
      speciesId: recentSpecies[0] || (site.standKind === 'Bamboo' ? 'sp_bbalcooa' : 'sp_grevillea'),
      photo: false, height: '', diameter: '', notes: '',
    });
  };

  const save = (andContinue) => {
    if (!draft) return;
    const newUnit = {
      id: draft.id,
      x: 90 + Math.random() * 220,
      y: 60  + Math.random() * 110,
      species: draft.speciesId,
      year: draft.year,
      photo: draft.photo,
      flagged: false,
    };
    onSaveUnit(newUnit, draft.speciesId);
    setSavedTick(true);
    setTimeout(()=>setSavedTick(false), 1100);
    if (andContinue && autoAdvance) {
      // Auto-advance: keep sheet open with a fresh draft
      setTimeout(() => {
        const num = (units.length + 2).toString().padStart(5,'0');
        setDraft({
          id: `PU-${num}`,
          lat: (0.16838 + (Math.random()-0.5) * 0.0002).toFixed(5),
          lon: (34.01646 + (Math.random()-0.5) * 0.0002).toFixed(5),
          acc: (2 + Math.random() * 3).toFixed(1),
          year: new Date().getFullYear(),
          speciesId: draft.speciesId,
          photo: false, height: '', diameter: '', notes: '',
        });
        setMoreOpen(false);
      }, 300);
    } else {
      setSheetOpen(false);
      setPhase('idle');
      setDraft(null);
    }
  };

  return (
    <div style={{position:'relative',height:'100%',display:'flex',flexDirection:'column',background:'#0e1f15',overflow:'hidden'}}>
      {/* Map */}
      <CensusMap site={site} units={units} agentPos={{x:50, y:200}} highlightLatest={savedTick && units.length>0 ? units[0] : null}/>

      {/* Density / progress header (floating) */}
      <div style={{position:'absolute',top:12,left:12,right:12,display:'flex',gap:8,zIndex:5}}>
        <DensityChip captured={captured} target={target} density={density} max={densityLimit} overDensity={overDensity} nearDensity={nearDensity}/>
        <button onClick={onExit} style={{background:'rgba(2,28,24,0.8)',border:'1px solid rgba(255,255,255,0.1)',color:'#fff',padding:'8px 12px',borderRadius:10,fontSize:11,fontWeight:800,letterSpacing:'0.06em',cursor:'pointer',fontFamily:'inherit',whiteSpace:'nowrap',backdropFilter:'blur(8px)',WebkitBackdropFilter:'blur(8px)'}}>
          Done
        </button>
      </div>

      {/* Captured pill rail along bottom of map */}
      {units.length > 0 && !sheetOpen && (
        <div style={{position:'absolute',bottom:120,left:0,right:0,padding:'0 12px',display:'flex',gap:6,overflowX:'auto',zIndex:4,scrollbarWidth:'none'}}>
          {units.slice(0, 10).map((u, i) => {
            const sp = speciesById(u.species);
            return (
              <div key={u.id} style={{flexShrink:0,background:'rgba(2,28,24,0.85)',border:'1px solid rgba(244,195,0,0.3)',borderRadius:999,padding:'6px 10px',fontSize:10,color:'#F4C300',fontFamily:"'JetBrains Mono', monospace",fontWeight:800,letterSpacing:'0.04em',display:'inline-flex',alignItems:'center',gap:5,backdropFilter:'blur(8px)',WebkitBackdropFilter:'blur(8px)'}}>
                <span style={{width:6,height:6,borderRadius:'50%',background:u.flagged?'#DC2626':'#F4C300'}}/>
                {u.id.replace('PU-','#')}<span style={{color:'rgba(255,255,255,0.55)',fontWeight:600}}> · {sp?.common}</span>
              </div>
            );
          })}
        </div>
      )}

      {/* Tap saved toast */}
      {savedTick && <div style={{position:'absolute',top:'48%',left:'50%',transform:'translate(-50%,-50%)',background:'rgba(43,196,138,0.95)',color:'#022C28',padding:'10px 20px',borderRadius:999,fontWeight:900,fontSize:14,zIndex:6,letterSpacing:'-0.01em',boxShadow:'0 10px 30px rgba(0,0,0,0.3)',animation:'pop .3s ease-out'}}>
        ✓ Saved · {units.length} captured
      </div>}

      {/* Idle CTA */}
      {!sheetOpen && (
        <div style={{position:'absolute',left:18,right:18,bottom:24,zIndex:5}}>
          <button onClick={startCapture} style={{width:'100%',padding:'18px',background:'#F4C300',color:'#022C28',border:'none',borderRadius:14,fontWeight:900,fontSize:16,cursor:'pointer',fontFamily:'inherit',letterSpacing:'-0.01em',display:'flex',alignItems:'center',justifyContent:'center',gap:10,boxShadow:'0 12px 40px rgba(244,195,0,0.35)'}}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
            I'm at the next {site.standKind === 'Bamboo' ? 'clump' : 'tree'}
          </button>
          <div style={{textAlign:'center',marginTop:8,fontSize:11,color:'rgba(255,255,255,0.55)',fontFamily:"'JetBrains Mono', monospace",letterSpacing:'0.04em'}}>
            Stand right next to it · GPS will pin from where you're standing
          </div>
        </div>
      )}

      {/* Capture sheet */}
      {sheetOpen && draft && (
        <CaptureSheet
          draft={draft} setDraft={setDraft}
          standKind={site.standKind}
          onPickSpecies={()=>setPickerOpen(true)}
          moreOpen={moreOpen} setMoreOpen={setMoreOpen}
          onCancel={()=>{ setSheetOpen(false); setPhase('idle'); setDraft(null); }}
          onSaveContinue={()=>save(true)}
          onSaveDone={()=>save(false)}
        />
      )}

      {/* Species picker */}
      <SpeciesPicker
        open={pickerOpen}
        onClose={()=>setPickerOpen(false)}
        value={draft ? [draft.speciesId] : []}
        dominant={draft?.speciesId}
        onChange={(arr)=>setDraft(d => ({...d, speciesId: arr[arr.length-1] || d.speciesId}))}
        onDominantChange={(id)=>setDraft(d => id ? ({...d, speciesId:id}) : d)}
        standKind={site.standKind}
      />

      <style>{`@keyframes pop { 0%{transform:translate(-50%,-50%) scale(.7); opacity:0} 60%{transform:translate(-50%,-50%) scale(1.08); opacity:1} 100%{transform:translate(-50%,-50%) scale(1); opacity:1} }
      @keyframes gpsPulse { 0%,100%{opacity:.55} 50%{opacity:1} }`}</style>
    </div>
  );
}

// ─────────────────────────── Census map ───────────────────────────
function CensusMap({ site, units, agentPos, highlightLatest }) {
  return (
    <div style={{position:'absolute',inset:0,background:'linear-gradient(135deg,#1a3d39 0%,#0e1f15 100%)'}}>
      <svg width="100%" height="100%" viewBox="0 0 360 320" preserveAspectRatio="xMidYMid slice">
        <defs>
          <pattern id="cmgrid" width="22" height="22" patternUnits="userSpaceOnUse">
            <path d="M 22 0 L 0 0 0 22" fill="none" stroke="rgba(255,255,255,0.04)" strokeWidth="0.5"/>
          </pattern>
        </defs>
        <rect width="360" height="320" fill="url(#cmgrid)"/>
        {/* River */}
        <path d="M0,40 Q90,32 180,42 T360,36" stroke="rgba(43,196,138,0.22)" strokeWidth="4" fill="none"/>
        <text x="14" y="30" fontSize="9" fill="rgba(43,196,138,0.65)" fontFamily="'JetBrains Mono', monospace">YALA RIVER</text>
        {/* Site polygon */}
        <polygon points="80,80 290,75 305,170 250,235 100,220 60,140"
          fill="rgba(244,195,0,0.06)" stroke="rgba(244,195,0,0.4)" strokeWidth="1.5" strokeDasharray="4 3"/>
        <text x="240" y="225" fontSize="9" fill="rgba(244,195,0,0.7)" fontFamily="'JetBrains Mono', monospace">SITE BOUNDARY</text>
        {/* Captured units */}
        {units.map((u, i) => {
          const isLatest = highlightLatest && u.id === highlightLatest.id;
          return (
            <g key={u.id} transform={`translate(${u.x},${u.y})`}>
              {isLatest && <circle r="14" fill="#2BC48A" opacity="0.4"/>}
              <circle r="4.5" fill={u.flagged?'#DC2626':'#F4C300'} stroke="rgba(2,28,24,0.7)" strokeWidth="1"/>
            </g>
          );
        })}
        {/* Agent position */}
        <g transform={`translate(${agentPos.x},${agentPos.y})`} style={{animation:'gpsPulse 1.6s infinite'}}>
          <circle r="20" fill="#2BC48A" opacity="0.15"/>
          <circle r="11" fill="#2BC48A" opacity="0.35"/>
          <circle r="6" fill="#2BC48A" stroke="#fff" strokeWidth="2"/>
        </g>
      </svg>
    </div>
  );
}

// ─────────────────────────── Density chip ───────────────────────────
function DensityChip({ captured, target, density, max, overDensity, nearDensity }) {
  const color = overDensity ? '#DC2626' : nearDensity ? '#D97706' : '#2BC48A';
  return (
    <div style={{flex:1,background:'rgba(2,28,24,0.82)',border:'1px solid rgba(255,255,255,0.08)',backdropFilter:'blur(10px)',WebkitBackdropFilter:'blur(10px)',borderRadius:12,padding:'10px 12px',display:'flex',alignItems:'center',gap:12,color:'#fff'}}>
      <div>
        <div style={{fontSize:9,fontWeight:800,letterSpacing:'0.1em',color:'rgba(255,255,255,0.55)',fontFamily:"'JetBrains Mono', monospace"}}>CAPTURED</div>
        <div style={{fontSize:18,fontWeight:900,color:'#F4C300',letterSpacing:'-0.02em',marginTop:1}}>{captured}<span style={{fontSize:11,color:'rgba(255,255,255,0.5)',fontWeight:700}}> / {target}</span></div>
      </div>
      <div style={{width:1,height:30,background:'rgba(255,255,255,0.1)'}}/>
      <div style={{flex:1}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',gap:6}}>
          <div style={{fontSize:9,fontWeight:800,letterSpacing:'0.08em',color:'rgba(255,255,255,0.55)',fontFamily:"'JetBrains Mono', monospace"}}>DENSITY</div>
          <div style={{fontSize:9,color, fontWeight:800,letterSpacing:'0.06em',fontFamily:"'JetBrains Mono', monospace"}}>{overDensity?'OVER':nearDensity?'NEAR':'OK'} · ≤{max}/HA</div>
        </div>
        <div style={{display:'flex',alignItems:'baseline',gap:4,marginTop:1}}>
          <span style={{fontSize:18,fontWeight:900,color,letterSpacing:'-0.02em'}}>{density.toFixed(0)}</span>
          <span style={{fontSize:10,color:'rgba(255,255,255,0.5)',fontWeight:700}}>units/ha</span>
        </div>
        <div style={{position:'relative',height:3,background:'rgba(255,255,255,0.1)',borderRadius:2,marginTop:4}}>
          <div style={{position:'absolute',left:0,top:0,bottom:0,width:`${Math.min(100, density / max * 100)}%`,background:color,borderRadius:2,transition:'width .3s ease'}}/>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────── Capture sheet ───────────────────────────
function CaptureSheet({ draft, setDraft, standKind, onPickSpecies, moreOpen, setMoreOpen, onCancel, onSaveContinue, onSaveDone }) {
  const species = speciesById(draft.speciesId);
  const accNum = parseFloat(draft.acc);
  const accGood = accNum <= 5;
  const accOk = accNum <= 8;
  const accColor = accGood ? '#2BC48A' : accOk ? '#D97706' : '#DC2626';
  const accLabel = accGood ? 'EXCELLENT' : accOk ? 'OK · LOWER ACCURACY' : 'POOR · MOVE TO OPEN SKY';

  return (
    <div style={{position:'absolute',left:0,right:0,bottom:0,top: moreOpen ? 60 : 'auto',background:'#fff',borderTopLeftRadius:18,borderTopRightRadius:18,boxShadow:'0 -10px 40px rgba(0,0,0,0.45)',display:'flex',flexDirection:'column',zIndex:10,overflow:'hidden',animation:'sheetIn .25s ease-out'}}>
      <div style={{padding:'10px 0 4px',display:'flex',justifyContent:'center'}}>
        <div style={{width:42,height:4,borderRadius:2,background:'#D1D5DB'}}/>
      </div>

      <div style={{flex:1, overflowY:'auto', padding:'4px 18px 14px'}}>
        {/* Unit ID + GPS — both auto-captured */}
        <div style={{display:'grid',gridTemplateColumns:'auto 1fr',gap:10,alignItems:'stretch',marginBottom:12}}>
          <div style={{background:'#022C28',color:'#fff',borderRadius:12,padding:'10px 12px',display:'flex',flexDirection:'column',justifyContent:'center'}}>
            <div style={{fontSize:9,fontWeight:800,letterSpacing:'0.1em',color:'#F4C300',fontFamily:"'JetBrains Mono', monospace"}}>UNIT ID</div>
            <div style={{fontSize:16,fontWeight:900,fontFamily:"'JetBrains Mono', monospace",marginTop:2,letterSpacing:'-0.01em'}}>{draft.id}</div>
          </div>
          <div style={{background:'#fff',border:`1px solid ${accColor}30`,borderRadius:12,padding:'10px 12px'}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
              <div style={{display:'inline-flex',alignItems:'center',gap:5,fontSize:9,fontWeight:800,letterSpacing:'0.08em',color:accColor,fontFamily:"'JetBrains Mono', monospace"}}>
                <span style={{width:7,height:7,borderRadius:'50%',background:accColor,animation:'gpsPulse 1.6s infinite'}}/>GPS · ±{draft.acc} m
              </div>
              <div style={{fontSize:9,fontWeight:700,color:accColor,letterSpacing:'0.04em'}}>{accLabel}</div>
            </div>
            <div style={{fontSize:13,fontWeight:800,color:'#022C28',marginTop:4,fontFamily:"'JetBrains Mono', monospace",letterSpacing:'-0.01em'}}>
              {draft.lat}, {draft.lon}
            </div>
          </div>
        </div>

        {!accGood && (
          <div style={{background:accColor+'12',border:`1px solid ${accColor}40`,borderRadius:10,padding:'10px 12px',marginBottom:12,fontSize:11,color:accColor,fontWeight:600,lineHeight:1.4}}>
            {accOk
              ? 'Step out from canopy if possible — Pamoja keeps the reading but flags it for verifier review.'
              : 'GPS is poor here. Step into open sky and wait 10 seconds for the reading to settle.'}
          </div>
        )}

        {/* Year planted */}
        <div style={{marginBottom:12}}>
          <div style={{fontSize:11,fontWeight:800,letterSpacing:'0.08em',textTransform:'uppercase',color:'#6B7280',marginBottom:6}}>Year planted</div>
          <div style={{display:'flex',gap:6}}>
            {[
              { y: new Date().getFullYear(),     l: 'This year' },
              { y: new Date().getFullYear() - 1, l: 'Last year' },
              { y: new Date().getFullYear() - 2, l: '2 yrs ago' },
              { y: 'older',                       l: 'Older…' },
            ].map(opt => {
              const sel = opt.y === 'older'
                ? (draft.year < new Date().getFullYear() - 2)
                : draft.year === opt.y;
              return (
                <button key={opt.l} onClick={()=>{
                  if (opt.y === 'older') setDraft(d=>({...d, year: d.year < new Date().getFullYear()-2 ? d.year : new Date().getFullYear()-3 }));
                  else setDraft(d=>({...d, year: opt.y}));
                }} style={{flex:1,padding:'10px 6px',background: sel?'#022C28':'#fff',color: sel?'#fff':'#022C28',border:`1.5px solid ${sel?'#022C28':'#E5E7EB'}`,borderRadius:10,fontWeight:800,fontSize:12,cursor:'pointer',fontFamily:'inherit'}}>
                  <div>{opt.l}</div>
                  <div style={{fontSize:10,fontWeight:700,opacity:0.7,marginTop:2,fontFamily:"'JetBrains Mono', monospace"}}>
                    {opt.y === 'older' ? (draft.year < new Date().getFullYear()-2 ? draft.year : '<2024') : opt.y}
                  </div>
                </button>
              );
            })}
          </div>
          {draft.year < new Date().getFullYear()-2 && (
            <div style={{marginTop:6,display:'flex',gap:8,alignItems:'center'}}>
              <button onClick={()=>setDraft(d=>({...d, year: d.year - 1}))} style={{padding:'8px 14px',background:'#F3F4F6',color:'#022C28',border:'none',borderRadius:8,fontWeight:900,fontSize:14,cursor:'pointer',fontFamily:'inherit'}}>−</button>
              <div style={{flex:1,textAlign:'center',fontSize:20,fontWeight:900,color:'#022C28',fontFamily:"'JetBrains Mono', monospace",letterSpacing:'-0.02em'}}>{draft.year}</div>
              <button onClick={()=>setDraft(d=>({...d, year: d.year + 1}))} style={{padding:'8px 14px',background:'#F3F4F6',color:'#022C28',border:'none',borderRadius:8,fontWeight:900,fontSize:14,cursor:'pointer',fontFamily:'inherit'}}>+</button>
            </div>
          )}
        </div>

        {/* Species */}
        <div style={{marginBottom:12}}>
          <div style={{fontSize:11,fontWeight:800,letterSpacing:'0.08em',textTransform:'uppercase',color:'#6B7280',marginBottom:6}}>Species</div>
          <button onClick={onPickSpecies} style={{width:'100%',padding:'12px 14px',background:'#F9FAFB',border:'1.5px solid #E5E7EB',borderRadius:10,textAlign:'left',display:'flex',alignItems:'center',gap:10,cursor:'pointer',fontFamily:'inherit'}}>
            <div style={{width:36,height:36,borderRadius:8,background:'#FFF8E0',color:'#B8960A',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M11 20A7 7 0 0 1 4 13 7 7 0 0 1 11 6h9v3a11 11 0 0 1-9 11z"/><path d="M2 22c0-7 5-12 12-12"/></svg>
            </div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:14,fontWeight:800,color:'#022C28',letterSpacing:'-0.01em',display:'flex',alignItems:'center',gap:6}}>
                {species?.common || 'Pick species'}
                {species?.shortlist && <span style={{fontSize:9,fontWeight:800,letterSpacing:'0.06em',padding:'1px 5px',borderRadius:3,background:'#FFF8E0',color:'#B8960A'}}>PROJECT</span>}
              </div>
              <div style={{fontSize:11,color:'#6B7280',fontStyle:'italic',marginTop:1}}>{species?.sci || 'Search common or scientific name'}</div>
            </div>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#6B7280" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
          </button>
        </div>

        {/* More details expander */}
        <button onClick={()=>setMoreOpen(o=>!o)} style={{width:'100%',padding:'12px',background: moreOpen ? '#FFF8E0' : 'transparent',border:`1.5px ${moreOpen?'solid':'dashed'} ${moreOpen?'#F4C300':'#D1D5DB'}`,borderRadius:10,color:'#022C28',fontWeight:800,fontSize:13,cursor:'pointer',fontFamily:'inherit',display:'flex',alignItems:'center',justifyContent:'center',gap:8}}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{transform: moreOpen?'rotate(45deg)':'none', transition:'transform .2s'}}><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
          {moreOpen ? 'Hide more details' : 'More details (optional)'}
        </button>

        {moreOpen && (
          <div style={{marginTop:10,display:'flex',flexDirection:'column',gap:10}}>
            <div style={{display:'flex',gap:8}}>
              <button onClick={()=>setDraft(d=>({...d, photo: !d.photo}))} style={{flex:1,padding:'14px 10px',background: draft.photo?'#ECFDF5':'#fff',border:`1.5px solid ${draft.photo?'#86EFAC':'#E5E7EB'}`,borderRadius:10,cursor:'pointer',fontFamily:'inherit',display:'flex',flexDirection:'column',alignItems:'flex-start',gap:6}}>
                <div style={{width:30,height:30,borderRadius:7,background: draft.photo?'#059669':'#F6F8F7',color: draft.photo?'#fff':'#022C28',display:'flex',alignItems:'center',justifyContent:'center'}}>
                  {draft.photo
                    ? <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="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="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 2z"/><circle cx="12" cy="13" r="4"/></svg>}
                </div>
                <div style={{fontSize:12,fontWeight:800,color:'#022C28',textAlign:'left'}}>{draft.photo ? 'Photo captured' : 'Add photo'}</div>
              </button>
              <div style={{flex:1,padding:'10px',background:'#fff',border:'1.5px solid #E5E7EB',borderRadius:10}}>
                <div style={{fontSize:10,fontWeight:800,letterSpacing:'0.08em',color:'#6B7280'}}>HEIGHT (M)</div>
                <input value={draft.height} onChange={(e)=>setDraft(d=>({...d, height: e.target.value}))} inputMode="decimal" placeholder="—" style={{width:'100%',background:'transparent',border:'none',outline:'none',fontSize:18,fontWeight:900,color:'#022C28',marginTop:2,fontFamily:"'JetBrains Mono', monospace",padding:0,letterSpacing:'-0.02em'}}/>
              </div>
              <DbhField draft={draft} setDraft={setDraft}/>
            </div>
            <div style={{padding:'10px 12px',background:'#fff',border:'1.5px solid #E5E7EB',borderRadius:10}}>
              <div style={{fontSize:10,fontWeight:800,letterSpacing:'0.08em',color:'#6B7280'}}>NOTES (OPTIONAL)</div>
              <input value={draft.notes} onChange={(e)=>setDraft(d=>({...d, notes: e.target.value}))} placeholder="e.g. cattle damage on lower stems" style={{width:'100%',background:'transparent',border:'none',outline:'none',fontSize:13,fontWeight:600,color:'#022C28',marginTop:4,padding:0,fontFamily:'inherit'}}/>
            </div>
            <div style={{fontSize:11,color:'#6B7280',padding:'0 4px',lineHeight:1.5}}>
              Height & DBH are only needed when this {standKind==='Bamboo'?'clump':'unit'} is in the sampling subset for biomass scaling (VM0047 §9.2.2).
            </div>
          </div>
        )}
      </div>

      {/* Sticky footer */}
      <div style={{padding:'10px 14px 14px',borderTop:'1px solid #E5E7EB',background:'#fff',display:'flex',gap:8}}>
        <button onClick={onCancel} style={{padding:'14px',background:'#fff',color:'#022C28',border:'1.5px solid #E5E7EB',borderRadius:10,fontWeight:800,fontSize:13,cursor:'pointer',fontFamily:'inherit',minWidth:80}}>
          Discard
        </button>
        <button onClick={onSaveDone} style={{flex:1,padding:'14px',background:'#fff',color:'#022C28',border:'1.5px solid #022C28',borderRadius:10,fontWeight:800,fontSize:13,cursor:'pointer',fontFamily:'inherit'}}>
          Save · stop
        </button>
        <button onClick={onSaveContinue} style={{flex:1.4,padding:'14px',background:'#F4C300',color:'#022C28',border:'none',borderRadius:10,fontWeight:900,fontSize:14,cursor:'pointer',fontFamily:'inherit',letterSpacing:'-0.01em'}}>
          Save · next →
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { CensusCapture });

// ─────────────────────────── DBH (with circumference toggle) ───────────────────────────
// Saves draft.diameter (DBH in cm). If measured with tape around the trunk,
// the user types circumference and we auto-convert: DBH ≈ circ / π.
function DbhField({ draft, setDraft }) {
  const [mode, setMode] = React.useState(draft.diameterMethod || 'across'); // 'across' | 'around'
  const [tapeInput, setTapeInput] = React.useState(draft.tapeInput || '');

  const setMethod = (m) => {
    setMode(m);
    setDraft(d => ({ ...d, diameterMethod: m }));
  };
  const onAcross = (v) => setDraft(d => ({ ...d, diameter: v, diameterMethod:'across' }));
  const onAround = (v) => {
    setTapeInput(v);
    const c = parseFloat(v);
    const dbh = isNaN(c) ? '' : (c / Math.PI).toFixed(1);
    setDraft(d => ({ ...d, diameter: dbh, diameterMethod:'around', tapeInput:v }));
  };

  return (
    <div style={{flex:1,padding:'10px',background:'#fff',border:'1.5px solid #E5E7EB',borderRadius:10,minWidth:0}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:6}}>
        <div style={{fontSize:10,fontWeight:800,letterSpacing:'0.08em',color:'#6B7280'}}>{mode==='across' ? 'DBH (CM)' : 'CIRC. (CM)'}</div>
        <div style={{display:'flex',gap:2,background:'#F3F4F6',borderRadius:6,padding:2}}>
          {[['across','Across'],['around','Tape']].map(([v,l])=>(
            <button key={v} onClick={()=>setMethod(v)} style={{padding:'3px 7px',background: mode===v?'#022C28':'transparent',color: mode===v?'#fff':'#6B7280',border:'none',borderRadius:4,fontSize:9,fontWeight:800,letterSpacing:'0.04em',cursor:'pointer',fontFamily:'inherit'}}>{l}</button>
          ))}
        </div>
      </div>
      {mode === 'across' ? (
        <input value={draft.diameter || ''} onChange={(e)=>onAcross(e.target.value)} inputMode="decimal" placeholder="—" style={{width:'100%',background:'transparent',border:'none',outline:'none',fontSize:18,fontWeight:900,color:'#022C28',marginTop:2,fontFamily:"'JetBrains Mono', monospace",padding:0,letterSpacing:'-0.02em'}}/>
      ) : (
        <>
          <input value={tapeInput} onChange={(e)=>onAround(e.target.value)} inputMode="decimal" placeholder="—" style={{width:'100%',background:'transparent',border:'none',outline:'none',fontSize:18,fontWeight:900,color:'#022C28',marginTop:2,fontFamily:"'JetBrains Mono', monospace",padding:0,letterSpacing:'-0.02em'}}/>
          {draft.diameter && <div style={{fontSize:10,color:'#059669',fontFamily:"'JetBrains Mono', monospace",marginTop:2,fontWeight:700}}>= {draft.diameter} cm DBH</div>}
        </>
      )}
    </div>
  );
}
