/* Gear tab — overview of guns / accessories / suppressors / loadouts.
   Plus the Add Gun flow (keystone) and lightweight add-X stubs for the others.
   This is the new first-class destination per SPEC.md §5.2. */

// ---------- GEAR HUB ----------
// v3.3: completely restructured. Gear is now a navigation hub. Each category
// (Loadouts / Guns / Accessories / Suppressors / Modifications) lives on its
// own dedicated subpage. The hub itself is just a clean tile menu. Solves the
// "everything fighting for attention on one page + endless scroll" problem.
function Gear({ go, emptyMode }) {
  const [reorder, setReorder] = React.useState(false);
  const [addMenuOpen, setAddMenuOpen] = React.useState(false);
  const [gunCount, setGunCount] = React.useState(null);

  React.useEffect(() => {
    window.rhDB.getAllGuns().then(function(gs) { setGunCount(gs.length); });
  }, [emptyMode]);

  const summary = gunCount === 0
    ? 'Empty · start with your first gun'
    : gunCount === null
      ? 'Loading…'
      : gunCount + ' gun' + (gunCount === 1 ? '' : 's') + ' · your safe';

  const tiles = [
    {
      id:'guns',
      label:'Guns',
      tagline:'Your safe — each gun carries its own setup',
      count: gunCount ?? 0,
      accent:'var(--rh-bone)',
      icon:<I.target s={20}/>,
      addRoute:'addgun',
      addLabel:'+ Add gun',
    },
    {
      id:'accessories',
      label:'Accessories',
      tagline:'Optics, lights, mags, triggers',
      count: emptyMode ? 0 : 6,
      accent:'var(--rh-bone-500)',
      icon:<I.package s={20}/>,
      addRoute:'addaccessory',
      addLabel:'+ Add accessory',
    },
    {
      id:'suppressors',
      label:'Suppressors',
      tagline:'NFA-regulated cans',
      count: emptyMode ? 0 : 2,
      accent:'var(--rh-dusty-red)',
      icon:<I.shield s={20}/>,
      addRoute:'addsuppressor',
      addLabel:'+ Add suppressor',
    },
    {
      id:'modifications',
      label:'Modifications',
      tagline:'Per-gun semi-permanent changes',
      count: emptyMode ? 0 : 5,
      accent:'var(--rh-steel)',
      icon:<I.cog s={20}/>,
      addRoute:'modifications',
      addLabel:'View mods',
    },
  ];

  return (
    <>
      <TopBar title="Gear"/>
      <div className="screen">
        <CollapsingHero
          eyebrow="The foundation"
          headline="Gear"
          summary={summary}
          right={
            <div style={{display:'flex', gap:6, alignItems:'center'}}>
              {/* + Gear opens a chooser, since this hub covers all gear types */}
              <QuickActionButton onClick={()=>setAddMenuOpen(o=>!o)} label="Gear"/>
              <ReorderButton on={reorder} onToggle={()=>setReorder(!reorder)}/>
              <TourButton onClick={()=>window.__rhTour && window.__rhTour('gear')}/>
            </div>
          }
        />

        {/* + Gear chooser — appears inline when toggled. Lets the user add
            any type of gear without committing to a category first. */}
        {addMenuOpen && (
          <div className="card brass" style={{padding:'4px 14px', marginTop:8}}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 0', borderBottom:'1px solid var(--border-hairline)'}}>
              <div className="label-md" style={{color:'var(--rh-brass-400)'}}>What are you adding?</div>
              <button onClick={()=>setAddMenuOpen(false)} style={{background:'transparent', border:0, color:'var(--rh-bone-500)', padding:0, cursor:'pointer', fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.18em', textTransform:'uppercase', fontWeight:600}}>Cancel</button>
            </div>
            {[
              {id:'addgun',          label:'A gun',          sub:'New firearm to your safe',          accent:'var(--rh-bone)'},
              {id:'addaccessory',    label:'An accessory',   sub:'Optic, light, magazine, holster',   accent:'var(--rh-bone-500)'},
              {id:'addsuppressor',   label:'A suppressor',   sub:'NFA-regulated can',                 accent:'var(--rh-dusty-red)'},
              {id:'modifications',   label:'A modification', sub:'Trigger, sights, grip, stock',      accent:'var(--rh-steel)'},
            ].map((opt, i, arr) => (
              <div
                key={opt.id}
                onClick={()=>{ setAddMenuOpen(false); go(opt.id); }}
                style={{
                  cursor:'pointer',
                  padding:'12px 0',
                  borderBottom: i < arr.length-1 ? '1px solid var(--border-hairline)' : 'none',
                  display:'grid', gridTemplateColumns:'auto 1fr auto', gap:12, alignItems:'center',
                }}>
                <span style={{width:9, height:9, borderRadius:'50%', background:opt.accent, display:'inline-block'}}/>
                <div>
                  <div style={{fontFamily:'var(--font-display)', fontSize:16, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1}}>{opt.label}</div>
                  <div className="label-md" style={{marginTop:3, color:'var(--rh-bone-500)', fontSize:9}}>{opt.sub}</div>
                </div>
                <X.fwd s={14}/>
              </div>
            ))}
          </div>
        )}

        <ReorderableSections
          editMode={reorder}
          onExit={(action)=>setReorder(action==='open' ? true : false)}
          defaultOrder={tiles.map(t => t.id)}
          sectionLabels={tiles.reduce((m,t)=>({...m, [t.id]: t.label.toUpperCase()}), {})}
          renderers={tiles.reduce((m,t)=>({
            ...m,
            [t.id]: () => <div style={{marginTop:10}}><GearCategoryTile tile={t} go={go}/></div>,
          }), {})}
        />
      </div>
    </>
  );
}

function GearCategoryTile({ tile, go }) {
  return (
    <div onClick={()=>go(tile.id)} style={{
      background:'var(--bg-elevated-1)',
      border:'1px solid var(--border-default)',
      borderLeft:`3px solid ${tile.accent}`,
      borderRadius:2,
      padding:'12px 14px',
      cursor:'pointer',
      display:'grid', gridTemplateColumns:'auto 1fr auto auto', gap:12, alignItems:'center',
    }}>
      <div style={{color:tile.accent}}>{tile.icon}</div>
      <div>
        <div style={{fontFamily:'var(--font-display)', fontSize:18, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1}}>{tile.label}</div>
        <div className="label-md" style={{marginTop:4, color:'var(--rh-bone-500)', fontSize:9}}>{tile.tagline}</div>
      </div>
      <div style={{textAlign:'right'}}>
        <div style={{fontFamily:'var(--font-display)', fontSize:20, color:tile.accent, letterSpacing:'0.02em', lineHeight:1, fontVariantNumeric:'tabular-nums'}}>{tile.count}</div>
        <button
          onClick={e=>{e.stopPropagation(); go(tile.addRoute);}}
          style={{
            marginTop:4,
            background:'transparent', border:0, padding:0, cursor:'pointer',
            fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.20em',
            color:'var(--rh-brass-400)', textTransform:'uppercase', fontWeight:600,
          }}>
          {tile.addLabel}
        </button>
      </div>
      <X.fwd s={14}/>
    </div>
  );
}

// ---------- GUN DETAIL (Gear context — config-focused) ----------
// v4.2: Config moved here from the Service Record. Gear → Guns → tap a gun
// lands here. This page is "what's on the gun right now" — operational.
// The Service Record (history) is reached via the cross-link button.
function GunDetail({ go }) {
  // Sample data — Glock 19 Gen5
  const gun = {
    name:'Glock 19 Gen5', gunType:'pistol', caliber:'9mm',
    serial:'ABXY1234', acquired:'Nov 02, 2023', condition:'New',
  };

  return (
    <>
      <TopBar title="Gun"/>
      <div className="screen">
        <BackRow to="guns" label="Guns" go={go}/>

        <CollapsingHero
          eyebrow={`${gun.caliber} · Acquired ${gun.acquired}`}
          headline={gun.name}
          summary={`SN ${gun.serial} · Config v3 active`}
          right={<TourButton/>}
        />

        {/* Cross-link to Service Record (history) */}
        <div className="card" style={{padding:'12px 14px', display:'grid', gridTemplateColumns:'1fr auto', gap:10, alignItems:'center', cursor:'pointer'}} onClick={()=>go('firearm')}>
          <div>
            <div className="label-md" style={{color:'var(--rh-bone-500)'}}>Looking for history?</div>
            <div style={{fontFamily:'var(--font-display)', fontSize:16, color:'var(--fg-1)', letterSpacing:'0.02em', marginTop:3}}>Open Service Record →</div>
            <div className="rh-body-sm" style={{marginTop:3, color:'var(--rh-bone-500)', fontSize:11}}>Rounds over time · sessions · malfunctions · service history</div>
          </div>
          <I.ring s={20}/>
        </div>

        {/* Slot-by-slot mounted components — version metadata moved to the
            history section below; this top section is just "what's on it". */}
        <div style={{display:'flex', alignItems:'baseline', gap:10, margin:'18px 0 8px'}}>
          <div className="label-md" style={{whiteSpace:'nowrap'}}>Components · v3 active · 740 rds</div>
          <div style={{flex:1, height:1, background:'var(--border-hairline)'}}/>
          <button onClick={()=>go('editgun')} style={{background:'transparent', border:0, padding:0, cursor:'pointer', fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.22em', color:'var(--rh-brass-400)', textTransform:'uppercase', fontWeight:600}}>Edit →</button>
        </div>
        <div style={{display:'flex', flexDirection:'column', gap:8}}>
          <ConfigSlotCard slot="OPTIC" item="Trijicon RMR Type 2" serial="RMR2-44912" mountedDate="Feb 22, 2024" rounds="740"/>
          <ConfigSlotCard slot="LIGHT" item="Streamlight TLR-7A"  mountedDate="Feb 22, 2024" rounds="740"/>
          <ConfigSlotCard slot="TRIGGER" item="Apex AEK trigger" mountedDate="Feb 22, 2024" rounds="740" mod/>
          <ConfigSlotCard slot="MAG" item="Magpul 15-rd PMAG" mountedDate="Stock"/>
          <ConfigSlotCard slot="SUPPRESSOR" item="SilencerCo Omega 9K" serial="OM9-44218" mountedDate="Apr 10, 2024" rounds="247" steel/>
          <ConfigSlotCard slot="GRIP" item="—" empty addLabel="+ Mount grip module"/>
        </div>

        {/* Modifications */}
        <LabelRule more="Add mod">Modifications · 2</LabelRule>
        <div className="card" style={{padding:'4px 14px'}}>
          <ModRow part="Trigger" detail="Apex Action Enhancement Kit" date="Feb 08" at="2,400 rds"/>
          <ModRow part="Sights"  detail="Trijicon HD Night Sights"    date="Nov 14 '23" at="0 rds" last/>
        </div>

        {/* Default ammo */}
        <LabelRule>Default ammo</LabelRule>
        <div className="card" style={{padding:'14px 16px', borderLeft:'3px solid var(--rh-brass-400)'}}>
          <div style={{display:'grid', gridTemplateColumns:'1fr auto', gap:10, alignItems:'flex-start'}}>
            <div>
              <div style={{display:'flex', alignItems:'baseline', gap:8}}>
                <span style={{fontFamily:'var(--font-display)', fontSize:22, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1}}>9mm</span>
                <span className="label-md" style={{color:'var(--rh-bone-500)', fontSize:9}}>· caliber from gun</span>
              </div>
              <div style={{display:'flex', gap:6, marginTop:10}}>
                <span style={{
                  padding:'4px 8px', background:'rgba(107,142,90,0.14)', color:'#A6C293',
                  border:'1px solid rgba(107,142,90,0.35)', borderRadius:2,
                  fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.18em',
                  textTransform:'uppercase', fontWeight:600, lineHeight:1,
                }}>Training</span>
                <span style={{
                  padding:'4px 8px', background:'var(--bg-elevated-2)', color:'var(--rh-bone-300)',
                  border:'1px solid var(--border-default)', borderRadius:2,
                  fontFamily:'var(--font-display)', fontSize:13, letterSpacing:'0.02em', lineHeight:1,
                }}>115gr</span>
              </div>
              <div className="label-md" style={{marginTop:8, color:'var(--rh-bone-500)', fontSize:9}}>Pre-fills when this gun is brought to the range. Override per session.</div>
            </div>
            <button className="btn btn-secondary" style={{padding:'8px 12px', fontSize:10}} onClick={()=>go('editgun')}>Change</button>
          </div>
        </div>

        {/* Photos */}
        <LabelRule more="Add photo">Photos</LabelRule>
        <div className="wire-firearm" style={{height:84}}>
          <span style={{position:'absolute', bottom:6, right:8, fontFamily:'var(--font-ui)', fontSize:8, letterSpacing:'0.24em', color:'var(--rh-bone-500)', fontWeight:600}}>FIREARM PHOTO</span>
        </div>

        {/* Acquisition */}
        <LabelRule>Acquisition</LabelRule>
        <div className="card">
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
            <div>
              <div className="label-md" style={{fontSize:8, color:'var(--rh-bone-500)'}}>Acquired</div>
              <div style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--fg-1)', letterSpacing:'0.02em', marginTop:3}}>{gun.acquired}</div>
            </div>
            <div>
              <div className="label-md" style={{fontSize:8, color:'var(--rh-bone-500)'}}>Condition</div>
              <div style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--fg-1)', letterSpacing:'0.02em', marginTop:3}}>{gun.condition}</div>
            </div>
            <div>
              <div className="label-md" style={{fontSize:8, color:'var(--rh-bone-500)'}}>Serial</div>
              <div style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--fg-1)', letterSpacing:'0.02em', marginTop:3}}>{gun.serial}</div>
            </div>
            <div>
              <div className="label-md" style={{fontSize:8, color:'var(--rh-bone-500)'}}>Type</div>
              <div style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--fg-1)', letterSpacing:'0.02em', marginTop:3, textTransform:'capitalize'}}>{gun.gunType}</div>
            </div>
          </div>
        </div>

        <div style={{marginTop:16}}>
          <Button variant="secondary" block onClick={()=>go('firearm')} icon={<I.ring s={14}/>}>Open Service Record</Button>
        </div>
      </div>
    </>
  );
}

