/* Roundhouse Record — Rings personality + Firearm Detail.
   Default record variant: segmented pillar rings + completeness. */

function Record({ go, emptyMode }) {
  const [reorder, setReorder] = React.useState(false);
  if (emptyMode) return <RecordEmpty go={go}/>;
  return (
    <>
      <TopBar title="Record"/>
      <div className="screen">
        <CollapsingHero
          eyebrow="The living record behind your setup"
          headline="Record"
          summary="24,318 rounds · 142 sessions · since Nov '23"
          right={
            <div style={{display:'flex', gap:6, alignItems:'center'}}>
              <ReorderButton on={reorder} onToggle={()=>setReorder(!reorder)}/>
              <TourButton onClick={()=>window.__rhTour && window.__rhTour('record')}/>
            </div>
          }
        />

        {/* Headline summary — always at top, not reorderable */}
        <div className="card brass" style={{marginTop:6, padding:14, display:'grid', gridTemplateColumns:'1fr 1fr 1fr 1fr', gap:0}}>
          <SummaryStat v="24,318" k="Rounds"/>
          <SummaryStat v="142"    k="Sessions"/>
          <SummaryStat v="538"    k="Days"/>
          <SummaryStat v="$3,247" k="Spend"    muted last/>
        </div>

        {/* Reorderable middle sections — controlled by parent's reorder state.
            Customize trigger lives in the CollapsingHero right slot. */}
        <ReorderableSections
          editMode={reorder}
          onExit={(action)=>setReorder(action==='open' ? true : false)}
          defaultOrder={['protect','gallery','goals','milestones']}
          sectionLabels={{
            protect:'PROTECT ENTRY',
            gallery:'SERVICE RECORDS',
            goals:'TRAINING GOALS',
            milestones:'MILESTONES',
          }}
          renderers={{
            protect: () => <RecordProtectEntry go={go}/>,
            gallery: () => <RecordGallery go={go}/>,
            goals: () => <RecordGoals/>,
            milestones: () => <RecordMilestones/>,
          }}
        />

        <div style={{marginTop:14, display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
          <Button variant="secondary" block icon={<X.upload s={12}/>}>Export Record</Button>
          <Button variant="ghost" block onClick={()=>go('gear')} icon={<X.plus2 s={12}/>}>Manage gear</Button>
        </div>
      </div>
    </>
  );
}

// ---------- Record section subcomponents (so reorderable) ----------
function RecordProtectEntry({ go }) {
  return (
    <div className="card brass" style={{marginTop:10, display:'flex', justifyContent:'space-between', alignItems:'center', gap:10, cursor:'pointer'}} onClick={()=>go('protect')}>
      <div style={{display:'flex', alignItems:'center', gap:12}}>
        <div style={{width:38, height:38, borderRadius:2, background:'var(--rh-obsidian-700)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--rh-dusty-red)'}}>
          <I.shield s={20}/>
        </div>
        <div>
          <div style={{fontFamily:'var(--font-display)', fontSize:18, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1}}>Open Protect Vault</div>
          <div className="label-md" style={{marginTop:4, color:'var(--rh-bone-500)'}}>65% claim-ready · 2 gaps</div>
        </div>
      </div>
      <X.fwd s={16}/>
    </div>
  );
}

function RecordGoals() {
  return (
    <>
      <div style={{display:'flex', alignItems:'baseline', gap:10, margin:'18px 0 8px'}}>
        <div className="label-md" style={{whiteSpace:'nowrap'}}>Training goals · 2 active</div>
        <div style={{flex:1, height:1, background:'var(--border-hairline)'}}/>
        <button
          onClick={()=>window.__rhGo && window.__rhGo('goalslibrary')}
          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}}>
          Library →
        </button>
      </div>
      <div style={{display:'flex', flexDirection:'column', gap:8}}>
        <GoalCard
          title="Sub-2s draw to first shot"
          sub="Consistent across 5 consecutive sessions"
          progress={73}
          sessions={11}
          lastWorked="Apr 14 · 250 rds"
          status="active"
        />
        <GoalCard
          title="1.5s split times at 7yd"
          sub="Bill Drill cadence"
          progress={41}
          sessions={7}
          lastWorked="Apr 02 · 180 rds"
          status="active"
        />
        <GoalCard
          title="Zero P365 at 25yd · retain through 500 rds"
          sub="Romeo Zero · POI tracking"
          progress={100}
          sessions={4}
          lastWorked="Feb 28 · achieved"
          status="achieved"
        />
      </div>
    </>
  );
}

function RecordGallery({ go }) {
  return (
    <>
      <SectionTitle dot="var(--rh-bone)"       label="Guns"        count={5}/>
      <FirearmCard name="Glock 19 Gen5" gunType="pistol" config="9mm · RMR · TLR-7A" status={{kind:'ready',label:'Ready'}} rounds="3,142" lastTrip="14d" malfunctions="0" onClick={()=>go('firearm')}/>
      <FirearmCard name="SIG P365 XL"   gunType="pistol" config="9mm · Romeo Zero"    status={{kind:'due',label:'Due Soon'}} rounds="1,247" lastTrip="21d" malfunctions="3" onClick={()=>go('firearm')}/>
      <FirearmCard name="11.5″ AR-15"   gunType="ar"     config="5.56 · LPVO · BCM"  status={{kind:'ready',label:'Ready'}} rounds="2,418" lastTrip="2d" malfunctions="1" onClick={()=>go('firearm')}/>
      <FirearmCard name="Ruger 10/22"   gunType="pcc"    config=".22LR · Iron sights" status={{kind:'ready',label:'Ready'}} rounds="856" lastTrip="34d" malfunctions="2" onClick={()=>go('firearm')}/>
      <FirearmCard name="Beretta 92FS"  gunType="pistol" config="9mm · Stock"         status={{kind:'ready',label:'Ready'}} rounds="312" lastTrip="3mo" malfunctions="0" onClick={()=>go('firearm')}/>

      <SectionTitle dot="var(--rh-steel)"      label="Suppressors" count={2}/>
      <FirearmCard name="Omega 9K"   kind="suppressor" config="SilencerCo · 9mm"  status={{kind:'verified',label:'Verified'}}     rounds="1,420" lastTrip="14d" malfunctions="0" onClick={()=>go('suppressordetail')}/>
      <FirearmCard name="Sandman-S"  kind="suppressor" config="Dead Air · 7.62"   status={{kind:'due',label:'NFA Pending'}}      rounds="380"   lastTrip="—"   malfunctions="0" onClick={()=>go('suppressordetail')}/>
    </>
  );
}

