/* Roundhouse app — shared components & hooks. Exports to window. */

const { useState } = React;

// ------------- Icons -------------
const I = {
  target: (p={}) => (
    <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square">
      <circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1" fill="currentColor"/>
    </svg>
  ),
  package: (p={}) => (
    <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="m7.5 4.27 9 5.15M21 8 12 3 3 8l9 5 9-5z"/><path d="M3 8v8l9 5 9-5V8"/>
    </svg>
  ),
  cog: (p={}) => (
    <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="12" r="3"/>
      <path d="M19 12a7 7 0 0 0-.1-1.2l2-1.6-2-3.4-2.4 1a7 7 0 0 0-2-1.2L14 3h-4l-.5 2.6a7 7 0 0 0-2 1.2l-2.4-1-2 3.4 2 1.6A7 7 0 0 0 5 12c0 .4 0 .8.1 1.2l-2 1.6 2 3.4 2.4-1a7 7 0 0 0 2 1.2L10 21h4l.5-2.6a7 7 0 0 0 2-1.2l2.4 1 2-3.4-2-1.6c.1-.4.1-.8.1-1.2Z"/>
    </svg>
  ),
  shield: (p={}) => (
    <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M20 13c0 5-3.5 7.5-8 9-4.5-1.5-8-4-8-9V5l8-3 8 3v8z"/><path d="m9 12 2 2 4-4"/>
    </svg>
  ),
  ring: (p={}) => (
    <svg width={p.s||20} height={p.s||20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3"/>
    </svg>
  ),
  gear: (p={}) => (
    <svg width={p.s||20} height={p.s||20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square">
      <rect x="3" y="3" width="8" height="8"/><rect x="13" y="3" width="8" height="8"/>
      <rect x="3" y="13" width="8" height="8"/><rect x="13" y="13" width="8" height="8"/>
    </svg>
  ),
  lock: (p={}) => (
    <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect x="4" y="10" width="16" height="11" rx="1"/>
      <path d="M8 10V7a4 4 0 0 1 8 0v3"/>
    </svg>
  ),
  bell: (p={}) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 21a2 2 0 0 0 4 0"/></svg>,
  menu: (p={}) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M3 12h18M3 18h18"/></svg>,
  plus: (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14"/></svg>,
  arrow: (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  warn: (p={}) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 9v4M12 17h.01M10.3 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z"/></svg>,
  check: (p={}) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m5 12 5 5L20 7"/></svg>,
  clock: (p={}) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/></svg>,
  chev: (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m9 18 6-6-6-6"/></svg>,
};

// ------------- Gun silhouettes -------------
// Used as the visual anchor for loadout cards + gun cards. Inline SVGs so
// they scale crisply. All take a width prop (height auto from viewBox aspect).
const GunSil = {
  pistol: (p={}) => (
    <svg viewBox="0 0 120 60" width={p.w||120} fill="currentColor" style={p.style}>
      {/* Slide with rear sights bump */}
      <path d="M 18 22 L 18 18 L 22 18 L 22 16 L 76 16 L 76 18 L 90 18 L 96 22 L 96 30 L 18 30 Z"/>
      {/* Front sight */}
      <rect x="84" y="14" width="3" height="4"/>
      {/* Barrel poke */}
      <rect x="96" y="22" width="6" height="6"/>
      {/* Trigger guard */}
      <path d="M 38 30 L 38 34 Q 38 42 46 42 Q 52 42 52 34 L 52 30 Z"/>
      {/* Grip + mag */}
      <path d="M 30 30 L 30 36 L 36 54 L 50 54 L 46 36 L 46 30 Z"/>
      <rect x="37" y="50" width="9" height="6"/>
    </svg>
  ),
  ar: (p={}) => (
    <svg viewBox="0 0 200 50" width={p.w||200} fill="currentColor" style={p.style}>
      {/* Stock */}
      <path d="M 5 20 L 30 20 L 30 32 L 18 36 L 5 32 Z"/>
      {/* Buffer tube */}
      <rect x="30" y="24" width="14" height="6"/>
      {/* Receiver */}
      <rect x="44" y="18" width="34" height="14"/>
      {/* Charging handle (carry-handle-style hump) */}
      <rect x="56" y="14" width="14" height="4"/>
      {/* Optic */}
      <rect x="60" y="8" width="14" height="4"/>
      <rect x="64" y="6" width="6" height="2"/>
      {/* Pistol grip */}
      <path d="M 50 32 L 48 44 L 60 44 L 64 32 Z"/>
      {/* Magazine */}
      <path d="M 60 32 L 60 46 L 72 50 L 74 50 L 74 32 Z"/>
      {/* Handguard */}
      <rect x="78" y="20" width="78" height="10"/>
      {/* Barrel */}
      <rect x="156" y="23" width="40" height="4"/>
      {/* Muzzle device */}
      <rect x="190" y="20" width="8" height="10"/>
    </svg>
  ),
  shotgun: (p={}) => (
    <svg viewBox="0 0 200 50" width={p.w||200} fill="currentColor" style={p.style}>
      {/* Stock — fuller, traditional shape */}
      <path d="M 5 22 L 8 16 L 30 18 L 32 34 L 12 38 Z"/>
      {/* Receiver */}
      <rect x="32" y="20" width="22" height="14"/>
      {/* Trigger area */}
      <path d="M 40 34 Q 40 40 46 40 Q 50 40 50 34 Z"/>
      {/* Pump (forend) */}
      <rect x="54" y="24" width="32" height="10"/>
      <rect x="58" y="22" width="24" height="2"/>
      {/* Barrel */}
      <rect x="86" y="23" width="106" height="4"/>
      {/* Bead sight */}
      <circle cx="188" cy="22" r="2"/>
    </svg>
  ),
  pcc: (p={}) => (
    <svg viewBox="0 0 180 50" width={p.w||180} fill="currentColor" style={p.style}>
      {/* Stock — collapsible style */}
      <path d="M 5 20 L 25 20 L 25 30 L 14 34 L 5 30 Z"/>
      <rect x="25" y="22" width="14" height="6"/>
      {/* Receiver */}
      <rect x="39" y="18" width="30" height="14"/>
      {/* Optic */}
      <rect x="50" y="10" width="14" height="6"/>
      {/* Pistol grip */}
      <path d="M 45 32 L 43 44 L 55 44 L 59 32 Z"/>
      {/* Glock-style mag (vertical, taller, blockier) */}
      <rect x="55" y="32" width="10" height="16"/>
      {/* Handguard */}
      <rect x="69" y="20" width="50" height="10"/>
      {/* Barrel — shorter */}
      <rect x="119" y="23" width="50" height="4"/>
      {/* Cap */}
      <rect x="167" y="20" width="6" height="10"/>
    </svg>
  ),
  bolt: (p={}) => (
    <svg viewBox="0 0 200 50" width={p.w||200} fill="currentColor" style={p.style}>
      {/* Stock — traditional rifle */}
      <path d="M 5 18 L 10 14 L 50 18 L 52 36 L 8 36 Z"/>
      {/* Receiver */}
      <rect x="52" y="18" width="26" height="12"/>
      {/* Bolt handle */}
      <rect x="68" y="14" width="3" height="4"/>
      <rect x="71" y="10" width="5" height="3"/>
      {/* Optic */}
      <rect x="56" y="8" width="20" height="4"/>
      <rect x="60" y="6" width="10" height="2"/>
      {/* Trigger area */}
      <path d="M 60 30 Q 60 36 66 36 Q 70 36 70 30 Z"/>
      {/* Barrel */}
      <rect x="78" y="22" width="116" height="4"/>
      {/* Muzzle */}
      <rect x="192" y="20" width="6" height="8"/>
    </svg>
  ),
  revolver: (p={}) => (
    <svg viewBox="0 0 120 60" width={p.w||120} fill="currentColor" style={p.style}>
      {/* Cylinder */}
      <circle cx="50" cy="26" r="14"/>
      {/* Cylinder detail (hint of chambers) */}
      <circle cx="50" cy="26" r="4" fill="var(--rh-obsidian)"/>
      {/* Top strap + barrel */}
      <rect x="50" y="14" width="50" height="6"/>
      {/* Front sight */}
      <rect x="92" y="10" width="3" height="4"/>
      {/* Frame back */}
      <rect x="30" y="20" width="14" height="14"/>
      {/* Trigger guard */}
      <path d="M 36 34 L 36 40 Q 36 46 42 46 Q 46 46 46 40 L 46 34 Z"/>
      {/* Grip */}
      <path d="M 28 30 L 26 38 L 30 54 L 42 54 L 44 38 L 44 30 Z"/>
    </svg>
  ),
};

function Wedge({ size=8, color }) {
  return <span className="wedge" style={{
    borderLeftWidth: size, borderRightWidth: size,
    borderTopWidth: size + 2,
    borderTopColor: color || 'var(--rh-dusty-red)',
  }}/>;
}

// ------------- Ring (segmented) -------------
function Ring({ size=80, pct=72, color='var(--rh-brass)', track='#26262C', label, value, sub }) {
  const r = 42, c = 2 * Math.PI * r;
  const dash = (pct / 100) * c;
  return (
    <div style={{position:'relative', width: size, height: size, display:'inline-block'}}>
      <svg width={size} height={size} viewBox="0 0 100 100">
        <circle cx="50" cy="50" r={r} fill="none" stroke={track} strokeWidth="6"/>
        <circle cx="50" cy="50" r={r} fill="none" stroke={color} strokeWidth="6"
                strokeDasharray={`${dash} ${c}`} strokeLinecap="butt"
                transform="rotate(-90 50 50)"/>
      </svg>
      <div style={{position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center'}}>
        <div style={{fontFamily:'var(--font-display)', fontSize: size*0.26, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1, fontVariantNumeric:'tabular-nums'}}>{value ?? `${pct}%`}</div>
        {sub && <div style={{fontFamily:'var(--font-ui)', fontSize: 8, color:'var(--fg-4)', letterSpacing:'0.2em', textTransform:'uppercase', marginTop: 3, fontWeight:600}}>{sub}</div>}
      </div>
    </div>
  );
}

// ------------- Badge -------------
function Badge({ kind='ready', children }) {
  const dot = { ready:'#6B8E5A', due:'#B89A56', attention:'#C33A2E', low:'#C77A3B', verified:'#8AA37A' }[kind];
  return <span className={`badge ${kind}`}><span className="dot" style={{background:dot}}/>{children}</span>;
}

// ------------- Button -------------
function Button({ variant='primary', block, onClick, children, icon }) {
  return <button className={`btn btn-${variant} ${block?'btn-block':''}`} onClick={onClick}>{icon}{children}</button>;
}

// ------------- TopBar -------------
// Menu icon navigates to Settings via window.__rhGo (set by Phone).
function TopBar({ title }) {
  const goSettings = () => { if (window.__rhGo) window.__rhGo('settings'); };
  return (
    <div className="topbar">
      <div className="topbar-logo">
        <img src="assets/logo_ring_icon.png" alt=""/>
        <div className="topbar-name">{title || 'Roundhouse'}</div>
      </div>
      <div className="topbar-actions">
        <button className="icon-btn" title="Alerts"><I.bell/></button>
        <button className="icon-btn" title="Settings" onClick={goSettings}><I.menu/></button>
      </div>
    </div>
  );
}

// ------------- BottomTabs -------------
function BottomTabs({ active, setActive, locked={} }) {
  const tabs = [
    { id:'home', label:'Use', icon:<I.target s={20}/> },
    { id:'gear', label:'Gear', icon:<I.gear s={20}/> },
    { id:'supply', label:'Supply', icon:<I.package s={20}/> },
    { id:'maintain', label:'Maintain', icon:<I.cog s={20}/> },
    { id:'record', label:'Record', icon:<I.ring s={20}/> },
  ];
  return (
    <nav className="bottom-tabs">
      {tabs.map(t => {
        const isLocked = locked[t.id];
        return (
          <button key={t.id} className={`tab ${active===t.id?'active':''} ${isLocked?'locked':''}`} onClick={()=>setActive(t.id)}>
            <span style={{position:'relative', display:'inline-flex'}}>
              {t.icon}
              {isLocked && <span style={{position:'absolute', top:-3, right:-5, width:10, height:10, background:'var(--rh-obsidian-900)', borderRadius:'50%', display:'inline-flex', alignItems:'center', justifyContent:'center', color:'var(--rh-bone-500)'}}><I.lock s={8}/></span>}
            </span>
            <span>{t.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

// ------------- Section head -------------
function SectionHead({ children, more }) {
  return (
    <div className="section-head">
      <div className="h">{children}</div>
      {more && <div className="more">{more} →</div>}
    </div>
  );
}

// ------------- FirearmCard -------------
// Accepts an optional `gunType` (pistol/ar/shotgun/pcc/bolt/revolver) — when
// provided, renders the matching silhouette in the lower-right corner as a
// faint background graphic for visual ID at a glance.
// `kind` ('gun' | 'suppressor') controls left-edge accent + small badge so
// suppressor cards read distinctly from gun cards in mixed galleries.
function FirearmCard({ name, config, status, rounds, lastTrip, malfunctions, gunType, kind='gun', onClick }) {
  const Silhouette = gunType && GunSil[gunType];
  const isSup = kind === 'suppressor';
  const accentColor = isSup ? 'var(--rh-steel)' : 'var(--rh-brass-tint-32)';
  return (
    <div
      className="card"
      style={{
        cursor:'pointer', position:'relative', overflow:'hidden',
        borderLeft:`3px solid ${accentColor}`,
      }}
      onClick={onClick}>
      {Silhouette && (
        <div style={{position:'absolute', right:6, bottom:6, color:'var(--rh-bone)', opacity:0.10, pointerEvents:'none'}}>
          <Silhouette w={gunType==='pistol' || gunType==='revolver' ? 70 : 130}/>
        </div>
      )}
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:8, position:'relative'}}>
        <div>
          <div style={{display:'flex', alignItems:'center', gap:8}}>
            <div style={{fontFamily:'var(--font-display)', fontSize:22, letterSpacing:'0.02em', color:'var(--fg-1)', textTransform:'uppercase', lineHeight:1}}>{name}</div>
            {isSup && (
              <span style={{
                padding:'3px 6px',
                background:'var(--rh-steel-tint-12)',
                color:'var(--rh-steel-400)',
                border:'1px solid var(--rh-steel-tint-24)',
                fontFamily:'var(--font-ui)', fontSize:8, letterSpacing:'0.20em',
                textTransform:'uppercase', fontWeight:600, lineHeight:1,
              }}>SUP</span>
            )}
          </div>
          <div style={{fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'0.18em', color: isSup ? 'var(--rh-steel-400)' : 'var(--rh-brass-400)', textTransform:'uppercase', marginTop:4, fontWeight:600}}>{config}</div>
        </div>
        <Badge kind={status.kind}>{status.label}</Badge>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8, borderTop:'1px solid var(--border-hairline)', paddingTop:12, marginTop:12, position:'relative'}}>
        <Stat v={rounds} k="Rounds"/>
        <Stat v={lastTrip} k="Last Trip"/>
        <Stat v={malfunctions} k="Issues"/>
      </div>
    </div>
  );
}
function Stat({ v, k, color }) {
  return (
    <div>
      <div style={{fontFamily:'var(--font-display)', fontSize:20, color:color||'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1, fontVariantNumeric:'tabular-nums'}}>{v}</div>
      <div style={{fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.2em', color:'var(--fg-4)', textTransform:'uppercase', marginTop:4, fontWeight:600}}>{k}</div>
    </div>
  );
}

// ------------- AmmoCard -------------
function AmmoCard({ caliber, qty, burnPerWeek, status }) {
  const pct = Math.min(100, Math.round((qty / (burnPerWeek*16)) * 100));
  const fill = { ok:'#6B8E5A', low:'#C77A3B', crit:'#C33A2E' }[status.kind] || '#6B8E5A';
  const weeks = Math.floor(qty / burnPerWeek);
  return (
    <div className="card">
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline'}}>
        <div style={{fontFamily:'var(--font-display)', fontSize:22, color:'var(--fg-1)', letterSpacing:'0.02em'}}>{caliber}</div>
        <Badge kind={status.kind==='ok'?'ready':status.kind==='low'?'low':'attention'}>{status.label}</Badge>
      </div>
      <div style={{fontFamily:'var(--font-display)', fontSize:30, color:'var(--fg-1)', letterSpacing:'0.02em', fontVariantNumeric:'tabular-nums', marginTop:8, lineHeight:1}}>
        {qty.toLocaleString()}
        <span style={{fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.2em', color:'var(--fg-4)', marginLeft:8, fontWeight:600}}>ROUNDS</span>
      </div>
      <div style={{height:6, background:'var(--rh-obsidian-500)', borderRadius:1, overflow:'hidden', marginTop:10}}>
        <div style={{height:'100%', width:`${pct}%`, background:fill}}/>
      </div>
      <div style={{display:'flex', justifyContent:'space-between', fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.2em', color:'var(--fg-4)', textTransform:'uppercase', fontWeight:600, marginTop:6}}>
        <span>Burn {burnPerWeek}/wk</span><span>~{weeks}wk</span>
      </div>
    </div>
  );
}

// ------------- AlertCard -------------
function AlertCard({ kind='due', title, sub, value, valueSub }) {
  const borderColor = { crit:'var(--rh-dusty-red)', due:'var(--rh-brass)', ok:'#6B8E5A' }[kind];
  const Icon = kind==='crit' ? I.warn : kind==='ok' ? I.check : I.clock;
  const iconColor = kind==='crit' ? 'var(--rh-dusty-red)' : kind==='ok' ? '#8AA37A' : 'var(--rh-brass)';
  return (
    <div className="card" style={{borderLeft:`3px solid ${borderColor}`, display:'grid', gridTemplateColumns:'auto 1fr auto', gap:14, alignItems:'center'}}>
      <div style={{width:32, height:32, borderRadius:2, background:'var(--rh-obsidian-700)', display:'flex', alignItems:'center', justifyContent:'center', color: iconColor}}><Icon/></div>
      <div>
        <div style={{fontFamily:'var(--font-ui)', fontSize:13, fontWeight:600, color:'var(--fg-1)', textTransform:'uppercase', letterSpacing:'0.06em', lineHeight:1.1}}>{title}</div>
        <div style={{fontFamily:'var(--font-body)', fontSize:12, color:'var(--fg-3)', marginTop:3}}>{sub}</div>
      </div>
      <div style={{textAlign:'right'}}>
        <div style={{fontFamily:'var(--font-display)', fontSize:20, color: kind==='crit'?'var(--rh-dusty-red)':kind==='ok'?'#8AA37A':'var(--fg-1)', letterSpacing:'0.02em', fontVariantNumeric:'tabular-nums', lineHeight:1}}>{value}</div>
        <div style={{fontFamily:'var(--font-ui)', fontSize:8, letterSpacing:'0.2em', color:'var(--fg-4)', textTransform:'uppercase', marginTop:3, fontWeight:600}}>{valueSub}</div>
      </div>
    </div>
  );
}

// ------------- Session row -------------
function SessionRow({ d, m, title, sub, rounds }) {
  return (
    <div style={{display:'grid', gridTemplateColumns:'56px 1fr auto', gap:12, alignItems:'center', padding:'12px 0', borderBottom:'1px solid var(--border-hairline)'}}>
      <div>
        <div style={{fontFamily:'var(--font-display)', fontSize:22, color:'var(--fg-1)', letterSpacing:'0.04em', lineHeight:1}}>{d}</div>
        <div style={{fontFamily:'var(--font-ui)', fontSize:10, color:'var(--fg-4)', letterSpacing:'0.22em', textTransform:'uppercase', marginTop:2, fontWeight:600}}>{m}</div>
      </div>
      <div>
        <div style={{fontFamily:'var(--font-ui)', fontSize:12, color:'var(--fg-1)', textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:600}}>{title}</div>
        <div style={{fontFamily:'var(--font-body)', fontSize:11, color:'var(--fg-3)', marginTop:2}}>{sub}</div>
      </div>
      <div style={{textAlign:'right'}}>
        <div style={{fontFamily:'var(--font-display)', fontSize:18, color:'var(--rh-brass-400)', fontVariantNumeric:'tabular-nums', letterSpacing:'0.02em', lineHeight:1}}>{rounds}</div>
        <div style={{fontFamily:'var(--font-ui)', fontSize:8, color:'var(--fg-4)', letterSpacing:'0.2em', textTransform:'uppercase', marginTop:2, fontWeight:600}}>Rounds</div>
      </div>
    </div>
  );
}

Object.assign(window, { I, GunSil, Wedge, Ring, Badge, Button, TopBar, BottomTabs, SectionHead, FirearmCard, AmmoCard, AlertCard, SessionRow, Stat });