// Small helper used here — the actual component lives in screens-record.jsx
// but for cross-page use we re-stub it. Since both files export it as window
// globals at parse time, this'll just use the global at runtime.
// (no local def needed — window.ConfigSlotCard is defined in screens-record.jsx)

// ---------- GUN CONFIG EDITOR ----------
// v4.5: real editor. Wires up the Edit / Swap / Change CTAs from GunDetail.
// Each slot has a current item + a "Swap" affordance that opens an inline
// inventory picker for accessories of that slot type. Modifications get a
// "remove + replace" flow since they're semi-permanent. Default ammo
// reuses the loadout-editor pattern.
function GunConfigEditor({ go }) {
  // Sample state — Glock 19 Gen5 current setup
  const [slots, setSlots] = React.useState({
    OPTIC: 'Trijicon RMR Type 2',
    LIGHT: 'Streamlight TLR-7A',
    SUPPRESSOR: 'SilencerCo Omega 9K',
    MAGAZINE: 'Magpul 15-rd PMAG',
  });
  const [mods, setMods] = React.useState({
    TRIGGER: 'Apex AEK trigger',
    SIGHTS: 'Trijicon HD Night Sights',
  });
  const [defAmmo, setDefAmmo] = React.useState({ type:'Training', grain:'115' });
  const [editingSlot, setEditingSlot] = React.useState(null); // slot id currently being swapped

  const gun = { name:'Glock 19 Gen5', caliber:'9mm', gunType:'pistol' };

  // Inventory pools — what the user could swap in for each slot
  const inventory = {
    OPTIC:    ['Trijicon RMR Type 2','Sig Romeo Zero','Holosun 507K'],
    LIGHT:    ['Streamlight TLR-7A','Surefire X300U-A'],
    SUPPRESSOR:['SilencerCo Omega 9K','Dead Air Sandman-S'],
    MAGAZINE: ['Magpul 15-rd PMAG','Magpul 17-rd PMAG','Glock factory 17-rd'],
  };
  const modInventory = {
    TRIGGER: ['Apex AEK trigger','Overwatch Precision','Stock'],
    SIGHTS:  ['Trijicon HD Night Sights','XS Big Dot','Factory sights'],
    GRIP:    ['Stock','Talon grip wrap','TXG tungsten module'],
  };

  const setSlot = (slot, value) => setSlots(s => ({...s, [slot]: value === '' ? null : value}));
  const setMod  = (slot, value) => setMods(m => ({...m, [slot]: value === '' ? null : value}));
  const removeSlot = (slot) => setSlots(s => ({...s, [slot]: null}));

  return (
    <>
      <TopBar title="Edit configuration"/>
      <div className="screen">
        <BackRow to="gundetail" label="Gun" go={go}/>

        <CollapsingHero
          eyebrow={`${gun.name} · ${gun.caliber}`}
          headline="Configure"
          summary="Slot-by-slot · changes saved as a new version"
          right={<TourButton/>}
        />

        {/* Banner explaining versioning */}
        <div className="card" style={{background:'transparent', borderStyle:'dashed', borderColor:'var(--rh-brass-tint-32)', padding:'10px 12px'}}>
          <div className="label-md" style={{color:'var(--rh-brass-400)'}}>Changes create a new config version</div>
          <div className="rh-body-sm" style={{marginTop:6, color:'var(--rh-bone-300)', fontSize:11}}>Past sessions still reference the version that was on the gun at the time. No data is overwritten.</div>
        </div>

        {/* ACCESSORIES — swappable slots */}
        <LabelRule>Accessories · swappable</LabelRule>
        <div style={{display:'flex', flexDirection:'column', gap:8}}>
          {['OPTIC','LIGHT','SUPPRESSOR','MAGAZINE'].map(slot => (
            <SlotEditor
              key={slot}
              slot={slot}
              accent={slot==='SUPPRESSOR' ? 'var(--rh-steel)' : 'var(--rh-bone-500)'}
              current={slots[slot]}
              isEditing={editingSlot===slot}
              inventory={inventory[slot] || []}
              onStartEdit={()=>setEditingSlot(editingSlot===slot ? null : slot)}
              onPick={(item)=>{ setSlot(slot, item); setEditingSlot(null); }}
              onRemove={()=>{ removeSlot(slot); setEditingSlot(null); }}
            />
          ))}
        </div>

        {/* MODIFICATIONS — semi-permanent. Same UX, different framing. */}
        <LabelRule>Modifications · semi-permanent</LabelRule>
        <div className="rh-body-sm" style={{padding:'0 4px 8px', color:'var(--rh-bone-500)', fontSize:11}}>
          Swapping a mod implies installing a new part. The previous mod is preserved in the gun's history.
        </div>
        <div style={{display:'flex', flexDirection:'column', gap:8}}>
          {['TRIGGER','SIGHTS','GRIP'].map(slot => (
            <SlotEditor
              key={slot}
              slot={slot}
              accent="var(--rh-dusty-red)"
              mod
              current={mods[slot]}
              isEditing={editingSlot===slot}
              inventory={modInventory[slot] || []}
              onStartEdit={()=>setEditingSlot(editingSlot===slot ? null : slot)}
              onPick={(item)=>{ setMod(slot, item); setEditingSlot(null); }}
              onRemove={()=>{ setMod(slot, null); setEditingSlot(null); }}
            />
          ))}
        </div>

        {/* DEFAULT AMMO */}
        <LabelRule>Default ammo</LabelRule>
        <div className="card" style={{padding:'12px 14px'}}>
          <div className="rh-body-sm" style={{color:'var(--rh-bone-500)', fontSize:11, marginBottom:8}}>
            Caliber from gun · {gun.caliber}. Pre-fills when this gun is brought to the range.
          </div>
          <div className="label-md" style={{fontSize:8, color:'var(--rh-bone-500)'}}>Use category</div>
          <div style={{display:'flex', flexWrap:'wrap', gap:6, marginTop:6}}>
            {['Training','Defensive','Match','Other'].map(t => (
              <Pill key={t} on={defAmmo.type===t} onClick={()=>setDefAmmo(a=>({...a, type:t}))}>{t}</Pill>
            ))}
          </div>
          <div style={{height:1, background:'var(--border-hairline)', margin:'10px 0'}}/>
          <div className="label-md" style={{fontSize:8, color:'var(--rh-bone-500)'}}>Grain</div>
          <div style={{display:'flex', flexWrap:'wrap', gap:6, marginTop:6}}>
            {['115','124','147'].map(g => (
              <Pill key={g} on={defAmmo.grain===g} onClick={()=>setDefAmmo(a=>({...a, grain:g}))}>{g}gr</Pill>
            ))}
          </div>
          <div style={{height:1, background:'var(--border-hairline)', margin:'10px 0'}}/>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline'}}>
            <span className="label-md" style={{color:'var(--rh-brass-400)'}}>RESULT</span>
            <span style={{fontFamily:'var(--font-display)', fontSize:16, color:'var(--fg-1)', letterSpacing:'0.02em'}}>{gun.caliber} · {defAmmo.type} · {defAmmo.grain}gr</span>
          </div>
        </div>

        {/* SAVE / CANCEL */}
        <div style={{marginTop:18, display:'grid', gridTemplateColumns:'1fr 2fr', gap:10}}>
          <Button variant="secondary" block onClick={()=>go('gundetail')}>Cancel</Button>
          <Button variant="primary" block onClick={()=>go('gundetail')} icon={<I.check s={14}/>}>Save configuration</Button>
        </div>
      </div>
    </>
  );
}