function RecordMilestones() {
  return (
    <>
      <LabelRule>Milestones</LabelRule>
      <div className="card" style={{padding:'4px 12px'}}>
        <MilestoneRow icon="◆" date="May 02" title="BCM Recce-16 · 6,000-rd service"/>
        <MilestoneRow icon="◆" date="Apr 14" title="100th session logged"/>
        <MilestoneRow icon="◆" date="Apr 02" title="Glock 19 · 3,000 rounds on record"/>
        <MilestoneRow icon="◆" date="Feb 14" title="1 year with Roundhouse"/>
      </div>
    </>
  );
}

function SummaryStat({ v, k, muted, last }) {
  return (
    <div style={{padding:'2px 10px', borderRight: last ? 'none' : '1px solid var(--border-hairline)'}}>
      <div style={{fontFamily:'var(--font-display)', fontSize:20, letterSpacing:'0.02em', color: muted ? 'var(--rh-bone-300)' : 'var(--fg-1)', lineHeight:1, fontVariantNumeric:'tabular-nums'}}>{v}</div>
      <div className="label-md" style={{marginTop:4, fontSize:8, color: muted ? 'var(--rh-bone-700)' : 'var(--rh-bone-500)'}}>{k}</div>
    </div>
  );
}

function MilestoneRow({ icon, date, title }) {
  return (
    <div style={{display:'grid', gridTemplateColumns:'16px 56px 1fr', gap:10, alignItems:'center', padding:'10px 0', borderBottom:'1px solid var(--border-hairline)'}}>
      <span style={{color:'var(--rh-brass-400)', fontFamily:'var(--font-display)', fontSize:12, lineHeight:1, textAlign:'center'}}>{icon}</span>
      <span className="label-md" style={{color:'var(--rh-bone-500)'}}>{date}</span>
      <span style={{fontFamily:'var(--font-ui)', fontSize:12, color:'var(--fg-1)', textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:600}}>{title}</span>
    </div>
  );
}

