/* Tour overlay — onboarding walkthrough + per-page deep dives.
   v4.7: full implementation.
   - The OVERALL tour fires once on first app load (high-level walkthrough)
   - Each page's "?" button opens a PER-PAGE tour with more specific content
   - From Settings, the user can replay any tour anytime */

const TOURS = {
  overall: [
    {
      title: 'Welcome to Roundhouse',
      body: 'A living ownership and training system for shooters who actually shoot. Use it. Maintain it. Prove it. Every range trip strengthens your record.',
      eyebrow: 'GETTING STARTED · 1 OF 5',
    },
    {
      title: 'The home ring',
      body: 'Four pillars surround your Record: Gear, Supply, Maintain, Protect. Each shows its current state and pulses red when something needs attention. Tap a pillar to drill in.',
      eyebrow: 'YOUR COMMAND CENTER',
    },
    {
      title: 'Plan · Live · Log',
      body: 'Three ways to capture a range trip. Plan it ahead, run a Live session at the range, or Log it after the fact. Same data, different moments.',
      eyebrow: 'THE CENTRAL LOOP',
    },
    {
      title: 'Five tabs · one loop',
      body: 'Use is where you live — plan trips, log sessions, real shooting. Gear, Supply, and Maintain are the foundations that fuel it. Record is where every trip becomes history. Protect — your documentation vault — lives one tap inside Record.',
      eyebrow: 'NAVIGATION',
    },
    {
      title: 'Page tours · Settings',
      body: 'Every pillar page has a "?" button in the top-right with a deeper walkthrough of just that page. Settings (menu icon) holds the defaults that shape your tracking — you can replay any tour from there.',
      eyebrow: 'GO DEEPER ANY TIME',
    },
  ],
  home: [
    { eyebrow:'PAGE TOUR · 1 OF 4', title:'The ring', body:'Each pillar shows current state. Red pulse = something is overdue. Orange = low supply. Brass = ready. Tap any pillar to drill in.' },
    { eyebrow:'PAGE TOUR · 2 OF 4', title:'The center disc', body:'Your Roundhouse Record. The big number is your lifetime rounds across all gear. Tap to see history.' },
    { eyebrow:'PAGE TOUR · 3 OF 4', title:'Plan · Live · Log', body:'Three entry points to a range trip. Plan before you go, run Live at the range, Log retroactively.' },
    { eyebrow:'PAGE TOUR · 4 OF 4', title:'Last session', body:'Your most recent activity. Tap "All" to browse the full session history.' },
  ],
  gear: [
    { eyebrow:'PAGE TOUR · 1 OF 4', title:'Four categories', body:'Guns, Accessories, Suppressors, Modifications. Tap any tile to open that inventory.' },
    { eyebrow:'PAGE TOUR · 2 OF 4', title:'Quick add', body:'The + button in the top-right adds a new gun without entering the inventory first. Each subpage has its own + for that category.' },
    { eyebrow:'PAGE TOUR · 3 OF 4', title:'Customize order', body:'Tap the ≡ button to reorder categories. Put what you use most at the top.' },
    { eyebrow:'PAGE TOUR · 4 OF 4', title:'Tap to drill', body:'Each category gets its own page. From there, tap a gun (or suppressor) to see its full record.' },
  ],
  guns: [
    { eyebrow:'PAGE TOUR · 1 OF 3', title:'Your safe inventory', body:'Every gun shows quick stats: rounds, last trip, malfunctions. Grouped by type (pistol / rifle / PCC).' },
    { eyebrow:'PAGE TOUR · 2 OF 3', title:'Tap a gun', body:'Lands on the gun\'s Gear page — current configuration, default ammo, modifications, photos. The Service Record is one tap away.' },
    { eyebrow:'PAGE TOUR · 3 OF 3', title:'Add a firearm', body:'Use the + button top-right. Three fields gets you to value: manufacturer, model, caliber. Everything else is fillable later.' },
  ],
  accessories: [
    { eyebrow:'PAGE TOUR · 1 OF 2', title:'Optics, lights, mags', body:'Items that attach and detach from guns. Triggers and stocks live under Modifications instead — those are semi-permanent.' },
    { eyebrow:'PAGE TOUR · 2 OF 2', title:'Add and mount', body:'Use the + button to add an accessory to inventory. To put it on a gun, open the gun\'s config editor.' },
  ],
  suppressors: [
    { eyebrow:'PAGE TOUR · 1 OF 3', title:'NFA-regulated', body:'Suppressors have their own service records, paperwork, and round counts.' },
    { eyebrow:'PAGE TOUR · 2 OF 3', title:'Across many guns', body:'A suppressor accumulates rounds across every gun it\'s been mounted on. Tap to see the per-host breakdown.' },
    { eyebrow:'PAGE TOUR · 3 OF 3', title:'Add a can', body:'Use the + button. Tracks Form 4 status, tax stamp, and starting round count if used.' },
  ],
  supply: [
    { eyebrow:'PAGE TOUR · 1 OF 4', title:'Caliber health at a glance', body:'Each caliber row shows on-hand vs par + a status badge (OK / LOW / CRITICAL) based on burn rate.' },
    { eyebrow:'PAGE TOUR · 2 OF 4', title:'Tap to drill', body:'Open a caliber to see breakdown by use category, grain weight, and individual purchase lots.' },
    { eyebrow:'PAGE TOUR · 3 OF 4', title:'Add a lot', body:'Use the + button top-right when you buy ammo. We categorize at entry — caliber, type, grain, brand, cost. Cost-per-round computes automatically.' },
    { eyebrow:'PAGE TOUR · 4 OF 4', title:'Customize order', body:'≡ button to move sections around.' },
  ],
  maintain: [
    { eyebrow:'PAGE TOUR · 1 OF 3', title:'What is due', body:'Three component categories at top: Firearms, Suppressors, Optics. Each shows ready/due/overdue counts.' },
    { eyebrow:'PAGE TOUR · 2 OF 3', title:'Customizable rules', body:'Default intervals seeded per firearm type. Edit in Settings, or per-gun on each Service Record.' },
    { eyebrow:'PAGE TOUR · 3 OF 3', title:'Log a service', body:'+ button top-right. Pick gun, event type, optional cost / parts / notes. Resets the matching rule and writes a milestone.' },
  ],
  record: [
    { eyebrow:'PAGE TOUR · 1 OF 4', title:'Your living record', body:'Top stats: lifetime rounds, sessions, days active. Below: per-gun service records, training goals, milestones.' },
    { eyebrow:'PAGE TOUR · 2 OF 4', title:'Service records', body:'Each gun has its own record. Tap any card to see history, malfunctions, configuration timeline, service log.' },
    { eyebrow:'PAGE TOUR · 3 OF 4', title:'Suppressors separate', body:'Suppressors are steel-accented and listed under their own section. Their records aggregate across every gun they\'ve been on.' },
    { eyebrow:'PAGE TOUR · 4 OF 4', title:'Customize what matters', body:'≡ button to reorder sections. If goals matter more than gallery, move them up. Headline stats stay pinned.' },
  ],
  servicerecord: [
    { eyebrow:'PAGE TOUR · 1 OF 4', title:'A gun\'s living record', body:'Everything that happened with this firearm — rounds, sessions, modifications, malfunctions, service.' },
    { eyebrow:'PAGE TOUR · 2 OF 4', title:'Overview · Service · Documents', body:'Three tabs. Overview = stats and trends. Service = open rules + history. Documents = receipts, photos, NFA.' },
    { eyebrow:'PAGE TOUR · 3 OF 4', title:'Config lives in Gear', body:'To swap an accessory or change default ammo, jump to the gun\'s Gear page via the link at top. This Service Record is read-only history.' },
    { eyebrow:'PAGE TOUR · 4 OF 4', title:'Customize Overview', body:'≡ button to reorder Overview sections. If you don\'t shoot suppressed, drag that section down. If reliability matters most, pin it up top.' },
  ],
  protect: [
    { eyebrow:'PAGE TOUR · 1 OF 3', title:'Documentation vault', body:'Receipts, NFA paperwork, photos, insurance schedules — all linked to the gear they protect.' },
    { eyebrow:'PAGE TOUR · 2 OF 3', title:'Three pivots', body:'Browse by gear item, by document type, or by status (what\'s expiring, what\'s missing).' },
    { eyebrow:'PAGE TOUR · 3 OF 3', title:'Claim packet', body:'Generate a single PDF for an insurance claim covering selected gear: serial numbers, photos, replacement values, NFA paperwork.' },
  ],
};