function SlotEditor({ slot, accent, mod, current, isEditing, inventory, onStartEdit, onPick, onRemove }) {
  return (
    <div style={{
      background:'var(--bg-elevated-1)',
      border:'1px solid var(--border-default)',
      borderLeft:`3px solid ${current ? accent : 'var(--border-default)'}`,
      borderRadius:2,
      padding:'10px 14px',
    }}>
      <div style={{display:'grid', gridTemplateColumns:'80px 1fr auto', gap:10, alignItems:'center'}}>
        <div>
          <span className="label-md" style={{color:current ? accent : 'var(--rh-bone-500)', letterSpacing:'0.20em', fontSize:9}}>{slot}</span>
          {mod && current && <div className="label-md" style={{color:'var(--rh-dusty-red)', fontSize:8, letterSpacing:'0.22em', marginTop:3}}>MOD</div>}
        </div>
        <div>
          {current ? (
            <span style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--fg-1)', letterSpacing:'0.02em'}}>{current}</span>
          ) : (
            <span className="rh-body-sm" style={{color:'var(--rh-bone-700)'}}>Empty</span>
          )}
        </div>
        <button onClick={onStartEdit} style={{
          padding:'5px 10px',
          background: isEditing ? 'var(--rh-brass)' : 'transparent',
          color: isEditing ? 'var(--rh-obsidian)' : 'var(--rh-brass-400)',
          border:`1px solid ${isEditing ? 'var(--rh-brass)' : 'var(--rh-brass-tint-32)'}`,
          borderRadius:2, cursor:'pointer',
          fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.16em',
          textTransform:'uppercase', fontWeight:600,
        }}>
          {isEditing ? 'Cancel' : (current ? 'Swap' : '+ Mount')}
        </button>
      </div>

      {/* Inline picker — when editing this slot, show inventory pills */}
      {isEditing && (
        <div style={{marginTop:10, paddingTop:10, borderTop:'1px solid var(--border-hairline)'}}>
          <div className="label-md" style={{fontSize:8, color:'var(--rh-bone-500)', marginBottom:6}}>Pick from your inventory · {slot.toLowerCase()}</div>
          <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
            {inventory.map(item => (
              <Pill key={item} on={current===item} onClick={()=>onPick(item)}>{item}</Pill>
            ))}
          </div>
          {current && (
            <button onClick={onRemove} style={{
              marginTop:10,
              padding:'5px 10px',
              background:'transparent',
              color:'#E48A82',
              border:'1px solid rgba(195,58,46,0.4)',
              borderRadius:2, cursor:'pointer',
              fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.16em',
              textTransform:'uppercase', fontWeight:600,
            }}>Remove from gun</button>
          )}
        </div>
      )}
    </div>
  );
}

// ---------- LOADOUTS SUBPAGE ----------
function LoadoutsPage({ go, emptyMode }) {
  const count = emptyMode ? 0 : 4;
  return (
    <>
      <TopBar title="Loadouts"/>
      <div className="screen">
        <BackRow to="gear" label="Gear" go={go}/>
        <CollapsingHero
          eyebrow="Gear · Loadouts"
          headline="Loadouts"
          summary={`${count} saved · what you bring to the range`}
          right={<TourButton/>}
        />

        {/* Scalability clarifier: loadouts are optional and curated.
            Counters the "do I need one per gun?" worry. */}
        <div className="card" style={{background:'transparent', borderStyle:'dashed', borderColor:'var(--rh-brass-tint-32)', padding:'10px 12px'}}>
          <div className="label-md" style={{color:'var(--rh-brass-400)'}}>Loadouts are optional</div>
          <div className="rh-body-sm" style={{marginTop:6, color:'var(--rh-bone-300)'}}>You don't need one per gun. Most users keep 3–10 loadouts for setups they actually shoot (range guns, carry guns, suppressed variants). For a one-off, log a session with just the gun + ammo — no loadout required.</div>
        </div>

        <LoadoutsFeatured go={go} emptyMode={emptyMode} hideHeader/>
      </div>
    </>
  );
}

// ---------- GUNS SUBPAGE ----------
function GunsPage({ go, emptyMode }) {
  const [guns, setGuns] = React.useState(null);

  React.useEffect(() => {
    window.rhDB.getAllGuns().then(setGuns);
  }, [emptyMode]);

  const count = guns ? guns.length : 0;
  const summary = guns === null
    ? 'Loading…'
    : count + ' gun' + (count === 1 ? '' : 's') + ' · grouped by type';

  return (
    <>
      <TopBar title="Guns"/>
      <div className="screen">
        <BackRow to="gear" label="Gear" go={go}/>
        <CollapsingHero
          eyebrow="Gear · Inventory"
          headline="Guns"
          summary={summary}
          right={
            <div style={{display:'flex', gap:6, alignItems:'center'}}>
              <QuickActionButton onClick={()=>go('addgun')} label="Gun"/>
              <TourButton onClick={()=>window.__rhTour && window.__rhTour('guns')}/>
            </div>
          }
        />
        <GunsList go={go} emptyMode={emptyMode} guns={guns}/>
      </div>
    </>
  );
}

// ---------- ACCESSORIES SUBPAGE ----------
function AccessoriesPage({ go, emptyMode }) {
  const count = emptyMode ? 0 : 6;
  return (
    <>
      <TopBar title="Accessories"/>
      <div className="screen">
        <BackRow to="gear" label="Gear" go={go}/>
        <CollapsingHero
          eyebrow="Gear · Inventory"
          headline="Accessories"
          summary={`${count} item${count===1?'':'s'} · optics, lights, mags`}
          right={
            <div style={{display:'flex', gap:6, alignItems:'center'}}>
              <QuickActionButton onClick={()=>go('addaccessory')} label="Acc"/>
              <TourButton onClick={()=>window.__rhTour && window.__rhTour('accessories')}/>
            </div>
          }
        />
        <AccessoriesList go={go} emptyMode={emptyMode}/>
      </div>
    </>
  );
}

// ---------- SUPPRESSORS SUBPAGE ----------
function SuppressorsPage({ go, emptyMode }) {
  const count = emptyMode ? 0 : 2;
  return (
    <>
      <TopBar title="Suppressors"/>
      <div className="screen">
        <BackRow to="gear" label="Gear" go={go}/>
        <CollapsingHero
          eyebrow="Gear · NFA-regulated"
          headline="Suppressors"
          summary={`${count} can${count===1?'':'s'} · own service records`}
          right={
            <div style={{display:'flex', gap:6, alignItems:'center'}}>
              <QuickActionButton onClick={()=>go('addsuppressor')} label="Can"/>
              <TourButton onClick={()=>window.__rhTour && window.__rhTour('suppressors')}/>
            </div>
          }
        />
        <SuppressorsList go={go} emptyMode={emptyMode}/>
      </div>
    </>
  );
}