function RecordEmpty({ go }) {
  return (
    <>
      <TopBar title="Record"/>
      <div className="screen">
        <div className="screen-hero">
          <div className="eyebrow">The living record behind your setup</div>
          <h1 className="hero-title">Your <span className="red">Record</span> starts soon.</h1>
          <div className="hero-sub">The Roundhouse Record fills in as you add gear and log range sessions.</div>
        </div>

        <div className="card" style={{marginTop:8, padding:18, textAlign:'center'}}>
          <div style={{width:120, height:120, margin:'0 auto', border:'1px dashed var(--rh-brass-tint-32)', borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center'}}>
            <div style={{fontFamily:'var(--font-display)', fontSize:36, color:'var(--rh-bone-500)', letterSpacing:'0.02em', lineHeight:1}}>0%</div>
          </div>
          <div className="label-md" style={{marginTop:14, color:'var(--rh-bone-500)'}}>Nothing recorded yet</div>
        </div>

        <LabelRule>Your first three steps</LabelRule>
        <div className="card">
          <EmptyStep n="1" title="Add a firearm" sub="The foundation of every Roundhouse Record." onClick={()=>go('addgun')} active/>
          <EmptyStep n="2" title="Add ammo to supply" sub="Unlocks Maintain and Protect." onClick={()=>{}}/>
          <EmptyStep n="3" title="Log your first range trip" sub="Watch the record come alive." onClick={()=>{}}/>
        </div>
      </div>
    </>
  );
}

function EmptyStep({ n, title, sub, active, onClick }) {
  return (
    <div onClick={onClick} style={{display:'grid', gridTemplateColumns:'36px 1fr auto', gap:12, alignItems:'center', padding:'12px 0', borderBottom:'1px solid var(--border-hairline)', cursor: active ? 'pointer' : 'default', opacity: active ? 1 : 0.5}}>
      <div style={{width:32, height:32, borderRadius:'50%', border:`1px solid ${active?'var(--rh-brass)':'var(--border-default)'}`, display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'var(--font-display)', fontSize:16, color:active?'var(--rh-brass-400)':'var(--rh-bone-500)'}}>{n}</div>
      <div>
        <div style={{fontFamily:'var(--font-ui)', fontSize:12, color:'var(--fg-1)', textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:600}}>{title}</div>
        <div className="rh-body-sm" style={{color:'var(--rh-bone-300)', marginTop:2}}>{sub}</div>
      </div>
      {active && <X.fwd s={14}/>}
    </div>
  );
}

function PillarRow({ color, label, pct }) {
  return (
    <div>
      <div style={{display:'flex', justifyContent:'space-between', fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'0.2em', textTransform:'uppercase', fontWeight:600}}>
        <span style={{color:'var(--fg-2)'}}>{label}</span>
        <span style={{color:color, fontFamily:'var(--font-display)', fontSize:14, letterSpacing:'0.02em'}}>{pct}%</span>
      </div>
      <div style={{height:3, background:'var(--rh-obsidian-500)', marginTop:4, position:'relative'}}>
        <div style={{position:'absolute', inset:'0 auto 0 0', width:`${pct}%`, background:color}}/>
      </div>
    </div>
  );
}

function DocRow({ label, v, tone }) {
  const color = tone==='due' ? 'var(--rh-brass-400)' : tone==='low' ? '#E5B07E' : tone==='ok' ? '#A6C293' : 'var(--fg-1)';
  return (
    <div style={{display:'flex', justifyContent:'space-between', padding:'10px 0', borderBottom:'1px solid var(--border-hairline)'}}>
      <span className="label-md" style={{color:'var(--fg-2)'}}>{label}</span>
      <span style={{fontFamily:'var(--font-display)', fontSize:14, color, letterSpacing:'0.02em'}}>{v}</span>
    </div>
  );
}

// ---------- FIREARM DETAIL ----------
function FirearmDetail({ go }) {
  const [tab, setTab] = React.useState('overview');
  const [reorder, setReorder] = React.useState(false);
  // v4.6: tab switches should jump back to top, not preserve scroll
  // from the previous tab.
  React.useEffect(() => { if (window.__rhScrollTop) window.__rhScrollTop(); }, [tab]);
  return (
    <>
      <TopBar title="Firearm"/>
      <div className="screen">
        {/* v4.3: back to the gun's operational page in Gear, not the Record
            gallery — that's where the user came from for any meaningful edit. */}
        <BackRow to="gundetail" label="Gun" go={go}/>

        <div className="screen-hero" style={{paddingTop:0, position:'relative'}}>
          <div className="eyebrow">9mm · Acquired Nov 2023</div>
          <h1 className="hero-title">Glock 19 <span className="red">Gen5</span></h1>
          <div className="hero-sub">Serial ABXY1234 · Configuration current.</div>
          {/* Top-right action stack: Reorder + Tour */}
          <div style={{position:'absolute', top:8, right:0, display:'flex', gap:6, alignItems:'center'}}>
            <ReorderButton on={reorder} onToggle={()=>setReorder(!reorder)}/>
            <TourButton onClick={()=>window.__rhTour && window.__rhTour('servicerecord')}/>
          </div>
        </div>

        <div className="wire-firearm" style={{marginTop:6, height:96}}>
          <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>

        {/* v4.2: Config tab moved to Gear → Gun. The Service Record stays
            historical: Overview (stats/charts/milestones), Service (rules
            + log), Documents. A small banner above the tabs links to the
            Gear-context Gun page where config is edited. */}
        <div className="card" style={{padding:'10px 12px', display:'grid', gridTemplateColumns:'1fr auto', gap:10, alignItems:'center', cursor:'pointer', background:'transparent', borderStyle:'dashed', borderColor:'var(--rh-brass-tint-32)', marginBottom:6}} onClick={()=>go('gundetail')}>
          <div>
            <div className="label-md" style={{color:'var(--rh-brass-400)'}}>Want to change the gun's setup?</div>
            <div className="rh-body-sm" style={{marginTop:3, color:'var(--rh-bone-300)', fontSize:11}}>Configuration, accessories, default ammo live in Gear → Gun</div>
          </div>
          <span style={{fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'0.16em', color:'var(--rh-brass-400)', textTransform:'uppercase', fontWeight:600}}>Open in Gear →</span>
        </div>

        <div className="top-tabs">
          {[
            {id:'overview', label:'Overview'},
            {id:'service',  label:'Service'},
            {id:'docs',     label:'Documents'},
          ].map(t => (
            <div key={t.id} className={`t ${tab===t.id?'on':''}`} onClick={()=>setTab(t.id)}>{t.label}</div>
          ))}
        </div>

        {tab==='overview' && (
          <ReorderableSections
            editMode={reorder}
            onExit={(action)=>setReorder(action==='open' ? true : false)}
            defaultOrder={['stats','supSplit','roundsChart','heatmap','mods','milestones','sessions']}
            sectionLabels={{
              stats:'STATS',
              supSplit:'SUPPRESSED SPLIT',
              roundsChart:'ROUNDS OVER TIME',
              heatmap:'RANGE FREQUENCY',
              mods:'MODIFICATIONS',
              milestones:'MILESTONES',
              sessions:'RECENT SESSIONS',
            }}
            renderers={{
              stats: () => (
                <div className="stat-grid">
                  <div className="stat-tile"><div className="k">Lifetime rounds</div><div className="v">3,142</div><div className="sub">SINCE NOV '23</div></div>
                  <div className="stat-tile"><div className="k">Range trips</div><div className="v">38</div><div className="sub">SHOT, NOT JUST OWNED</div></div>
                  <div className="stat-tile"><div className="k">Malfunctions</div><div className="v">2</div><div className="sub">99.94% RELIABILITY</div></div>
                  <div className="stat-tile"><div className="k">Cost to date</div><div className="v" style={{color:'var(--rh-brass-400)'}}>$642</div><div className="sub">AMMO LIFETIME</div></div>
                </div>
              ),
              supSplit: () => (
                <>
                  <LabelRule>Suppressed split</LabelRule>
                  <div className="card" style={{padding:'12px 14px'}}>
                    <div style={{display:'flex', height:8, background:'var(--rh-obsidian-500)', borderRadius:1, overflow:'hidden'}}>
                      <div style={{width:'74%', background:'var(--rh-bone)'}}/>
                      <div style={{width:'26%', background:'var(--rh-steel)'}}/>
                    </div>
                    <div style={{display:'flex', justifyContent:'space-between', marginTop:8, fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'0.14em', fontWeight:600}}>
                      <span style={{color:'var(--fg-1)'}}>UNSUPPRESSED · 2,322 <span style={{color:'var(--rh-bone-500)'}}>(74%)</span></span>
                      <span style={{color:'var(--rh-steel-400)'}}>SUPPRESSED · 820 <span style={{color:'var(--rh-bone-500)'}}>(26%)</span></span>
                    </div>
                  </div>
                </>
              ),
              roundsChart: () => (
                <>
                  <LabelRule more="Filter">Rounds fired · last 12 months</LabelRule>
                  <div className="card" style={{padding:'14px 14px 10px'}}>
                    <MiniBarChart data={[
                      {label:'M', v:180}, {label:'J', v:240}, {label:'J', v:90},  {label:'A', v:140},
                      {label:'S', v:200}, {label:'O', v:310}, {label:'N', v:160}, {label:'D', v:80},
                      {label:'J', v:220}, {label:'F', v:280}, {label:'M', v:340}, {label:'A', v:430},
                    ]}/>
                    <div style={{display:'flex', justifyContent:'space-between', marginTop:8}}>
                      <span className="label-md">Last 12 mo</span>
                      <span className="label-md" style={{color:'var(--rh-brass-400)'}}>↑ trending up</span>
                    </div>
                  </div>
                </>
              ),
              heatmap: () => (
                <>
                  <LabelRule>Range frequency · last 26 weeks</LabelRule>
                  <div className="card" style={{padding:'14px'}}>
                    <RangeFrequencyHeatmap data={[0,0,1,0,0,1,2,1,0,2,3,1,2,4,1,2,1,0,1,2,3,2,1,3,4,2]}/>
                    <div style={{display:'flex', justifyContent:'space-between', marginTop:10, fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.20em', fontWeight:600, color:'var(--rh-bone-500)'}}>
                      <span>NOV '25</span>
                      <div style={{display:'flex', alignItems:'center', gap:5}}>
                        <span>LESS</span>
                        {[0.2, 0.4, 0.65, 0.9].map((o,i)=>(<span key={i} style={{width:8, height:8, background:`rgba(107,142,168,${o})`, display:'inline-block'}}/>))}
                        <span>MORE</span>
                      </div>
                      <span>MAY '26</span>
                    </div>
                  </div>
                </>
              ),
              mods: () => (
                <>
                  <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>
                </>
              ),
              milestones: () => (
                <>
                  <LabelRule>Milestones</LabelRule>
                  <div className="card" style={{padding:'4px 12px'}}>
                    <MilestoneRow icon="◆" date="Apr 14" title="3,000 rounds on record"/>
                    <MilestoneRow icon="◆" date="Apr 02" title="Recoil spring replaced · 4,000-rd mark"/>
                    <MilestoneRow icon="◆" date="Feb 22" title="Configuration changed · RMR + TLR-7A mounted"/>
                    <MilestoneRow icon="◆" date="Feb 08" title="Mod · Apex trigger installed"/>
                    <MilestoneRow icon="◆" date="Nov 02 '23" title="Acquired · documentation captured"/>
                  </div>
                </>
              ),
              sessions: () => (
                <>
                  <LabelRule more="All">Recent sessions</LabelRule>
                  <div className="card">
                    <SessionRow d="14" m="Apr" title="Indoor · 25yd" sub="Drills · 0 issues" rounds="250"/>
                    <SessionRow d="02" m="Apr" title="Indoor · 25yd" sub="Reload practice" rounds="180"/>
                    <SessionRow d="22" m="Mar" title="Home · dry fire" sub="Holster work" rounds="0"/>
                  </div>
                </>
              ),
            }}
          />
        )}

        {tab==='config' && (
          <>
            {/* Active-version card — establishes which config version is live */}
            <div className="card brass" style={{padding:'14px 16px', display:'grid', gridTemplateColumns:'1fr auto', gap:10, alignItems:'flex-start'}}>
              <div>
                <div className="label-md" style={{color:'var(--rh-brass-400)', letterSpacing:'0.22em', fontSize:9}}>CONFIG v3 · ACTIVE</div>
                <div style={{fontFamily:'var(--font-display)', fontSize:22, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1, marginTop:4}}>Current configuration</div>
                <div className="rh-body-sm" style={{marginTop:4, color:'var(--rh-bone-500)'}}>Active since Feb 22, 2024 · 740 rounds fired with this config</div>
              </div>
              <button className="btn btn-secondary" style={{padding:'8px 12px', fontSize:10}}>Edit ↓</button>
            </div>

            {/* SLOT-BY-SLOT CONFIG — replaces flat pill list with structured slots.
                Each slot has its own card so the config feels like a real
                gun build sheet, not a tag cloud. */}
            <LabelRule>Mounted components</LabelRule>
            <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>

            {/* Default ammo block — visually distinct */}
            <LabelRule>Default ammo · for this gun</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:24, 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 planned for a trip. Override per session.</div>
                </div>
                <button className="btn btn-secondary" style={{padding:'8px 12px', fontSize:10}}>Change</button>
              </div>
            </div>

            {/* Config stats */}
            <LabelRule>This config's stats</LabelRule>
            <div className="stat-grid">
              <div className="stat-tile"><div className="k">Rounds fired</div><div className="v">740</div><div className="sub">SINCE FEB '24</div></div>
              <div className="stat-tile"><div className="k">Sessions</div><div className="v">11</div><div className="sub">WITH THIS BUILD</div></div>
              <div className="stat-tile"><div className="k">Suppressed split</div><div className="v" style={{color:'var(--rh-steel-400)'}}>247</div><div className="sub">33% OF ROUNDS</div></div>
              <div className="stat-tile"><div className="k">Malfunctions</div><div className="v" style={{color:'#A6C293'}}>0</div><div className="sub">CLEAN STREAK</div></div>
            </div>

            <LabelRule>Configuration history</LabelRule>
            <div className="card" style={{padding:'4px 12px'}}>
              <LoadoutHistoryRow num="v3" name="+ Omega 9K suppressor" dates="Feb 22, 2024 → current" rounds="740 rds" active/>
              <LoadoutHistoryRow num="v2" name="+ Apex trigger, RMR, TLR-7A" dates="Dec 14 '23 → Feb 22 '24" rounds="1,580 rds"/>
              <LoadoutHistoryRow num="v1" name="Factory stock" dates="Nov 02 '23 → Dec 14 '23" rounds="822 rds"/>
            </div>
          </>
        )}

        {tab==='service' && (
          <>
            <LabelRule>Open rules</LabelRule>
            <div className="maint-row ready">
              <div>
                <div className="ttl">Next: full strip clean</div>
                <div className="sub">~250 rounds out · est 2 weeks</div>
              </div>
              <div className="right">
                <div className="pct">93<span style={{fontSize:12}}>%</span></div>
                <div className="pct-sub">READY</div>
              </div>
            </div>
            <div className="maint-row ready">
              <div>
                <div className="ttl">Recoil spring · 5,000-rd interval</div>
                <div className="sub">1,858 rounds out · est 3 mo</div>
              </div>
              <div className="right">
                <div className="pct">37<span style={{fontSize:12}}>%</span></div>
                <div className="pct-sub">READY</div>
              </div>
            </div>
            <div className="maint-row ready">
              <div>
                <div className="ttl">RMR battery · 24-mo cycle</div>
                <div className="sub">22 weeks since change</div>
              </div>
              <div className="right">
                <div className="pct">79<span style={{fontSize:12}}>%</span></div>
                <div className="pct-sub">READY</div>
              </div>
            </div>

            <LabelRule>Service history</LabelRule>
            <div className="card">
              <SessionRow d="14" m="Apr" title="Cleaned · Lubricated" sub="Self · 247 rds since · standard interval" rounds="3142"/>
              <SessionRow d="22" m="Mar" title="RMR battery replaced" sub="CR2032 · 22-mo cycle"        rounds="2895"/>
              <SessionRow d="08" m="Feb" title="Trigger spring (Apex)" sub="Custom install · 2,400 rds"   rounds="2412"/>
              <SessionRow d="14" m="Jan" title="Recoil spring · OEM"   sub="2,000-rd mark · per Glock"    rounds="2050"/>
              <SessionRow d="22" m="Nov" title="Initial cleaning"      sub="At acquisition"                rounds="0"/>
            </div>

            <LabelRule>Malfunction events · 2 lifetime</LabelRule>
            <div className="card" style={{padding:'4px 12px'}}>
              <MalfunctionRow date="Mar 04" type="FTF" rounds="2,612" ammo="Winchester USA 115gr · Training" sup={false}/>
              <MalfunctionRow date="Dec 14" type="STOVE PIPE" rounds="1,840" ammo="PMC Bronze 115gr · Training" sup={false}/>
            </div>
          </>
        )}

        {tab==='docs' && (
          <>
            <LabelRule>Documents</LabelRule>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8}}>
              <div className="doc-tile"><div className="doc-thumb">RECEIPT</div><span className="label-md" style={{color:'var(--fg-1)', fontSize:9}}>Nov 02 '23</span></div>
              <div className="doc-tile"><div className="doc-thumb">SERIAL · PHOTO</div><span className="label-md" style={{color:'var(--fg-1)', fontSize:9}}>Nov 02 '23</span></div>
              <div className="doc-tile"><div className="doc-thumb">INSURANCE</div><span className="label-md" style={{color:'var(--fg-1)', fontSize:9}}>Listed</span></div>
              <div className="doc-tile missing"><div className="doc-thumb">+ ADD</div><span className="label-md" style={{color:'#E48A82', fontSize:9}}>Warranty card</span></div>
            </div>
          </>
        )}

        <div style={{marginTop:16, display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
          <Button variant="secondary" block>Log service</Button>
          <Button variant="primary" block onClick={()=>go('plan')}>Take to range →</Button>
        </div>
      </div>
    </>
  );
}

// ---------- Section title (display-sized header with colored dot) ----------
// v4.4: replaces LabelRule for the major guns-vs-suppressors split on
// Record. Bigger, more legible category headers.
function SectionTitle({ dot, label, count, more }) {
  return (
    <div style={{display:'flex', alignItems:'baseline', gap:12, margin:'22px 4px 12px'}}>
      <span style={{width:9, height:9, borderRadius:'50%', background:dot, alignSelf:'center'}}/>
      <div style={{fontFamily:'var(--font-display)', fontSize:22, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1}}>{label}</div>
      {typeof count === 'number' && (
        <span className="label-md" style={{color:'var(--rh-bone-500)', fontSize:10, letterSpacing:'0.16em'}}>· {count}</span>
      )}
      <div style={{flex:1, height:1, background:'var(--border-hairline)'}}/>
      {more && <div style={{fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.22em', color:'var(--rh-brass-400)', textTransform:'uppercase', fontWeight:600, cursor:'pointer'}}>{more} →</div>}
    </div>
  );
}

// ---------- Goal card ----------
function GoalCard({ title, sub, progress, sessions, lastWorked, status }) {
  const achieved = status === 'achieved';
  const color = achieved ? '#A6C293' : 'var(--rh-brass)';
  return (
    <div className="card" style={{borderLeft: `3px solid ${color}`, opacity: achieved ? 0.7 : 1}}>
      <div style={{display:'grid', gridTemplateColumns:'1fr auto', gap:10, alignItems:'flex-start'}}>
        <div>
          <div style={{fontFamily:'var(--font-display)', fontSize:17, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1.1}}>{title}</div>
          <div className="rh-body-sm" style={{marginTop:4, color:'var(--rh-bone-300)'}}>{sub}</div>
        </div>
        <div style={{textAlign:'right'}}>
          <div style={{fontFamily:'var(--font-display)', fontSize:22, color, letterSpacing:'0.02em', lineHeight:1, fontVariantNumeric:'tabular-nums'}}>{progress}<span style={{fontSize:12}}>%</span></div>
          {achieved && <div className="label-md" style={{marginTop:3, fontSize:8, color:'#A6C293'}}>ACHIEVED</div>}
        </div>
      </div>
      <div style={{height:4, background:'var(--rh-obsidian-500)', marginTop:10, borderRadius:1, overflow:'hidden'}}>
        <div style={{height:'100%', width:`${progress}%`, background:color}}/>
      </div>
      <div style={{display:'flex', justifyContent:'space-between', marginTop:8}}>
        <span className="label-md" style={{color:'var(--rh-bone-500)'}}>{sessions} sessions contributing</span>
        <span className="label-md" style={{color:'var(--rh-bone-500)'}}>Last · {lastWorked}</span>
      </div>
    </div>
  );
}

// ---------- Config slot card ----------
// v4.1: each accessory slot (OPTIC, LIGHT, TRIGGER, etc.) gets its own card
// in the gun's Config tab — feels like a real build sheet, not a tag cloud.
function ConfigSlotCard({ slot, item, serial, mountedDate, rounds, empty, addLabel, mod, steel }) {
  const accentColor = steel ? 'var(--rh-steel)' : (mod ? 'var(--rh-dusty-red)' : 'var(--rh-brass)');
  const accentText  = steel ? 'var(--rh-steel-400)' : (mod ? '#E48A82' : 'var(--rh-brass-400)');

  if (empty) return (
    <div style={{
      background:'transparent',
      border:'1px dashed var(--border-default)',
      borderLeft:'3px dashed var(--border-default)',
      borderRadius:2,
      padding:'10px 14px',
      display:'grid', gridTemplateColumns:'80px 1fr auto', gap:10, alignItems:'center',
      cursor:'pointer',
    }}>
      <span className="label-md" style={{color:'var(--rh-bone-700)', letterSpacing:'0.20em'}}>{slot}</span>
      <span style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--rh-bone-700)', letterSpacing:'0.02em'}}>{addLabel || '+ Add'}</span>
      <I.plus s={12}/>
    </div>
  );

  return (
    <div style={{
      background:'var(--bg-elevated-1)',
      border:'1px solid var(--border-default)',
      borderLeft:`3px solid ${accentColor}`,
      borderRadius:2,
      padding:'10px 14px',
      display:'grid', gridTemplateColumns:'80px 1fr auto', gap:10, alignItems:'center',
    }}>
      <div>
        <div className="label-md" style={{color:accentText, letterSpacing:'0.20em', fontSize:9}}>{slot}</div>
        {mod && <div className="label-md" style={{color:'var(--rh-dusty-red)', fontSize:8, letterSpacing:'0.22em', marginTop:3}}>MOD</div>}
      </div>
      <div>
        <div style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--fg-1)', letterSpacing:'0.02em'}}>{item}</div>
        <div className="label-md" style={{marginTop:3, color:'var(--rh-bone-500)', fontSize:8}}>
          {serial && <>SN {serial} · </>}
          mounted {mountedDate}
          {rounds && <> · {rounds} rds with this gun</>}
        </div>
      </div>
      <button
        onClick={()=>window.__rhGo && window.__rhGo('editgun')}
        style={{
          background:'transparent', border:0, padding:0, cursor:'pointer',
          fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.20em',
          color:'var(--rh-bone-500)', textTransform:'uppercase', fontWeight:600,
        }}>Swap →</button>
    </div>
  );
}

// ---------- Modification row ----------
function ModRow({ part, detail, date, at, last }) {
  return (
    <div style={{display:'grid', gridTemplateColumns:'80px 1fr auto', gap:10, alignItems:'baseline', padding:'10px 0', borderBottom: last ? 'none' : '1px solid var(--border-hairline)'}}>
      <span className="label-md" style={{color:'var(--rh-steel-400)', letterSpacing:'0.18em'}}>{part}</span>
      <div>
        <div style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--fg-1)', letterSpacing:'0.02em'}}>{detail}</div>
        <div className="label-md" style={{marginTop:2, color:'var(--rh-bone-500)', fontSize:8}}>installed {date} · at {at}</div>
      </div>
      <X.fwd s={12}/>
    </div>
  );
}

// ---------- Loadout history row ----------
function LoadoutHistoryRow({ num, name, dates, rounds, active }) {
  return (
    <div style={{display:'grid', gridTemplateColumns:'auto 1fr auto', gap:10, alignItems:'center', padding:'10px 0', borderBottom:'1px solid var(--border-hairline)'}}>
      <span style={{fontFamily:'var(--font-display)', fontSize:18, color: active ? 'var(--rh-brass-400)' : 'var(--rh-bone-500)', letterSpacing:'0.02em', minWidth:24, textAlign:'center'}}>{num}</span>
      <div>
        <div style={{fontFamily:'var(--font-ui)', fontSize:12, color: active ? 'var(--fg-1)' : 'var(--rh-bone-300)', textTransform:'uppercase', letterSpacing:'0.10em', fontWeight:600}}>{name}{active && <span style={{color:'#A6C293', marginLeft:6, fontSize:8, letterSpacing:'0.22em'}}>· ACTIVE</span>}</div>
        <div className="label-md" style={{marginTop:2, color:'var(--rh-bone-500)'}}>{dates}</div>
      </div>
      <span style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--rh-bone-300)', letterSpacing:'0.02em'}}>{rounds}</span>
    </div>
  );
}

// ---------- Visualization primitives ----------

function MiniBarChart({ data, height=64, color='var(--rh-brass)' }) {
  const max = Math.max(...data.map(d=>d.v));
  return (
    <div style={{display:'flex', alignItems:'flex-end', gap:3, height}}>
      {data.map((d,i)=>(
        <div key={i} style={{flex:1, display:'flex', flexDirection:'column', alignItems:'stretch', gap:4}}>
          <div style={{flex:1, display:'flex', alignItems:'flex-end'}}>
            <div style={{
              width:'100%',
              height:`${Math.max((d.v/max)*100, 5)}%`,
              background: i===data.length-1 ? 'var(--rh-brass-400)' : color,
              opacity: i===data.length-1 ? 1 : 0.85,
            }}/>
          </div>
          <div style={{fontFamily:'var(--font-ui)', fontSize:8, letterSpacing:'0.18em', color:'var(--rh-bone-500)', textAlign:'center', fontWeight:600}}>{d.label}</div>
        </div>
      ))}
    </div>
  );
}

function RangeFrequencyHeatmap({ data }) {
  // Uses steel blue for intensity — "cool / data" feel, distinct from
  // the warm brass used for active state across the rest of the app.
  return (
    <div style={{display:'flex', gap:3}}>
      {data.map((d,i)=>(
        <div key={i} style={{
          flex:1, aspectRatio:'1',
          background: d===0
            ? 'var(--rh-obsidian-700)'
            : `rgba(107,142,168,${Math.min(0.20 + d*0.22, 0.95)})`,
          border: d===0 ? '1px solid var(--border-hairline)' : 'none',
        }} title={d===0 ? 'no sessions' : `${d} session${d>1?'s':''}`}/>
      ))}
    </div>
  );
}

function MalfunctionRow({ date, type, rounds, ammo, sup }) {
  return (
    <div style={{display:'grid', gridTemplateColumns:'56px 1fr auto', gap:10, alignItems:'center', padding:'10px 0', borderBottom:'1px solid var(--border-hairline)'}}>
      <div>
        <div style={{fontFamily:'var(--font-display)', fontSize:14, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1}}>{date}</div>
        <div className="label-md" style={{marginTop:3, fontSize:8, color:'var(--rh-bone-500)'}}>at {rounds}</div>
      </div>
      <div>
        <div style={{fontFamily:'var(--font-ui)', fontSize:11, color:'var(--rh-dusty-red)', textTransform:'uppercase', letterSpacing:'0.18em', fontWeight:600}}>{type}</div>
        <div className="rh-body-sm" style={{color:'var(--rh-bone-300)', marginTop:2}}>{ammo}</div>
      </div>
      <span className="label-md" style={{color: sup ? 'var(--rh-dusty-red)' : 'var(--rh-bone-500)', fontSize:8}}>{sup ? 'SUP' : 'NO SUP'}</span>
    </div>
  );
}

// ---------- SUPPRESSOR DETAIL ----------
// v4.5: dedicated screen for a suppressor's record. A suppressor accumulates
// rounds across MANY guns over its life. The 'Hosts' section breaks that
// down per-gun so the user can see where the can's been.
function SuppressorDetail({ go }) {
  // Sample data — Omega 9K
  const sup = {
    name:'SilencerCo Omega 9K',
    caliber:'9mm-rated · also 9×18, .380, .300 BLK',
    serial:'OM9-44218',
    acquired:'Jan 14, 2024',
    nfa:'Form 4 · Approved',
    stampDate:'Sep 22, 2023',
    totalRounds:1420,
    sessions:8,
    malfunctions:0,
  };
  // Per-gun round breakdown — the answer to "how do records work across guns"
  const hosts = [
    { gun:'Glock 19 Gen5', rounds:1180, sessions:6, lastUsed:'14d',  rangePct:83, current:true },
    { gun:'SIG P365 XL',   rounds:160,  sessions:1, lastUsed:'2mo',  rangePct:11 },
    { gun:'Beretta 92FS',  rounds:80,   sessions:1, lastUsed:'3mo',  rangePct:6 },
  ];

  return (
    <>
      <TopBar title="Suppressor"/>
      <div className="screen">
        <BackRow to="record" label="Roundhouse Record" go={go}/>

        <div className="screen-hero" style={{paddingTop:4}}>
          <div className="eyebrow" style={{color:'var(--rh-steel-400)'}}>SUPPRESSOR · {sup.serial}</div>
          <h1 className="hero-title" style={{fontSize:34}}>{sup.name}</h1>
          <div className="hero-sub" style={{marginTop:6}}>{sup.caliber}</div>
        </div>

        {/* Cross-link to Gear suppressor page (config-side, when we build it) */}
        <div className="card" style={{padding:'10px 12px', borderLeft:'3px solid var(--rh-steel)', display:'grid', gridTemplateColumns:'1fr auto', gap:10, alignItems:'center'}}>
          <div>
            <div className="label-md" style={{color:'var(--rh-steel-400)', letterSpacing:'0.22em', fontSize:9}}>NFA</div>
            <div style={{fontFamily:'var(--font-display)', fontSize:15, color:'var(--fg-1)', letterSpacing:'0.02em', marginTop:3}}>{sup.nfa}</div>
            <div className="label-md" style={{marginTop:3, color:'var(--rh-bone-500)', fontSize:9}}>Tax stamp · {sup.stampDate}</div>
          </div>
          <button className="btn btn-ghost" style={{padding:'6px 10px', fontSize:9}}>Documents →</button>
        </div>

        {/* Headline stats — across all hosts */}
        <LabelRule>Lifetime — across all hosts</LabelRule>
        <div className="stat-grid">
          <div className="stat-tile"><div className="k">Total rounds</div><div className="v" style={{color:'var(--rh-steel-400)'}}>{sup.totalRounds.toLocaleString()}</div><div className="sub">ALL HOSTS COMBINED</div></div>
          <div className="stat-tile"><div className="k">Sessions</div><div className="v">{sup.sessions}</div><div className="sub">WITH CAN MOUNTED</div></div>
          <div className="stat-tile"><div className="k">Hosts</div><div className="v">{hosts.length}</div><div className="sub">GUNS USED ON</div></div>
          <div className="stat-tile"><div className="k">Reliability</div><div className="v" style={{color:'#A6C293'}}>100%</div><div className="sub">0 MALFUNCTIONS</div></div>
        </div>

        {/* THE KEY SECTION — answers the user's question. Per-host breakdown. */}
        <LabelRule more="Sort">Used on · per-host breakdown</LabelRule>
        <div className="card" style={{padding:'4px 14px'}}>
          {hosts.map((h, i) => (
            <div key={h.gun} style={{padding:'12px 0', borderBottom: i < hosts.length-1 ? '1px solid var(--border-hairline)' : 'none'}}>
              <div style={{display:'grid', gridTemplateColumns:'1fr auto', gap:10, alignItems:'baseline'}}>
                <div>
                  <div style={{display:'flex', alignItems:'baseline', gap:8}}>
                    <span style={{fontFamily:'var(--font-display)', fontSize:16, color:'var(--fg-1)', letterSpacing:'0.02em'}}>{h.gun}</span>
                    {h.current && (
                      <span style={{
                        padding:'2px 6px',
                        background:'rgba(107,142,90,0.14)',
                        color:'#A6C293',
                        border:'1px solid rgba(107,142,90,0.35)',
                        fontFamily:'var(--font-ui)', fontSize:8, letterSpacing:'0.20em',
                        textTransform:'uppercase', fontWeight:600, lineHeight:1,
                      }}>Currently mounted</span>
                    )}
                  </div>
                  <div className="label-md" style={{marginTop:4, color:'var(--rh-bone-500)', fontSize:9}}>{h.sessions} session{h.sessions===1?'':'s'} · last used {h.lastUsed} ago</div>
                </div>
                <div style={{textAlign:'right'}}>
                  <div style={{fontFamily:'var(--font-display)', fontSize:18, color:'var(--rh-steel-400)', letterSpacing:'0.02em', fontVariantNumeric:'tabular-nums'}}>{h.rounds.toLocaleString()}</div>
                  <div className="label-md" style={{marginTop:3, fontSize:8, color:'var(--rh-bone-500)'}}>RDS</div>
                </div>
              </div>
              {/* visual bar — share of total */}
              <div style={{height:3, background:'var(--rh-obsidian-500)', marginTop:8}}>
                <div style={{height:'100%', width:`${h.rangePct}%`, background:'var(--rh-steel)'}}/>
              </div>
              <div className="label-md" style={{marginTop:4, fontSize:8, color:'var(--rh-bone-500)'}}>{h.rangePct}% of lifetime rounds</div>
            </div>
          ))}
        </div>

        {/* Rounds-over-time chart — same primitive used on gun records */}
        <LabelRule>Rounds over time</LabelRule>
        <div className="card" style={{padding:'14px 14px 10px'}}>
          <MiniBarChart data={[
            {label:'F', v:0}, {label:'M', v:0}, {label:'A', v:120},
            {label:'M', v:80}, {label:'J', v:60}, {label:'J', v:0},
            {label:'A', v:140}, {label:'S', v:100}, {label:'O', v:220},
            {label:'N', v:180}, {label:'D', v:240}, {label:'J', v:280},
          ]}/>
          <div style={{display:'flex', justifyContent:'space-between', marginTop:8}}>
            <span className="label-md">12 months · all hosts</span>
            <span className="label-md" style={{color:'var(--rh-steel-400)'}}>↑ usage trending up</span>
          </div>
        </div>

        {/* Service history — for a suppressor this is typically light */}
        <LabelRule>Service history</LabelRule>
        <div className="card">
          <SessionRow d="04" m="Mar" title="Disassembled · cleaned"   sub="ATF-approved solvent · 920 rds since acq." rounds="—"/>
          <SessionRow d="14" m="Jan" title="Acquired · initial inspection" sub="No rounds yet"                  rounds="0"/>
        </div>

        <div style={{marginTop:14, display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
          <Button variant="secondary" block icon={<X.upload s={12}/>}>Export</Button>
          <Button variant="ghost" block>Documents (NFA)</Button>
        </div>
      </div>
    </>
  );
}

window.Record = Record;
window.FirearmDetail = FirearmDetail;
window.SuppressorDetail = SuppressorDetail;
// Cross-file usage (Gear's GunDetail uses these too):
window.ConfigSlotCard = ConfigSlotCard;
window.ModRow = ModRow;
window.LoadoutHistoryRow = LoadoutHistoryRow;
