/* Goals library — curated training goals organized by level.
   v4.8: addresses the user's request for a "list of goals ranked beginner,
   intermediate, advanced" with assignment to a gun. */

const GOALS = [
  // BEGINNER
  { id:'beg-1',  level:'BEG', title:'Safe operating fundamentals', sub:'Muzzle discipline · trigger discipline · ready position', target:'PISTOL', sessions:'3-5 sessions' },
  { id:'beg-2',  level:'BEG', title:'Consistent two-handed grip', sub:'Same hold every time · no rotation under recoil', target:'PISTOL', sessions:'Ongoing' },
  { id:'beg-3',  level:'BEG', title:'Sight alignment + sight picture', sub:'Front sight focus · clean horizontal/vertical alignment', target:'PISTOL · RIFLE', sessions:'2-3 sessions' },
  { id:'beg-4',  level:'BEG', title:'5 shots in a saucer at 7 yards', sub:'Slow fire · group consistency', target:'PISTOL', sessions:'5 sessions' },
  { id:'beg-5',  level:'BEG', title:'Smooth trigger press', sub:'No anticipation · no flinch · no jerk', target:'PISTOL · RIFLE', sessions:'Ongoing' },

  // INTERMEDIATE
  { id:'int-1',  level:'INT', title:'Sub-3s draw to first shot', sub:'From concealment · 7-yd target zone', target:'PISTOL · CARRY', sessions:'~20 reps weekly' },
  { id:'int-2',  level:'INT', title:'Bill Drill in under 5s', sub:'6 shots in A-zone at 7 yd · clean cadence', target:'PISTOL', sessions:'Weekly' },
  { id:'int-3',  level:'INT', title:'Tactical and emergency reloads', sub:'Both types · index pocket reach · keep gun up', target:'PISTOL', sessions:'5-10 sessions' },
  { id:'int-4',  level:'INT', title:'Strong-hand only shooting', sub:'One-handed groups at 5 yd · then 10 yd', target:'PISTOL', sessions:'Monthly maintenance' },
  { id:'int-5',  level:'INT', title:'Holster work + concealment draw', sub:'Draw + reholster · intent + repeatability', target:'PISTOL · CARRY', sessions:'Weekly dry fire + monthly live' },

  // ADVANCED
  { id:'adv-1',  level:'ADV', title:'Sub-2s draw to first shot, consistent', sub:'Pressure-tested · 5 consecutive sessions', target:'PISTOL · CARRY', sessions:'Tracked across weeks' },
  { id:'adv-2',  level:'ADV', title:'Sub-1.5s splits at 7 yd', sub:'Bill Drill cadence · A-zone hits', target:'PISTOL', sessions:'Weekly' },
  { id:'adv-3',  level:'ADV', title:'25-yard precision', sub:'5 shots in a 4-inch group · slow fire', target:'PISTOL', sessions:'Bi-weekly' },
  { id:'adv-4',  level:'ADV', title:'El Presidente', sub:'6 targets · turn · transition · reload · all under 10s', target:'PISTOL', sessions:'Monthly' },
  { id:'adv-5',  level:'ADV', title:'Failure to stop drill', sub:'2 to body + 1 to head · 7 yd · under 2.5s', target:'PISTOL · CARRY', sessions:'Weekly' },

  // RIFLE
  { id:'rif-1',  level:'RIF', title:'Zero confirm + retain through 500 rds', sub:'Hold zero across cleaning + carry events', target:'RIFLE', sessions:'After every transport' },
  { id:'rif-2',  level:'RIF', title:'Standing → kneeling → prone transitions', sub:'Position changes under time pressure', target:'RIFLE', sessions:'Monthly' },
  { id:'rif-3',  level:'RIF', title:'100 / 200 / 300 yd shooting', sub:'Build comfort across realistic distances', target:'RIFLE', sessions:'Quarterly outdoor' },
];

const LEVELS = {
  BEG: { label:'Beginner',     color:'#A6C293', tint:'rgba(107,142,90,0.14)', border:'rgba(107,142,90,0.40)' },
  INT: { label:'Intermediate', color:'var(--rh-brass-400)', tint:'var(--rh-brass-tint-08)', border:'var(--rh-brass-tint-32)' },
  ADV: { label:'Advanced',     color:'#E48A82', tint:'rgba(195,58,46,0.14)', border:'rgba(195,58,46,0.40)' },
  RIF: { label:'Rifle',        color:'var(--rh-steel-400)', tint:'var(--rh-steel-tint-12)', border:'var(--rh-steel-tint-24)' },
};