// ---------- MODIFICATIONS SUBPAGE ----------
// Modifications are gun-level attributes (semi-permanent, non-transferable).
// This view aggregates mods across all guns; per-gun mods live inside each
// gun's Service Record.
function ModificationsPage({ go, emptyMode }) {
  if (emptyMode) return (
    <>
      <TopBar title="Modifications"/>
      <div className="screen">
        <BackRow to="gear" label="Gear" go={go}/>
        <CollapsingHero
          eyebrow="Gear · Per-gun changes"
          headline="Modifications"
          summary="No modifications yet"
          right={<TourButton/>}
        />
        <EmptySectionCTA
          title="No modifications yet"
          sub="Modifications are semi-permanent changes to a specific gun (trigger swap, barrel change, etc.). Add one from a gun's Service Record."
          cta="Browse guns"
          onClick={()=>go('guns')}
        />
      </div>
    </>
  );

  const mods = [
    { gun:'Glock 19 Gen5', gunType:'pistol', part:'Trigger', detail:'Apex Action Enhancement Kit', date:'Feb 08' },
    { gun:'Glock 19 Gen5', gunType:'pistol', part:'Sights',  detail:'Trijicon HD Night Sights',    date:'Nov 14 \'23' },
    { gun:'SIG P365 XL',   gunType:'pistol', part:'Trigger', detail:'Grayguns flat trigger',       date:'Mar 22' },
    { gun:'11.5″ AR-15',   gunType:'ar',     part:'Stock',   detail:'BCM Mod 0 stock',             date:'Apr 02' },
    { gun:'11.5″ AR-15',   gunType:'ar',     part:'Grip',    detail:'Magpul MOE pistol grip',      date:'Apr 02' },
  ];

  // Group by gun
  const grouped = {};
  mods.forEach(m => { (grouped[m.gun] = grouped[m.gun] || []).push(m); });

  return (
    <>
      <TopBar title="Modifications"/>
      <div className="screen">
        <BackRow to="gear" label="Gear" go={go}/>
        <CollapsingHero
          eyebrow="Gear · Per-gun changes"
          headline="Modifications"
          summary={`${mods.length} modifications across ${Object.keys(grouped).length} firearm${Object.keys(grouped).length===1?'':'s'}`}
          right={<TourButton/>}
        />

        <div className="card" style={{background:'transparent', borderStyle:'dashed', borderColor:'var(--rh-brass-tint-32)', padding:'10px 12px', marginTop:4}}>
          <div className="label-md" style={{color:'var(--rh-brass-400)'}}>What goes here</div>
          <div className="rh-body-sm" style={{marginTop:6, color:'var(--rh-bone-300)'}}>Modifications are semi-permanent, gun-specific changes — triggers, barrels, sights, mag wells. Unlike accessories, they don't transfer between guns. Each mod creates a milestone in the gun's Service Record.</div>
        </div>

        {Object.keys(grouped).map(gun => (
          <React.Fragment key={gun}>
            <LabelRule more="Open record">{gun}</LabelRule>
            <div className="card" style={{padding:'4px 14px'}}>
              {grouped[gun].map((m, i) => (
                <div key={i} style={{display:'grid', gridTemplateColumns:'72px 1fr auto', gap:10, alignItems:'baseline', padding:'10px 0', borderBottom: i < grouped[gun].length-1 ? '1px solid var(--border-hairline)' : 'none'}}>
                  <span className="label-md" style={{color:'var(--rh-steel-400)', letterSpacing:'0.18em'}}>{m.part}</span>
                  <span style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--fg-1)', letterSpacing:'0.02em'}}>{m.detail}</span>
                  <span className="label-md" style={{color:'var(--rh-bone-500)'}}>{m.date}</span>
                </div>
              ))}
            </div>
          </React.Fragment>
        ))}

        <div style={{marginTop:16}}>
          <Button variant="secondary" block onClick={()=>go('guns')}>Open a gun's record to add</Button>
        </div>
      </div>
    </>
  );
}

// ---------- LOADOUTS FEATURED (list of loadout cards) ----------
function LoadoutsFeatured({ go, emptyMode, hideHeader }) {
  if (emptyMode) return (
    <div style={{marginTop:12}}>
      <EmptySectionCTA
        title="No loadouts yet"
        sub="A loadout is a gun + accessories + suppressor you bring to the range."
        cta="Create a loadout"
        onClick={()=>go('editloadout')}
      />
    </div>
  );

  const loadouts = [
    { num:'01', name:'Glock 19',              gun:'Glock 19 Gen5', gunType:'pistol', caliber:'9mm',  accessories:[{name:'Trijicon RMR Type 2', slot:'OPTIC'}, {name:'Streamlight TLR-7A', slot:'LIGHT'}], suppressor:null,       ammo:'9mm · Training · 115gr',   status:'ready' },
    { num:'02', name:'Glock 19 · Suppressed', gun:'Glock 19 Gen5', gunType:'pistol', caliber:'9mm',  accessories:[{name:'Trijicon RMR Type 2', slot:'OPTIC'}, {name:'Streamlight TLR-7A', slot:'LIGHT'}], suppressor:{name:'SilencerCo Omega 9K', serial:'OM9-44218'}, ammo:'9mm · Training · 115gr',   status:'ready' },
    { num:'03', name:'AR Defense',            gun:'11.5″ AR-15',   gunType:'ar',     caliber:'5.56', accessories:[{name:'Primary Arms GLx 1-6× LPVO', slot:'OPTIC'}, {name:'BCM Mod 0 Stock', slot:'STOCK'}, {name:'Magpul MOE grip', slot:'GRIP'}], suppressor:null, ammo:'5.56 · Defensive · 62gr',  status:'ready' },
    { num:'04', name:'P365 Carry',            gun:'SIG P365 XL',   gunType:'pistol', caliber:'9mm',  accessories:[{name:'Sig Romeo Zero', slot:'OPTIC'}], suppressor:null, ammo:'9mm · Defensive · 124gr',  status:'due' },
  ];

  return (
    <>
      {!hideHeader && (
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginTop:14, marginBottom:10}}>
          <div>
            <div className="label-md" style={{color:'var(--rh-brass-400)'}}>Loadouts · 4</div>
            <div style={{fontFamily:'var(--font-display)', fontSize:22, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1, marginTop:4}}>What you bring to the range</div>
          </div>
          <button className="btn btn-secondary" style={{padding:'8px 12px', fontSize:10}} onClick={()=>go('editloadout')}>+ New</button>
        </div>
      )}
      <div style={{display:'flex', flexDirection:'column', gap:12, marginTop: hideHeader ? 8 : 0}}>
        {loadouts.map(l => <LoadoutCard key={l.num} {...l} onEdit={()=>go('editloadout')}/>)}
      </div>
      {hideHeader && (
        <div style={{marginTop:14}}>
          <Button variant="primary" block onClick={()=>go('editloadout')} icon={<I.plus s={14}/>}>Create a new loadout</Button>
        </div>
      )}
    </>
  );
}

// ---------- LOADOUT CARD ----------
// v3.1: character-sheet redesign. Brass top strip with big number + LOADOUT
// eyebrow, hero silhouette of the gun, component slots with type labels,
// prominent default ammo, expandable "inspect" section with internal tabs
// (Gun / Accessories / Suppressor) per user request.
function LoadoutCard({ num, name, gun, gunType, caliber, accessories, suppressor, ammo, status, onEdit }) {
  const [expanded, setExpanded] = React.useState(false);
  const [subTab, setSubTab] = React.useState('gun');
  const Silhouette = (GunSil[gunType] || GunSil.pistol);

  return (
    <div className="loadout-card" style={{
      background:'var(--bg-elevated-1)',
      border:'1px solid var(--rh-brass-tint-32)',
      borderLeft:'4px solid var(--rh-brass)',
      borderRadius:2,
      overflow:'hidden',
      transition:'box-shadow 120ms ease',
      boxShadow: expanded ? '0 0 0 1px var(--rh-brass-tint-32), 0 8px 24px rgba(0,0,0,0.4)' : 'none',
    }}>
      {/* HEADER STRIP — establishes this is a LOADOUT, not a gun.
          Silhouette moved to a small corner badge so the card stays compact. */}
      <div style={{
        padding:'12px 14px',
        background:'rgba(184,154,86,0.06)',
        borderBottom:'1px solid var(--rh-brass-tint-32)',
        display:'grid', gridTemplateColumns:'auto 1fr auto auto', gap:10, alignItems:'center',
      }}>
        <div style={{
          fontFamily:'var(--font-display)', fontSize:28, color:'var(--rh-brass-400)',
          letterSpacing:'0.04em', lineHeight:1, fontVariantNumeric:'tabular-nums',
          minWidth:36, textAlign:'center',
        }}>{num}</div>
        <div>
          <div className="label-md" style={{fontSize:8, color:'var(--rh-brass-400)', letterSpacing:'0.28em'}}>· LOADOUT ·</div>
          <div style={{fontFamily:'var(--font-display)', fontSize:20, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1, marginTop:3}}>{name}</div>
        </div>
        {/* Small silhouette badge — compact, no longer dominates */}
        <div style={{color:'var(--rh-bone-500)', opacity:0.75, display:'flex', alignItems:'center'}}>
          <Silhouette w={gunType==='pistol'||gunType==='revolver' ? 44 : 64}/>
        </div>
        {suppressor && (
          <span style={{
            display:'inline-flex', alignItems:'center', gap:5,
            padding:'4px 7px',
            background:'rgba(195,58,46,0.14)',
            color:'#E48A82',
            border:'1px solid rgba(195,58,46,0.4)',
            fontFamily:'var(--font-ui)', fontSize:8, letterSpacing:'0.22em',
            fontWeight:600, textTransform:'uppercase', lineHeight:1,
          }}>
            <span style={{width:4, height:4, borderRadius:'50%', background:'#E48A82'}}/>
            SUP
          </span>
        )}
      </div>

      {/* COMPONENT SLOTS — color-coded by gear type to convey assembly */}
      <div style={{padding:'10px 14px 8px', display:'flex', flexWrap:'wrap', gap:6}}>
        <ComponentSlot type="gun" label={gun} slot={caliber}/>
        {accessories.map(a => (
          <ComponentSlot key={a.name} type="acc" label={a.name} slot={a.slot}/>
        ))}
        {suppressor && <ComponentSlot type="sup" label={suppressor.name} slot="SUP"/>}
      </div>

      {/* DEFAULT AMMO row */}
      <div style={{padding:'8px 14px', borderTop:'1px solid var(--border-hairline)', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
        <span className="label-md" style={{fontSize:8, color:'var(--rh-bone-500)'}}>Default ammo</span>
        <span style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--rh-bone-300)', letterSpacing:'0.02em'}}>{ammo}</span>
      </div>

      {/* Two clear CTAs — collapsed shows Details + Edit. Use-for-trip
          was redundant with the Home "Live" button and has been removed. */}
      <div style={{padding:'8px 10px 10px', borderTop:'1px solid var(--border-hairline)', display:'grid', gridTemplateColumns:'1fr 1fr', gap:6}}>
        <button
          className="btn btn-ghost"
          style={{padding:'10px', fontSize:10, justifyContent:'center'}}
          onClick={()=>setExpanded(e=>!e)}>
          {expanded ? 'Hide details ↑' : 'Details ↓'}
        </button>
        <button
          className="btn btn-secondary"
          style={{padding:'10px', fontSize:10, justifyContent:'center'}}
          onClick={onEdit}>
          Edit
        </button>
      </div>

      {/* EXPANDED INTERNAL TABS */}
      {expanded && (
        <div style={{borderTop:'1px solid var(--rh-brass-tint-32)', background:'var(--rh-obsidian-900)'}}>
          <div className="top-tabs" style={{margin:0, padding:'0 14px', borderBottom:'1px solid var(--border-default)'}}>
            {[
              {id:'gun', label:'Gun',         dot:'var(--rh-bone)'},
              {id:'acc', label:'Accessories', dot:'var(--rh-bone-500)'},
              {id:'sup', label:'Suppressor',  dot:'var(--rh-dusty-red)'},
            ].map(t => (
              <div key={t.id} className={`t ${subTab===t.id?'on':''}`} onClick={()=>setSubTab(t.id)}>
                <span className="dot" style={{background:t.dot}}/>
                {t.label}
              </div>
            ))}
          </div>
          <div style={{padding:'14px'}}>
            {subTab==='gun' && <LoadoutDetailGun gun={gun} caliber={caliber}/>}
            {subTab==='acc' && <LoadoutDetailAcc accessories={accessories}/>}
            {subTab==='sup' && <LoadoutDetailSup suppressor={suppressor}/>}
          </div>
          <div style={{padding:'0 14px 14px'}}>
            <Button variant="primary" block onClick={onEdit}>Open in editor</Button>
          </div>
        </div>
      )}
    </div>
  );
}

function ComponentSlot({ type, label, slot }) {
  const colors = {
    gun: 'var(--rh-bone)',
    acc: 'var(--rh-bone-500)',
    sup: 'var(--rh-dusty-red)',
  };
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap:6,
      padding:'5px 9px',
      background:'var(--bg-elevated-2)',
      border:'1px solid var(--border-default)',
      borderRadius:2,
      fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'0.12em',
      textTransform:'uppercase', fontWeight:600, color:'var(--rh-bone-300)',
      lineHeight:1.1,
    }}>
      <span style={{width:5, height:5, borderRadius:'50%', background:colors[type]}}/>
      <span style={{color:'var(--rh-bone-500)', fontSize:8, letterSpacing:'0.22em'}}>{slot}</span>
      <span>{label}</span>
    </span>
  );
}

