/* Extra Roundhouse components specific to the wireframes. Adds to base
   components.jsx (Ring, Badge, Button, FirearmCard, AmmoCard, etc).
   All exports go on window so the screen files can use them globally. */

const { useState: useStateX } = React;

// More icons (geometric, brass, 2px stroke — Roundhouse style)
const X = {
  back: (p={}) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m15 18-6-6 6-6"/></svg>,
  fwd:  (p={}) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m9 18 6-6-6-6"/></svg>,
  plus2:(p={}) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14"/></svg>,
  play: (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="currentColor" stroke="none"><path d="M6 4l14 8L6 20V4z"/></svg>,
  edit: (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 20h4l10-10-4-4L4 16v4zM14 6l4 4"/></svg>,
  cart: (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="9" cy="20" r="1.5"/><circle cx="18" cy="20" r="1.5"/><path d="M2 3h3l3 13h12l2-9H6"/></svg>,
  upload:(p={})=> <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 16V4M6 10l6-6 6 6M4 20h16"/></svg>,
  doc:  (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M14 3H6v18h12V7l-4-4z"/><path d="M14 3v4h4"/></svg>,
  cal:  (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="5" width="18" height="16" rx="1"/><path d="M3 9h18M8 3v4M16 3v4"/></svg>,
  loc:  (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 22s7-7 7-13a7 7 0 1 0-14 0c0 6 7 13 7 13z"/><circle cx="12" cy="9" r="2.5"/></svg>,
  flag: (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 21V4h12l-2 4 2 4H4"/></svg>,
  bolt: (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M13 2 4 14h7l-2 8 9-12h-7l2-8z"/></svg>,
  list: (p={}) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg>,
};

// --- Big numeric block ---
function BigNum({ v, k, sub, color }) {
  return (
    <div>
      <div style={{fontFamily:'var(--font-display)', fontSize:48, lineHeight:1, color: color || 'var(--fg-1)', letterSpacing:'0.02em', fontVariantNumeric:'tabular-nums'}}>{v}</div>
      <div style={{fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.24em', color:'var(--fg-4)', textTransform:'uppercase', marginTop:6, fontWeight:600}}>{k}</div>
      {sub && <div style={{fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.22em', color:'var(--rh-brass-400)', textTransform:'uppercase', marginTop:2, fontWeight:600}}>{sub}</div>}
    </div>
  );
}

// --- Status pill (alternate style — wider) ---
function StatusPill({ kind='ready', children }) {
  const map = {
    ready:    { bg:'rgba(107,142,90,0.14)', fg:'#A6C293', br:'rgba(107,142,90,0.35)' },
    due:      { bg:'var(--rh-brass-tint-08)', fg:'var(--rh-brass-200)', br:'var(--rh-brass-tint-32)' },
    attention:{ bg:'rgba(195,58,46,0.14)', fg:'#E48A82', br:'rgba(195,58,46,0.4)' },
    low:      { bg:'rgba(199,122,59,0.14)', fg:'#E5B07E', br:'rgba(199,122,59,0.35)' },
    updated:  { bg:'transparent', fg:'var(--rh-brass-400)', br:'var(--rh-brass-tint-32)' },
    verified: { bg:'transparent', fg:'#A6C293', br:'rgba(138,163,122,0.45)' },
  };
  const c = map[kind] || map.ready;
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap:5,
      padding:'4px 8px',
      background:c.bg, color:c.fg, border:`1px solid ${c.br}`,
      borderRadius:1,
      fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'0.22em', fontWeight:600,
      textTransform:'uppercase', lineHeight:1,
    }}>
      <span style={{width:5, height:5, borderRadius:'50%', background:c.fg, opacity:0.85}}/>
      {children}
    </span>
  );
}

// --- Segmented ring (uses dashes — true brand motif) ---
function SegRing({ size=120, segments=24, filled=18, color='var(--rh-brass)', track='var(--rh-obsidian-500)', stroke=4, gap=3, children, rotate=-90 }) {
  const r = (size - stroke) / 2;
  const cx = size/2, cy = size/2;
  const segs = [];
  for (let i = 0; i < segments; i++) {
    const a1 = (i / segments) * 360 + rotate;
    const a2 = ((i + 1) / segments) * 360 + rotate - gap;
    const x1 = cx + r * Math.cos(a1 * Math.PI/180);
    const y1 = cy + r * Math.sin(a1 * Math.PI/180);
    const x2 = cx + r * Math.cos(a2 * Math.PI/180);
    const y2 = cy + r * Math.sin(a2 * Math.PI/180);
    const large = (a2 - a1) > 180 ? 1 : 0;
    const d = `M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2}`;
    segs.push(
      <path key={i} d={d} fill="none"
        stroke={i < filled ? color : track}
        strokeWidth={stroke}
        strokeLinecap="butt"/>
    );
  }
  return (
    <div style={{position:'relative', width:size, height:size, display:'inline-block'}}>
      <svg width={size} height={size}>{segs}</svg>
      <div style={{position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', textAlign:'center'}}>
        {children}
      </div>
    </div>
  );
}

// --- Tiny pill chip used in plan-trip / config selectors ---
function Pill({ children, on, onClick, kind }) {
  const cls = `chip ${on?'on':''}`;
  return <span className={cls} onClick={onClick}>{children}</span>;
}

// --- Back row (used at top of detail screens) ---
function BackRow({ to, label, go }) {
  return (
    <div style={{display:'flex', alignItems:'center', gap:8, marginTop:4, marginBottom:6}}>
      <button className="icon-btn" onClick={()=>go(to)} style={{color:'var(--rh-bone-300)'}}>
        <X.back s={16}/>
      </button>
      <span className="label-md" style={{color:'var(--rh-bone-500)'}}>{label}</span>
    </div>
  );
}

// --- Plain divider with caption ---
function LabelRule({ children, more }) {
  return (
    <div style={{display:'flex', alignItems:'center', gap:10, margin:'18px 0 8px'}}>
      <div className="label-md" style={{whiteSpace:'nowrap'}}>{children}</div>
      <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>
  );
}

// --- CollapsingHero: scrolls naturally at top; a thin sticky data bar
//     glues to top:44px (below the topbar) so once the hero scrolls away,
//     the user still sees a quick summary of the section state.
//     Pillar pages (Gear / Supply / Maintain / Record / Protect) use this.
//     v3.2: `right` slot lets each page drop a per-section action (e.g., a
//     '?' tour button) into the empty top-right corner of the hero. ---
function CollapsingHero({ eyebrow, headline, sub, summary, right }) {
  return (
    <>
      <div className="ch-hero" style={{position:'relative'}}>
        {right && <div className="ch-hero-right">{right}</div>}
        {eyebrow && <div className="ch-eyebrow">{eyebrow}</div>}
        <h1 className="ch-headline">{headline}</h1>
        {sub && <div className="ch-sub">{sub}</div>}
      </div>
      {summary && (
        <div className="ch-bar">
          <span className="ch-bar-summary">{summary}</span>
        </div>
      )}
    </>
  );
}

// --- QuickActionButton: small red "+ Label" button for the CollapsingHero
//     right slot. Saves the user from scrolling to the bottom of a page for
//     a primary add action. Pattern is reused across Gear / Supply / etc. ---
function QuickActionButton({ onClick, label, title }) {
  return (
    <button
      onClick={onClick}
      title={title || `Add ${label}`}
      style={{
        padding:'5px 10px',
        background:'var(--rh-dusty-red)',
        color:'var(--rh-bone-100)',
        border:'1px solid var(--rh-dusty-red)',
        borderRadius:2, cursor:'pointer',
        fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'0.16em',
        textTransform:'uppercase', fontWeight:600,
        display:'inline-flex', alignItems:'center', gap:5,
        whiteSpace:'nowrap',
      }}>
      <span style={{fontSize:14, lineHeight:1, fontFamily:'var(--font-display)'}}>+</span>
      {label}
    </button>
  );
}

// --- Tour button: standard "?" in a circle — universal help imagery.
//     Drops into the top-right of any CollapsingHero. The walkthrough
//     overlay is deferred to next pass; this is the entry point. ---
function TourButton({ onClick }) {
  return (
    <button
      title="Help · page tour"
      aria-label="Page tour"
      onClick={onClick || (()=>alert('Tour mode — coming next pass.'))}
      style={{
        background:'transparent',
        border:'1px solid var(--border-default)',
        color:'var(--rh-bone-300)',
        width:30, height:30,
        borderRadius:'50%',
        cursor:'pointer',
        display:'inline-flex', alignItems:'center', justifyContent:'center',
        padding:0,
        transition:'color 120ms ease, border-color 120ms ease, background 120ms ease',
      }}
      onMouseOver={e=>{e.currentTarget.style.color='var(--rh-bone-100)'; e.currentTarget.style.borderColor='var(--rh-bone-300)'; e.currentTarget.style.background='var(--rh-brass-tint-08)';}}
      onMouseOut={e=>{e.currentTarget.style.color='var(--rh-bone-300)'; e.currentTarget.style.borderColor='var(--border-default)'; e.currentTarget.style.background='transparent';}}>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>
        <path d="M12 17h.01"/>
      </svg>
    </button>
  );
}

// --- ReorderableSections: generic helper for letting the user reorder
//     page sections. v4.7 refactor: now CONTROLLED — the page owns the
//     editMode state and renders the trigger button wherever it wants
//     (typically the CollapsingHero's right slot, next to TourButton).
//     A compact instruction strip appears only when editMode is on. ---
function ReorderableSections({ defaultOrder, renderers, sectionLabels, editMode, onExit }) {
  const [order, setOrder] = React.useState(defaultOrder);

  const move = (id, dir) => {
    const idx = order.indexOf(id);
    if (idx < 0) return;
    const target = dir === 'up' ? idx - 1 : idx + 1;
    if (target < 0 || target >= order.length) return;
    const next = [...order];
    [next[idx], next[target]] = [next[target], next[idx]];
    setOrder(next);
  };
  const reset = () => setOrder(defaultOrder);
  const customized = JSON.stringify(order) !== JSON.stringify(defaultOrder);

  return (
    <>
      {editMode && (
        <ReorderInstructionStrip onExit={onExit} onReset={reset} customized={customized}/>
      )}
      {order.map((id, idx) => {
        const Render = renderers[id];
        if (!Render) return null;
        return (
          <div key={id} style={{position:'relative'}}>
            {editMode && (
              <ReorderControls
                id={id}
                label={(sectionLabels && sectionLabels[id]) || id}
                canMoveUp={idx > 0}
                canMoveDown={idx < order.length - 1}
                onUp={()=>move(id, 'up')}
                onDown={()=>move(id, 'down')}
              />
            )}
            <div style={editMode ? {opacity:0.85, pointerEvents:'none', border:'1px dashed var(--rh-brass-tint-32)', borderRadius:2, padding:'0 6px', marginTop:6, marginBottom:6} : {}}>
              <Render/>
            </div>
          </div>
        );
      })}
      {/* Bottom Customize entry (alternate path per user request) */}
      {!editMode && (
        <div style={{marginTop:14, display:'flex', justifyContent:'center'}}>
          <ReorderButton on={false} onToggle={()=>onExit && onExit('open')} compact/>
        </div>
      )}
    </>
  );
}

// --- ReorderButton: drop into CollapsingHero's right slot. Single icon,
//     same visual weight as TourButton. Tap toggles editMode. ---
function ReorderButton({ on, onToggle, compact }) {
  if (compact) {
    return (
      <button
        onClick={onToggle}
        title="Reorder sections"
        style={{
          background:'transparent',
          color:'var(--rh-bone-500)',
          border:'1px dashed var(--rh-brass-tint-32)',
          padding:'8px 14px', borderRadius:2,
          fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'0.18em',
          textTransform:'uppercase', fontWeight:600,
          cursor:'pointer',
          display:'inline-flex', alignItems:'center', gap:8,
        }}>
        <span style={{fontFamily:'var(--font-display)', fontSize:14, lineHeight:1}}>≡</span>
        Customize order
      </button>
    );
  }
  return (
    <button
      onClick={onToggle}
      title="Reorder sections"
      aria-label="Reorder sections"
      style={{
        background: on ? 'var(--rh-brass)' : 'transparent',
        color: on ? 'var(--rh-obsidian)' : 'var(--rh-bone-300)',
        border:`1px solid ${on ? 'var(--rh-brass)' : 'var(--border-default)'}`,
        width:30, height:30, padding:0,
        borderRadius:'50%',
        cursor:'pointer',
        display:'inline-flex', alignItems:'center', justifyContent:'center',
        fontFamily:'var(--font-display)', fontSize:16, lineHeight:1,
        transition:'color 120ms ease, border-color 120ms ease, background 120ms ease',
      }}
      onMouseOver={e=>{ if(!on){ e.currentTarget.style.color='var(--rh-bone-100)'; e.currentTarget.style.borderColor='var(--rh-bone-300)'; e.currentTarget.style.background='var(--rh-brass-tint-08)'; } }}
      onMouseOut={e=>{ if(!on){ e.currentTarget.style.color='var(--rh-bone-300)'; e.currentTarget.style.borderColor='var(--border-default)'; e.currentTarget.style.background='transparent'; } }}>
      ≡
    </button>
  );
}

function ReorderInstructionStrip({ onExit, onReset, customized }) {
  return (
    <div style={{
      position:'sticky', top:44, zIndex:5,
      margin:'8px 0 6px',
      padding:'10px 12px',
      display:'flex', justifyContent:'space-between', alignItems:'center', gap:10,
      background:'rgba(184,154,86,0.14)',
      border:'1px solid var(--rh-brass)',
      borderLeft:'3px solid var(--rh-brass)',
      borderRadius:2,
    }}>
      <div style={{display:'flex', alignItems:'center', gap:10}}>
        <span style={{color:'var(--rh-brass-400)', fontFamily:'var(--font-display)', fontSize:18, lineHeight:1}}>≡</span>
        <div>
          <div className="label-md" style={{color:'var(--rh-brass-400)', fontSize:10, letterSpacing:'0.18em'}}>Reorder mode</div>
          <div className="rh-body-sm" style={{marginTop:2, color:'var(--rh-bone-300)', fontSize:10}}>Tap ↑↓ on each section · Done to save</div>
        </div>
      </div>
      <div style={{display:'flex', gap:6, alignItems:'center'}}>
        {customized && (
          <button onClick={onReset} style={{background:'transparent', border:0, color:'var(--rh-bone-500)', padding:'6px 8px', cursor:'pointer', fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'0.18em', textTransform:'uppercase', fontWeight:600}}>Reset</button>
        )}
        <button
          onClick={()=>onExit && onExit('close')}
          style={{
            padding:'8px 14px',
            background:'var(--rh-brass)',
            color:'var(--rh-obsidian)',
            border:'1px solid var(--rh-brass)',
            borderRadius:2, cursor:'pointer',
            fontFamily:'var(--font-ui)', fontSize:11, letterSpacing:'0.16em',
            textTransform:'uppercase', fontWeight:600,
          }}>
          Done ✓
        </button>
      </div>
    </div>
  );
}

function ReorderControls({ id, label, canMoveUp, canMoveDown, onUp, onDown }) {
  return (
    <div style={{
      position:'sticky', top:90,  /* sit below the topbar + instruction strip */
      zIndex:3,
      background:'var(--rh-obsidian)',
      padding:'4px 6px',
      display:'grid', gridTemplateColumns:'auto 1fr auto auto', gap:8, alignItems:'center',
      pointerEvents:'auto',
    }}>
      <span style={{color:'var(--rh-brass-400)', fontFamily:'var(--font-display)', fontSize:14, letterSpacing:'0.06em', lineHeight:1}}>≡</span>
      <span className="label-md" style={{color:'var(--rh-brass-400)', letterSpacing:'0.18em'}}>{label}</span>
      <button
        onClick={onUp}
        disabled={!canMoveUp}
        style={{
          padding:'5px 8px', background:'var(--bg-elevated-1)',
          border:'1px solid var(--rh-brass-tint-32)', borderRadius:2,
          cursor: canMoveUp ? 'pointer' : 'not-allowed',
          color: canMoveUp ? 'var(--rh-brass-400)' : 'var(--rh-bone-700)',
          fontFamily:'var(--font-display)', fontSize:14,
        }}>↑</button>
      <button
        onClick={onDown}
        disabled={!canMoveDown}
        style={{
          padding:'5px 8px', background:'var(--bg-elevated-1)',
          border:'1px solid var(--rh-brass-tint-32)', borderRadius:2,
          cursor: canMoveDown ? 'pointer' : 'not-allowed',
          color: canMoveDown ? 'var(--rh-brass-400)' : 'var(--rh-bone-700)',
          fontFamily:'var(--font-display)', fontSize:14,
        }}>↓</button>
    </div>
  );
}

Object.assign(window, { X, BigNum, StatusPill, SegRing, Pill, BackRow, LabelRule, CollapsingHero, TourButton, ReorderableSections, ReorderButton, QuickActionButton });