function GoalsLibrary({ go }) {
  const [filter, setFilter] = React.useState('ALL');
  // For prototype: simulate goals already being tracked
  const [tracking, setTracking] = React.useState(new Set(['int-1','int-2']));

  const toggleTrack = (id) => {
    setTracking(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const visible = filter === 'ALL'
    ? GOALS
    : GOALS.filter(g => g.level === filter);

  return (
    <>
      <TopBar title="Goals library"/>
      <div className="screen">
        <BackRow to="record" label="Record" go={go}/>
        <CollapsingHero
          eyebrow="Training goals · curated"
          headline="Library"
          summary={`${GOALS.length} goals · ${tracking.size} active`}
          right={<TourButton onClick={()=>alert('Goals library tour — coming next pass.')}/>}
        />

        {/* Explainer */}
        <div className="card" style={{background:'transparent', borderStyle:'dashed', borderColor:'var(--rh-brass-tint-32)', padding:'10px 12px'}}>
          <div className="label-md" style={{color:'var(--rh-brass-400)'}}>How goals work</div>
          <div className="rh-body-sm" style={{marginTop:6, color:'var(--rh-bone-300)', fontSize:11}}>Pick goals to track from this curated library. Each is assigned to one of your guns. Tag a session with a goal during logging — progress accrues over time and shows on the gun's Service Record.</div>
        </div>

        {/* Level filters */}
        <LabelRule>Filter</LabelRule>
        <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
          <Pill on={filter==='ALL'} onClick={()=>setFilter('ALL')}>All ({GOALS.length})</Pill>
          {Object.entries(LEVELS).map(([key, cfg]) => (
            <Pill key={key} on={filter===key} onClick={()=>setFilter(key)}>
              {cfg.label} ({GOALS.filter(g => g.level===key).length})
            </Pill>
          ))}
        </div>

        {/* Goal cards — grouped by level when ALL, flat otherwise */}
        {filter === 'ALL' ? (
          Object.keys(LEVELS).map(level => (
            <React.Fragment key={level}>
              <GoalSectionHeader level={level}/>
              <div style={{display:'flex', flexDirection:'column', gap:8}}>
                {GOALS.filter(g => g.level === level).map(g => (
                  <GoalCard key={g.id} goal={g} tracking={tracking.has(g.id)} onToggle={()=>toggleTrack(g.id)}/>
                ))}
              </div>
            </React.Fragment>
          ))
        ) : (
          <>
            <GoalSectionHeader level={filter}/>
            <div style={{display:'flex', flexDirection:'column', gap:8}}>
              {visible.map(g => (
                <GoalCard key={g.id} goal={g} tracking={tracking.has(g.id)} onToggle={()=>toggleTrack(g.id)}/>
              ))}
            </div>
          </>
        )}

        <div style={{marginTop:18}}>
          <Button variant="secondary" block onClick={()=>go('record')}>← Back to Record</Button>
        </div>
      </div>
    </>
  );
}

function GoalSectionHeader({ level }) {
  const cfg = LEVELS[level];
  return (
    <div style={{display:'flex', alignItems:'baseline', gap:12, margin:'22px 4px 12px'}}>
      <span style={{width:9, height:9, borderRadius:'50%', background:cfg.color, alignSelf:'center'}}/>
      <div style={{fontFamily:'var(--font-display)', fontSize:20, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1}}>{cfg.label}</div>
      <div style={{flex:1, height:1, background:'var(--border-hairline)'}}/>
    </div>
  );
}

function GoalCard({ goal, tracking, onToggle }) {
  const cfg = LEVELS[goal.level];
  return (
    <div className="card" style={{padding:'12px 14px', borderLeft:`3px solid ${cfg.color}`}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:8}}>
        <div style={{flex:1}}>
          <div style={{display:'flex', alignItems:'baseline', gap:8}}>
            <span style={{
              padding:'2px 6px',
              background:cfg.tint, color:cfg.color,
              border:`1px solid ${cfg.border}`,
              fontFamily:'var(--font-ui)', fontSize:8, letterSpacing:'0.22em',
              textTransform:'uppercase', fontWeight:600, lineHeight:1,
            }}>{cfg.label}</span>
            <span className="label-md" style={{color:'var(--rh-bone-500)', fontSize:8, letterSpacing:'0.18em'}}>{goal.target}</span>
          </div>
          <div style={{fontFamily:'var(--font-display)', fontSize:17, color:'var(--fg-1)', letterSpacing:'0.02em', lineHeight:1.1, marginTop:8}}>{goal.title}</div>
          <div className="rh-body-sm" style={{marginTop:4, color:'var(--rh-bone-300)'}}>{goal.sub}</div>
          <div className="label-md" style={{marginTop:8, color:'var(--rh-bone-500)', fontSize:8}}>{goal.sessions}</div>
        </div>
      </div>
      <div style={{marginTop:10, paddingTop:10, borderTop:'1px solid var(--border-hairline)'}}>
        <button
          onClick={onToggle}
          style={{
            width:'100%',
            padding:'9px',
            background: tracking ? cfg.tint : 'transparent',
            color: tracking ? cfg.color : 'var(--rh-brass-400)',
            border:`1px solid ${tracking ? cfg.border : 'var(--rh-brass-tint-32)'}`,
            borderRadius:2, cursor:'pointer',
            fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'0.16em',
            textTransform:'uppercase', fontWeight:600,
            display:'inline-flex', alignItems:'center', justifyContent:'center', gap:6,
          }}>
          {tracking ? <>✓ Tracking · {goal.level==='RIF' ? '11.5″ AR-15' : 'Glock 19 Gen5'}</> : 'Track this goal →'}
        </button>
      </div>
    </div>
  );
}

window.GoalsLibrary = GoalsLibrary;