function LoadoutDetailGun({ gun, caliber }) {
  return (
    <>
      <div style={{display:'grid', gridTemplateColumns:'1fr auto', gap:8}}>
        <div>
          <div className="label-md" style={{color:'var(--rh-bone-500)'}}>Firearm</div>
          <div style={{fontFamily:'var(--font-display)', fontSize:18, color:'var(--fg-1)', letterSpacing:'0.02em', marginTop:3}}>{gun}</div>
          <div className="rh-body-sm" style={{marginTop:4, color:'var(--rh-bone-500)'}}>Caliber · {caliber}</div>
        </div>
        <button className="btn btn-ghost" style={{padding:'6px 10px', fontSize:10}}>Open record →</button>
      </div>
    </>
  );
}

function LoadoutDetailAcc({ accessories }) {
  if (!accessories || !accessories.length) return <div className="rh-body-sm" style={{color:'var(--rh-bone-500)', textAlign:'center', padding:'12px 0'}}>No accessories mounted</div>;
  return (
    <div style={{display:'flex', flexDirection:'column', gap:0}}>
      {accessories.map(a => (
        <div key={a.name} style={{display:'grid', gridTemplateColumns:'80px 1fr', gap:10, padding:'8px 0', borderBottom:'1px solid var(--border-hairline)'}}>
          <span className="label-md" style={{color:'var(--rh-bone-500)'}}>{a.slot}</span>
          <span style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--fg-1)', letterSpacing:'0.02em'}}>{a.name}</span>
        </div>
      ))}
    </div>
  );
}

function LoadoutDetailSup({ suppressor }) {
  if (!suppressor) return (
    <div className="rh-body-sm" style={{color:'var(--rh-bone-500)', textAlign:'center', padding:'12px 0'}}>
      No suppressor on this loadout.
      <div style={{marginTop:8}}>
        <button className="btn btn-ghost" style={{padding:'6px 10px', fontSize:10}}>+ Add suppressor</button>
      </div>
    </div>
  );
  return (
    <>
      <div className="label-md" style={{color:'var(--rh-bone-500)'}}>Suppressor</div>
      <div style={{fontFamily:'var(--font-display)', fontSize:18, color:'var(--fg-1)', letterSpacing:'0.02em', marginTop:3}}>{suppressor.name}</div>
      <div className="rh-body-sm" style={{marginTop:4, color:'var(--rh-bone-500)'}}>Serial · {suppressor.serial}</div>
    </>
  );
}

// ---------- GUNS LIST ----------
// v3.1: grouped by firearm type so the list stays scannable as the user's
// safe grows. Each gun card carries a faint silhouette for instant visual ID.
function GunsList({ go, emptyMode, guns }) {
  const isEmpty = guns !== null && guns !== undefined && guns.length === 0;

  if (isEmpty) return (
    <EmptySectionCTA
      title="No guns yet"
      sub="Start your Roundhouse Record by adding the first gun in your safe."
      cta="Add a gun"
      onClick={()=>go('addgun')}
    />
  );

  if (!guns) return (
    <div style={{padding:'32px 0', textAlign:'center'}}>
      <div className="label-md" style={{color:'var(--rh-bone-500)'}}>Loading…</div>
    </div>
  );

  const typeLabels = {
    pistol:   'Pistols',
    revolver: 'Revolvers',
    ar:       'Rifles · AR',
    bolt:     'Rifles · Bolt-action',
    pcc:      'PCCs · Rimfire',
    shotgun:  'Shotguns',
  };

  // Map DB record → FirearmCard display shape
  const display = guns.map(function(g) {
    var name = g.nickname || (g.manufacturer + ' ' + g.model);
    var configDesc = g.caliber + ' · Stock';
    return {
      id: g.id,
      name: name,
      gunType: g.gunType,
      config: configDesc,
      status: { kind: 'ready', label: 'Ready' },
      rounds: (g.startingRounds || 0).toLocaleString(),
      lastTrip: '—',
      malfunctions: '0',
    };
  });

  const order = ['pistol','revolver','ar','bolt','pcc','shotgun'];
  const grouped = {};
  display.forEach(g => { (grouped[g.gunType] = grouped[g.gunType] || []).push(g); });

  return (
    <>
      <LabelRule more="Sort">{guns.length} gun{guns.length===1?'':'s'}</LabelRule>
      {order.filter(t => grouped[t]).map(t => (
        <div key={t} style={{marginBottom:14}}>
          <div style={{display:'flex', alignItems:'center', gap:8, padding:'8px 0 6px'}}>
            <span className="label-md" style={{color:'var(--rh-bone-500)', fontSize:9}}>{typeLabels[t]}</span>
            <div style={{flex:1, height:1, background:'var(--border-hairline)'}}/>
            <span className="label-md" style={{color:'var(--rh-bone-500)', fontSize:9}}>{grouped[t].length}</span>
          </div>
          <div style={{display:'flex', flexDirection:'column', gap:8}}>
            {grouped[t].map(g => <FirearmCard key={g.id} {...g} onClick={()=>go('gundetail')}/>)}
          </div>
        </div>
      ))}
      <div style={{marginTop:6}}>
        <Button variant="primary" block onClick={()=>go('addgun')} icon={<I.plus s={14}/>}>Add a gun</Button>
      </div>
    </>
  );
}

// ---------- ACCESSORIES LIST ----------
// v4.3: grouped by category. Optics, lights, magazines, triggers, and other
// don't share a list anymore — each category gets its own section header
// with a count, mirroring the gun-list-by-type pattern.
function AccessoriesList({ go, emptyMode }) {
  if (emptyMode) return (
    <EmptySectionCTA
      title="No accessories yet"
      sub="Optics, lights, magazines — anything you can attach to a gun."
      cta="Add an accessory"
      onClick={()=>go('addaccessory')}
    />
  );

  // Accessories are ATTACH/DETACH items — they live and move between guns.
  // Modifications (triggers, stocks, sights, grips, magwells, barrels) are
  // semi-permanent and gun-specific — they live on Modifications, not here.
  const accessories = [
    { brand:'Trijicon',      model:'RMR Type 2',          category:'OPTIC',    mountedOn:'Glock 19 Gen5' },
    { brand:'Sig Sauer',     model:'Romeo Zero',          category:'OPTIC',    mountedOn:'SIG P365 XL' },
    { brand:'Primary Arms',  model:'GLx 1-6× LPVO',       category:'OPTIC',    mountedOn:'11.5″ AR-15' },
    { brand:'Holosun',       model:'507K',                category:'OPTIC',    mountedOn:null },
    { brand:'Streamlight',   model:'TLR-7A',              category:'LIGHT',    mountedOn:'Glock 19 Gen5' },
    { brand:'Surefire',      model:'X300U-A',             category:'LIGHT',    mountedOn:null },
    { brand:'Magpul',        model:'PMAG 30-rd',          category:'MAGAZINE', mountedOn:null },
    { brand:'Magpul',        model:'PMAG 15-rd',          category:'MAGAZINE', mountedOn:'Glock 19 Gen5' },
    { brand:'T.Rex Arms',    model:'Sidecar AIWB',        category:'HOLSTER',  mountedOn:null },
  ];

  const categoryConfig = {
    OPTIC:    { label:'Optics',      accent:'var(--rh-bone)' },
    LIGHT:    { label:'Lights',      accent:'var(--rh-brass-400)' },
    MAGAZINE: { label:'Magazines',   accent:'var(--rh-bone-500)' },
    HOLSTER:  { label:'Holsters',    accent:'var(--rh-steel-400)' },
    OTHER:    { label:'Other',       accent:'var(--rh-bone-500)' },
  };

  const order = ['OPTIC','LIGHT','MAGAZINE','HOLSTER','OTHER'];
  const grouped = {};
  accessories.forEach(a => { (grouped[a.category] = grouped[a.category] || []).push(a); });

  return (
    <>
      <LabelRule more="Sort">{accessories.length} accessories</LabelRule>
      {order.filter(c => grouped[c]).map(c => {
        const cfg = categoryConfig[c] || categoryConfig.OTHER;
        return (
          <div key={c} style={{marginBottom:16}}>
            <div style={{display:'flex', alignItems:'center', gap:8, padding:'8px 0 8px'}}>
              <span style={{width:7, height:7, borderRadius:'50%', background:cfg.accent, display:'inline-block'}}/>
              <span className="label-md" style={{color:'var(--rh-bone-300)', fontSize:10, letterSpacing:'0.18em'}}>{cfg.label}</span>
              <div style={{flex:1, height:1, background:'var(--border-hairline)'}}/>
              <span className="label-md" style={{color:'var(--rh-bone-500)', fontSize:9}}>{grouped[c].length}</span>
            </div>
            <div style={{display:'flex', flexDirection:'column', gap:8}}>
              {grouped[c].map(a => <AccessoryRow key={a.brand+a.model} {...a}/>)}
            </div>
          </div>
        );
      })}
      <div style={{marginTop:6}}>
        <Button variant="primary" block onClick={()=>go('addaccessory')} icon={<I.plus s={14}/>}>Add an accessory</Button>
      </div>
    </>
  );
}