function TourOverlay({ tourId, onClose }) {
  const steps = TOURS[tourId] || [];
  const [idx, setIdx] = React.useState(0);
  React.useEffect(() => { setIdx(0); }, [tourId]);

  if (!steps.length) return null;
  const step = steps[idx];
  const isLast = idx === steps.length - 1;
  const isOverall = tourId === 'overall';

  // Card floats above the bottom tabs — screen stays fully visible + interactive
  return (
    <div style={{
      position:'absolute', bottom:80, left:12, right:12,
      zIndex:50,
      pointerEvents:'none',
    }}>
      <div style={{
        pointerEvents:'auto',
        background:'rgba(12,12,16,0.97)',
        border:'1px solid var(--rh-bone-700)',
        borderTop:'3px solid var(--rh-brass)',
        borderRadius:2,
        padding:'14px 16px 12px',
        boxShadow:'0 8px 40px rgba(0,0,0,0.8), 0 0 0 1px rgba(184,154,86,0.12)',
      }}>

        <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:8}}>
          <span className="label-md" style={{color:'var(--rh-brass-400)', letterSpacing:'0.22em', fontSize:9}}>{step.eyebrow}</span>
          <button
            onClick={onClose}
            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}}>
            {isLast ? 'Close ×' : 'Skip ×'}
          </button>
        </div>

        <div style={{fontFamily:'var(--font-display)', fontSize:20, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1.1, textTransform:'uppercase', marginBottom:8}}>{step.title}</div>

        <p style={{fontFamily:'var(--font-body)', fontSize:13, color:'var(--rh-bone-300)', lineHeight:1.5, margin:0}}>{step.body}</p>

        <div style={{display:'flex', justifyContent:'center', gap:5, margin:'12px 0'}}>
          {steps.map((_, i) => (
            <span key={i} onClick={()=>setIdx(i)} style={{
              width: i===idx ? 16 : 5, height:5,
              background: i===idx ? 'var(--rh-brass)' : 'var(--rh-bone-700)',
              borderRadius:1, cursor:'pointer',
              transition:'width 120ms ease',
            }}/>
          ))}
        </div>

        <div style={{display:'grid', gridTemplateColumns: idx > 0 ? '1fr 1fr' : '1fr', gap:8}}>
          {idx > 0 && (
            <button onClick={()=>setIdx(idx-1)} className="btn btn-secondary" style={{padding:'10px 12px', fontSize:11}}>← Back</button>
          )}
          {isLast ? (
            <button onClick={onClose} className="btn btn-primary" style={{padding:'10px 12px', fontSize:11}}>
              {isOverall ? 'Start using Roundhouse →' : 'Done'}
            </button>
          ) : (
            <button onClick={()=>setIdx(idx+1)} className="btn btn-primary" style={{padding:'10px 12px', fontSize:11}}>Next →</button>
          )}
        </div>
      </div>
    </div>
  );
}

window.TourOverlay = TourOverlay;
window.__rhTours = TOURS;