function AccessoryRow({ brand, model, category, mountedOn }) {
  return (
    <div className="card" style={{marginBottom:8, cursor:'pointer'}}>
      <div style={{display:'grid', gridTemplateColumns:'auto 1fr auto', gap:12, alignItems:'center'}}>
        <div style={{width:36, height:36, background:'var(--rh-obsidian-700)', border:'1px solid var(--border-hairline)', display:'flex', alignItems:'center', justifyContent:'center'}}>
          <span className="label-md" style={{fontSize:7, color:'var(--rh-brass-400)'}}>{category.slice(0,3)}</span>
        </div>
        <div>
          <div style={{fontFamily:'var(--font-display)', fontSize:18, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1}}>{brand} · {model}</div>
          <div className="label-md" style={{marginTop:4, color:mountedOn?'#A6C293':'var(--rh-bone-500)'}}>
            {mountedOn ? `Mounted · ${mountedOn}` : 'Unmounted'}
          </div>
        </div>
        <X.fwd s={14}/>
      </div>
    </div>
  );
}

// ---------- SUPPRESSORS LIST ----------
function SuppressorsList({ go, emptyMode }) {
  if (emptyMode) return (
    <EmptySectionCTA
      title="No suppressors yet"
      sub="NFA paperwork and round counts tracked separately for each can."
      cta="Add a suppressor"
      onClick={()=>go('addsuppressor')}
    />
  );

  const suppressors = [
    { brand:'SilencerCo', model:'Omega 9K',    caliber:'9mm',   serial:'OM9-44218', rounds:1420, nfa:'Approved',     mountedOn:'Glock 19 Gen5' },
    { brand:'Dead Air',   model:'Sandman-S',   caliber:'7.62',  serial:'DA-77910',  rounds:380,  nfa:'In progress',  mountedOn:null },
  ];

  return (
    <>
      <LabelRule more="Sort">{suppressors.length} suppressors</LabelRule>
      {suppressors.map(s => <SuppressorRow key={s.serial} {...s} onClick={()=>go('suppressordetail')}/>)}
      <div style={{marginTop:14}}>
        <Button variant="primary" block onClick={()=>go('addsuppressor')} icon={<I.plus s={14}/>}>Add a suppressor</Button>
      </div>
    </>
  );
}

function SuppressorRow({ brand, model, caliber, serial, rounds, nfa, mountedOn, onClick }) {
  return (
    <div className="card" style={{marginBottom:8, cursor:'pointer'}} onClick={onClick}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:8}}>
        <div>
          <div style={{fontFamily:'var(--font-display)', fontSize:22, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1}}>{brand} · {model}</div>
          <div className="label-md" style={{marginTop:4, color:'var(--rh-brass-400)'}}>{caliber} · {serial}</div>
        </div>
        <StatusPill kind={nfa==='Approved'?'verified':'due'}>{nfa}</StatusPill>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, borderTop:'1px solid var(--border-hairline)', paddingTop:10, marginTop:10}}>
        <Stat v={rounds.toLocaleString()} k="Total Rounds"/>
        <Stat v={mountedOn || '—'} k="Mounted On" color={mountedOn?'#A6C293':'var(--rh-bone-500)'}/>
      </div>
    </div>
  );
}

// ---------- LOADOUTS LIST ----------
function LoadoutsList({ go, emptyMode }) {
  if (emptyMode) return (
    <EmptySectionCTA
      title="No loadouts yet"
      sub="A loadout is a gun + accessories + suppressor you bring to the range."
      cta="Create a loadout"
      onClick={()=>go('editloadout')}
    />
  );

  const loadouts = [
    { name:'Glock 19 EDC',     gun:'Glock 19 Gen5', pieces:['RMR','TLR-7A'],          suppressor:null,         ammo:'9mm · Training · 115gr' },
    { name:'Glock 19 Range',   gun:'Glock 19 Gen5', pieces:['RMR','TLR-7A'],          suppressor:'Omega 9K',   ammo:'9mm · Training · 115gr' },
    { name:'AR Defense',       gun:'11.5″ AR-15',   pieces:['LPVO','BCM stock'],      suppressor:null,         ammo:'5.56 · Defensive · 62gr' },
    { name:'P365 Carry',       gun:'SIG P365 XL',   pieces:['Romeo Zero'],            suppressor:null,         ammo:'9mm · Defensive · 124gr' },
  ];

  return (
    <>
      <LabelRule more="Sort">{loadouts.length} loadouts</LabelRule>
      {loadouts.map(l => <LoadoutRow key={l.name} {...l} onClick={()=>go('editloadout')}/>)}
      <div style={{marginTop:14}}>
        <Button variant="primary" block onClick={()=>go('editloadout')} icon={<I.plus s={14}/>}>Create a loadout</Button>
      </div>
    </>
  );
}

function LoadoutRow({ name, gun, pieces, suppressor, ammo, onClick }) {
  return (
    <div className="card" style={{marginBottom:8, cursor:'pointer'}} onClick={onClick}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:8}}>
        <div style={{flex:1}}>
          <div style={{fontFamily:'var(--font-display)', fontSize:20, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1}}>{name}</div>
          <div className="label-md" style={{marginTop:4, color:'var(--rh-brass-400)'}}>{gun}</div>
        </div>
        {suppressor && <StatusPill kind="updated">Suppressed</StatusPill>}
      </div>
      <div style={{display:'flex', flexWrap:'wrap', gap:6, marginTop:10}}>
        {pieces.map(p => <Pill key={p} on>{p}</Pill>)}
        {suppressor && <Pill on>{suppressor}</Pill>}
      </div>
      <div style={{borderTop:'1px solid var(--border-hairline)', marginTop:10, paddingTop:10, display:'flex', justifyContent:'space-between', alignItems:'center'}}>
        <span className="label-md">Default ammo</span>
        <span style={{fontFamily:'var(--font-display)', fontSize:13, color:'var(--rh-bone-300)', letterSpacing:'0.02em'}}>{ammo}</span>
      </div>
    </div>
  );
}

// ---------- GUN BRAND / MODEL LOOKUP ----------
const GUN_BRANDS = {
  'Glock':                 { type:'pistol',   models:['G17','G19','G19X','G20','G21','G22','G23','G26','G27','G34','G43','G43X','G45','G48'] },
  'Smith & Wesson':        { type:'pistol',   models:['M&P9 2.0','M&P Shield','M&P Shield Plus','M&P Shield EZ','686','629','642','M&P15','M&P10','SW1911'] },
  'Sig Sauer':             { type:'pistol',   models:['P226','P229','P238','P320','P320 Compact','P320 X-Five','P365','P365X','P365XL','P365-380','P938','MCX','MPX'] },
  'Ruger':                 { type:'pistol',   models:['LCP','LCP II','LCP Max','LC9s','GP100','SP101','Redhawk','Security-9','PC Carbine','10/22','AR-556','American'] },
  'Springfield Armory':    { type:'pistol',   models:['XD','XDM','XD-S','Hellcat','Hellcat Pro','Hellcat RDP','SA-35','M1A','Saint'] },
  'Beretta':               { type:'pistol',   models:['92FS','M9A3','APX','APX A1','92X','CX4 Storm','PX4 Storm'] },
  'CZ':                    { type:'pistol',   models:['CZ 75','CZ 75 SP-01','P-07','P-09','P-10 C','P-10 F','Scorpion EVO 3'] },
  'Walther':               { type:'pistol',   models:['PPQ M2','PDP','PDP Compact','P99','PPS M2','CCP M2'] },
  'Taurus':                { type:'pistol',   models:['G3','G3C','G2C','Spectrum','1911','692','856'] },
  'Heckler & Koch':        { type:'pistol',   models:['VP9','VP40','VP9SK','USP','P30','HK45','P2000','SFP9'] },
  'Kimber':                { type:'pistol',   models:['Custom II','Pro Carry II','Ultra Carry II','Micro 9','Rapide'] },
  'Colt':                  { type:'pistol',   models:['1911','Gold Cup','Commander','Defender','Python','Anaconda','King Cobra'] },
  'FN':                    { type:'pistol',   models:['FNX-45','FNX-9','FN 509','FN 509 Compact','FN 509 LS Edge','FiveSeven','FN SCAR 16S','FN SCAR 17S','FN 15'] },
  'Canik':                 { type:'pistol',   models:['TP9SF','TP9SA','TP9SFX','Mete SFT','Mete SFx','TTI Combat'] },
  'Staccato':              { type:'pistol',   models:['C','C2','P','P DUO','XC','2011'] },
  'Wilson Combat':         { type:'pistol',   models:['EDC X9','SFX9','CQB','Tactical Carry','Protector'] },
  'Daniel Defense':        { type:'ar',       models:['DDM4 V7','DDM4 V11','DDM4 MK18','DDM4 PDW','Delta 5'] },
  'Palmetto State Armory': { type:'ar',       models:['PA-15','PA-10','Dagger','AK-P'] },
  'Aero Precision':        { type:'ar',       models:['M4E1','M5','M4E1 Enhanced','EPC-9'] },
  'BCM':                   { type:'ar',       models:['RECCE-14','RECCE-16','RECCE-11','Jack Carbine'] },
  'Mossberg':              { type:'shotgun',  models:['500','590','590A1','590 Shockwave','940 JM Pro','MVP','Patriot'] },
  'Remington':             { type:'shotgun',  models:['870','870 Express','870 Wingmaster','Model 700','Model 783','RP9'] },
  'Kel-Tec':               { type:'pcc',      models:['PF-9','P-11','PMR-30','Sub-2000','KSG','RFB','CP33'] },
};

// ---------- ADD GUN FLOW ----------
function AddGun({ go }) {
  const [manufacturer, setManufacturer] = React.useState('');
  const [model, setModel] = React.useState('');
  const [caliber, setCaliber] = React.useState('');
  const [gunType, setGunType] = React.useState('');
  const [nickname, setNickname] = React.useState('');
  const [condition, setCondition] = React.useState('new');
  const [startingRounds, setStartingRounds] = React.useState('');
  const [saving, setSaving] = React.useState(false);
  const [confirmedBrand, setConfirmedBrand] = React.useState(null);

  function findBrand(val) {
    var key = Object.keys(GUN_BRANDS).find(function(k) {
      return k.toLowerCase() === (val || '').toLowerCase();
    });
    return key ? GUN_BRANDS[key] : null;
  }

  function handleManufacturerSelect(val) {
    setManufacturer(val);
    setModel('');
    var brand = findBrand(val);
    setConfirmedBrand(brand);
    if (brand && !gunType) setGunType(brand.type);
  }

  function handleSave() {
    if (!canSave || saving) return;
    setSaving(true);
    var gun = {
      manufacturer: manufacturer,
      model: model,
      nickname: nickname,
      caliber: caliber,
      gunType: gunType,
      condition: condition,
      startingRounds: parseInt(startingRounds) || 0,
      config: {
        accessories: { optic: null, light: null, magazine: null, holster: null },
        modifications: [],
        suppressor: null,
      },
      defaultAmmo: { type: 'Training', grain: '' },
      serial: '',
      notes: '',
      createdAt: new Date().toISOString(),
    };
    window.rhDB.saveGun(gun).then(function() { go('guns'); });
  }

  const calibers = ['9mm','.380 ACP','.45 ACP','.40 S&W','5.56','7.62','.308','10mm','.357 Mag','.44 Mag','.22LR','12ga','Other'];
  const gunTypes = [
    {id:'pistol',   label:'Pistol'},
    {id:'revolver', label:'Revolver'},
    {id:'ar',       label:'Rifle · AR'},
    {id:'bolt',     label:'Rifle · Bolt'},
    {id:'pcc',      label:'PCC · Rimfire'},
    {id:'shotgun',  label:'Shotgun'},
  ];

  const canSave = manufacturer && model && caliber && gunType;
  const Silhouette = gunType && GunSil[gunType];

  return (
    <>
      <TopBar title="Add a gun"/>
      <div className="screen">
        <BackRow to="gear" label="Gear" go={go}/>
        <div className="screen-hero" style={{paddingTop:0}}>
          <div className="eyebrow">Gear · Add a gun</div>
          <h1 className="hero-title">What are you <span className="red">adding?</span></h1>
          <div className="hero-sub">Three fields gets you to value. The rest can be filled in later.</div>
        </div>

        <LabelRule>Identity</LabelRule>
        <div className="card">
          <AutocompleteRow
            label="Manufacturer"
            placeholder="e.g. Glock"
            value={manufacturer}
            onChange={v=>{ setManufacturer(v); if (!v) setConfirmedBrand(null); }}
            onSelect={handleManufacturerSelect}
            suggestions={Object.keys(GUN_BRANDS)}
            listId="rh-manufacturers"
          />
          <FieldRow label="Model" placeholder="e.g. 19 Gen5" value={model} onChange={v=>{ setModel(v); }} />
          <FieldRow label="Nickname (optional)" placeholder="e.g. Range G19" value={nickname} onChange={setNickname} last/>
        </div>

        {/* Model pills — shown only after user explicitly picks a brand from datalist */}
        {confirmedBrand && (
          <>
            <div className="rh-body-sm" style={{padding:'4px 4px 6px', color:'var(--rh-bone-500)', fontSize:11}}>
              Quick pick · {manufacturer} models
            </div>
            <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
              {confirmedBrand.models.map(m => (
                <Pill key={m} on={model===m} onClick={()=>setModel(m)}>{m}</Pill>
              ))}
            </div>
          </>
        )}

        <LabelRule>Type</LabelRule>
        <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
          {gunTypes.map(t => <Pill key={t.id} on={gunType===t.id} onClick={()=>setGunType(t.id)}>{t.label}</Pill>)}
        </div>
        {Silhouette && (
          <div style={{marginTop:12, padding:'14px 10px', background:'var(--bg-elevated-1)', border:'1px solid var(--border-default)', borderRadius:2, display:'flex', justifyContent:'center', color:'var(--rh-bone)'}}>
            <Silhouette w={gunType==='pistol' || gunType==='revolver' ? 140 : 220}/>
          </div>
        )}

        <LabelRule>Caliber</LabelRule>
        <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
          {calibers.map(c => <Pill key={c} on={caliber===c} onClick={()=>setCaliber(c)}>{c}</Pill>)}
        </div>

        <LabelRule>Condition at acquisition</LabelRule>
        <div style={{display:'flex', gap:6}}>
          {[
            {v:'new',     label:'New'},
            {v:'used',    label:'Used'},
            {v:'unknown', label:'Unknown'},
          ].map(c => <Pill key={c.v} on={condition===c.v} onClick={()=>setCondition(c.v)}>{c.label}</Pill>)}
        </div>

        {condition==='used' && (
          <div className="card" style={{marginTop:10, background:'transparent', borderStyle:'dashed', borderColor:'var(--rh-brass-tint-32)'}}>
            <div className="label-md" style={{color:'var(--rh-brass-400)'}}>Starting round count</div>
            <div className="rh-body-sm" style={{marginTop:4, color:'var(--rh-bone-300)'}}>If you know roughly how many rounds went through it before you got it, enter that here. Maintenance countdowns will start from this number.</div>
            <div style={{marginTop:10, display:'grid', gridTemplateColumns:'1fr auto', gap:8, alignItems:'center'}}>
              <input
                type="number"
                placeholder="e.g. 2400"
                value={startingRounds}
                onChange={e=>setStartingRounds(e.target.value)}
                style={{background:'var(--bg-elevated-2)', border:'1px solid var(--border-default)', color:'var(--fg-1)', padding:'10px', borderRadius:2, fontFamily:'var(--font-display)', fontSize:18, letterSpacing:'0.02em'}}/>
              <span className="label-md">Rounds</span>
            </div>
          </div>
        )}

        <LabelRule>Photo (optional)</LabelRule>
        <div className="wire-firearm" style={{height:84, cursor:'pointer'}}>
          <span style={{position:'absolute', bottom:6, right:8, fontFamily:'var(--font-ui)', fontSize:8, letterSpacing:'0.24em', color:'var(--rh-bone-500)', fontWeight:600}}>+ TAP TO ADD</span>
        </div>

        <div style={{marginTop:18}}>
          <Button variant="primary" block onClick={handleSave} icon={canSave && !saving ? <I.check s={14}/> : null}>
            {saving ? 'Saving…' : canSave ? 'Save gun' : 'Manufacturer, model, caliber, type required'}
          </Button>
          <div className="rh-body-sm" style={{textAlign:'center', marginTop:10, color:'var(--rh-bone-500)'}}>
            Default maintenance rules will be created automatically.
          </div>
        </div>
      </div>
    </>
  );
}

function FieldRow({ label, placeholder, value, onChange, last }) {
  return (
    <div style={{padding:'8px 0', borderBottom: last ? 'none' : '1px solid var(--border-hairline)'}}>
      <div className="label-md" style={{color:'var(--rh-bone-500)'}}>{label}</div>
      <input
        value={value}
        onChange={e=>onChange(e.target.value)}
        placeholder={placeholder}
        style={{width:'100%', background:'transparent', border:0, color:'var(--fg-1)', padding:'4px 0', fontFamily:'var(--font-display)', fontSize:18, letterSpacing:'0.02em', outline:'none', marginTop:2}}/>
    </div>
  );
}

function AutocompleteRow({ label, placeholder, value, onChange, onSelect, suggestions, listId }) {
  return (
    <div style={{padding:'8px 0', borderBottom:'1px solid var(--border-hairline)'}}>
      <div className="label-md" style={{color:'var(--rh-bone-500)'}}>{label}</div>
      <input
        value={value}
        onChange={e=>{ onChange(e.target.value); if (onSelect && suggestions.includes(e.target.value)) onSelect(e.target.value); }}
        placeholder={placeholder}
        list={listId}
        autoComplete="on"
        style={{width:'100%', background:'transparent', border:0, color:'var(--fg-1)', padding:'4px 0', fontFamily:'var(--font-display)', fontSize:18, letterSpacing:'0.02em', outline:'none', marginTop:2}}
      />
      {listId && (
        <datalist id={listId}>
          {suggestions.map(s => <option key={s} value={s}/>)}
        </datalist>
      )}
    </div>
  );
}

// ---------- STUBS: Add Accessory / Add Suppressor / Edit Loadout ----------
function AddAccessory({ go }) {
  return (
    <StubScreen title="Add an accessory" backTo="gear" go={go}>
      <p className="rh-body-sm" style={{color:'var(--rh-bone-300)'}}>
        Full form coming next pass: brand (autocomplete) + model + category + photo + optional purchase info → save.
      </p>
      <p className="rh-body-sm" style={{color:'var(--rh-bone-300)', marginTop:8}}>
        After save, optional CTA: "Mount on a gun" → pick which gun this accessory is currently on.
      </p>
    </StubScreen>
  );
}

function AddSuppressor({ go }) {
  return (
    <StubScreen title="Add a suppressor" backTo="gear" go={go}>
      <p className="rh-body-sm" style={{color:'var(--rh-bone-300)'}}>
        Full form coming next pass: brand + model + caliber + serial + NFA form status + tax stamp date + photo.
      </p>
      <p className="rh-body-sm" style={{color:'var(--rh-bone-300)', marginTop:8}}>
        Suppressors get their own Service Record like guns. Round count accumulates whenever a session marks rounds as suppressed.
      </p>
    </StubScreen>
  );
}

// ---------- LOADOUT EDITOR ----------
// v3.2: real editor. Pick gun → attach accessories by slot → attach optional
// suppressor → set default ammo type → name + save. Caliber is inferred
// from the gun (read-only). Saving creates a new loadout version per the
// config=loadout model — editing preserves history.
function EditLoadout({ go }) {
  const [gun, setGun] = React.useState({name:'Glock 19 Gen5', gunType:'pistol', caliber:'9mm'});
  const [slots, setSlots] = React.useState({
    OPTIC: {name:'Trijicon RMR Type 2'},
    LIGHT: {name:'Streamlight TLR-7A'},
    TRIGGER: null,
    GRIP: null,
  });
  const [suppressor, setSuppressor] = React.useState(null);
  const [ammo, setAmmo] = React.useState({type:'Training', grain:'115', brand:null});
  const [name, setName] = React.useState('Glock 19');

  const Silhouette = GunSil[gun.gunType] || GunSil.pistol;

  // Inventory pools (sample data)
  const guns = [
    {name:'Glock 19 Gen5', gunType:'pistol', caliber:'9mm'},
    {name:'SIG P365 XL',   gunType:'pistol', caliber:'9mm'},
    {name:'Beretta 92FS',  gunType:'pistol', caliber:'9mm'},
    {name:'11.5″ AR-15',   gunType:'ar',     caliber:'5.56'},
    {name:'Ruger 10/22',   gunType:'pcc',    caliber:'.22LR'},
  ];
  const accInventory = {
    OPTIC: ['Trijicon RMR Type 2','Sig Romeo Zero','Holosun 507K','Primary Arms GLx 1-6× LPVO'],
    LIGHT: ['Streamlight TLR-7A','Surefire X300U','Modlite PL350'],
    TRIGGER: ['Apex Trigger','Overwatch Precision','Stock'],
    GRIP: ['Magpul MOE','BCM Mod 3','Stock'],
  };
  const suppressors = [
    {name:'SilencerCo Omega 9K', caliber:'9mm'},
    {name:'Dead Air Sandman-S',  caliber:'7.62'},
  ];

  // Ammo options filtered by gun's caliber
  const ammoTypes = ['Training','Defensive','Match','Other'];
  const grainsByCaliber = {
    '9mm':   ['115','124','147'],
    '.45 ACP': ['185','200','230'],
    '5.56':  ['55','62','69','77'],
    '.22LR': ['36','40'],
  };

  const setSlot = (slot, val) => setSlots(s => ({...s, [slot]: s[slot] && s[slot].name===val ? null : (val ? {name:val} : null)}));

  return (
    <>
      <TopBar title="Loadout"/>
      <div className="screen">
        <BackRow to="gear" label="Gear" go={go}/>
        <CollapsingHero
          eyebrow="Gear · Edit loadout"
          headline={name || 'New loadout'}
          summary={`${gun.name} · ${gun.caliber}${suppressor ? ' · suppressed' : ''}`}
          right={<TourButton/>}
        />

        {/* Silhouette preview */}
        <div className="card brass" style={{padding:'14px', display:'flex', flexDirection:'column', alignItems:'center'}}>
          <div style={{color:'var(--rh-bone)', opacity:0.85}}>
            <Silhouette w={gun.gunType==='pistol' ? 160 : 240}/>
          </div>
          <div style={{marginTop:8, fontFamily:'var(--font-ui)', fontSize:11, color:'var(--rh-bone-300)', letterSpacing:'0.18em', textTransform:'uppercase', fontWeight:600}}>
            {gun.name} · {gun.caliber}
          </div>
        </div>

        {/* Name */}
        <LabelRule>Name</LabelRule>
        <div className="card">
          <input
            value={name}
            onChange={e=>setName(e.target.value)}
            placeholder="e.g. Glock 19 EDC"
            style={{width:'100%', background:'transparent', border:0, color:'var(--fg-1)', padding:'4px 0', fontFamily:'var(--font-display)', fontSize:20, letterSpacing:'0.02em', outline:'none'}}/>
        </div>

        {/* Gun */}
        <LabelRule>Gun</LabelRule>
        <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
          {guns.map(g => <Pill key={g.name} on={gun.name===g.name} onClick={()=>setGun(g)}>{g.name}</Pill>)}
        </div>

        {/* Accessories — slot-by-slot */}
        <LabelRule>Accessories · by slot</LabelRule>
        <div style={{display:'flex', flexDirection:'column', gap:10}}>
          {Object.keys(accInventory).map(slot => (
            <div key={slot} className="card" style={{padding:'10px 12px'}}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8}}>
                <span className="label-md" style={{color:'var(--rh-bone-500)'}}>{slot}</span>
                <span className="label-md" style={{color: slots[slot] ? '#A6C293' : 'var(--rh-bone-500)', fontSize:8}}>{slots[slot] ? 'MOUNTED' : 'EMPTY'}</span>
              </div>
              <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
                {accInventory[slot].map(a => (
                  <Pill key={a} on={slots[slot] && slots[slot].name===a} onClick={()=>setSlot(slot, a)}>{a}</Pill>
                ))}
              </div>
            </div>
          ))}
        </div>

        {/* Suppressor */}
        <LabelRule>Suppressor (optional)</LabelRule>
        <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
          <Pill on={!suppressor} onClick={()=>setSuppressor(null)}>None</Pill>
          {suppressors.filter(s => s.caliber===gun.caliber || (gun.caliber==='9mm' && s.caliber==='9mm')).map(s => (
            <Pill key={s.name} on={suppressor && suppressor.name===s.name} onClick={()=>setSuppressor(s)}>{s.name}</Pill>
          ))}
        </div>

        {/* Default ammo — caliber locked to gun */}
        <LabelRule>Default ammo</LabelRule>
        <div className="card" style={{padding:'12px 14px'}}>
          <div className="label-md" style={{fontSize:8, color:'var(--rh-bone-500)'}}>Caliber · from gun</div>
          <div style={{fontFamily:'var(--font-display)', fontSize:16, color:'var(--fg-1)', letterSpacing:'0.02em', marginTop:3}}>{gun.caliber}</div>

          <div style={{height:1, background:'var(--border-hairline)', margin:'10px 0'}}/>

          <div className="label-md" style={{fontSize:8, color:'var(--rh-bone-500)'}}>Use category</div>
          <div style={{display:'flex', flexWrap:'wrap', gap:6, marginTop:6}}>
            {ammoTypes.map(t => <Pill key={t} on={ammo.type===t} onClick={()=>setAmmo(a=>({...a, type:t}))}>{t}</Pill>)}
          </div>

          <div style={{height:1, background:'var(--border-hairline)', margin:'10px 0'}}/>

          <div className="label-md" style={{fontSize:8, color:'var(--rh-bone-500)'}}>Grain</div>
          <div style={{display:'flex', flexWrap:'wrap', gap:6, marginTop:6}}>
            {(grainsByCaliber[gun.caliber] || ['—']).map(g => (
              <Pill key={g} on={ammo.grain===g} onClick={()=>setAmmo(a=>({...a, grain:g}))}>{g}gr</Pill>
            ))}
          </div>

          <div style={{height:1, background:'var(--border-hairline)', margin:'10px 0'}}/>

          <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline'}}>
            <div>
              <div className="label-md" style={{fontSize:8, color:'var(--rh-brass-400)'}}>RESULT</div>
              <div style={{fontFamily:'var(--font-display)', fontSize:16, color:'var(--fg-1)', letterSpacing:'0.02em', marginTop:3}}>
                {gun.caliber} · {ammo.type} · {ammo.grain}gr
              </div>
            </div>
            <span className="label-md" style={{color:'var(--rh-bone-500)', fontSize:8}}>Brand optional</span>
          </div>
        </div>

        <div className="card" style={{marginTop:12, background:'transparent', borderStyle:'dashed', borderColor:'var(--rh-brass-tint-32)', padding:'10px 12px'}}>
          <div className="label-md" style={{color:'var(--rh-brass-400)'}}>How edits work</div>
          <div className="rh-body-sm" style={{marginTop:6, color:'var(--rh-bone-300)'}}>Saving creates a new loadout version. Old versions stay in history so each gun's Service Record knows what was on it during past sessions.</div>
        </div>

        <div style={{marginTop:16, display:'grid', gridTemplateColumns:'1fr 2fr', gap:10}}>
          <Button variant="secondary" block onClick={()=>go('gear')}>Cancel</Button>
          <Button variant="primary" block onClick={()=>go('gear')} icon={<I.check s={14}/>}>Save loadout</Button>
        </div>
      </div>
    </>
  );
}

// ---------- Shared helpers ----------
function EmptySectionCTA({ title, sub, cta, onClick }) {
  return (
    <div style={{padding:'48px 16px 24px', textAlign:'center'}}>
      <div style={{width:64, height:64, margin:'0 auto 16px', border:'1px dashed var(--rh-brass-tint-32)', borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--rh-brass-400)'}}>
        <I.plus s={20}/>
      </div>
      <div style={{fontFamily:'var(--font-display)', fontSize:22, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1}}>{title}</div>
      <div className="rh-body-sm" style={{marginTop:8, maxWidth:280, marginLeft:'auto', marginRight:'auto', color:'var(--rh-bone-300)'}}>{sub}</div>
      <div style={{marginTop:20}}>
        <Button variant="primary" onClick={onClick} icon={<I.plus s={14}/>}>{cta}</Button>
      </div>
    </div>
  );
}

function StubScreen({ title, backTo, go, children }) {
  return (
    <>
      <TopBar title={title}/>
      <div className="screen">
        <BackRow to={backTo} label="Back" go={go}/>
        <div className="screen-hero" style={{paddingTop:0}}>
          <div className="eyebrow">Stub · next pass</div>
          <h1 className="hero-title" style={{fontSize:34}}>{title}</h1>
        </div>
        <div className="card" style={{marginTop:8}}>
          {children}
        </div>
        <div style={{marginTop:16}}>
          <Button variant="secondary" block onClick={()=>go(backTo)}>Back to Gear</Button>
        </div>
      </div>
    </>
  );
}

window.Gear = Gear;
window.GunsPage = GunsPage;
window.GunDetail = GunDetail;
window.GunConfigEditor = GunConfigEditor;
window.AccessoriesPage = AccessoriesPage;
window.SuppressorsPage = SuppressorsPage;
window.ModificationsPage = ModificationsPage;
window.AddGun = AddGun;
window.AddAccessory = AddAccessory;
window.AddSuppressor = AddSuppressor;
