// Left "Saved jobs" rail — dark navy panel
const { color: JRC, font: JRF, shadow: JRS } = window.FF;

function JobsRail({ jobs, selectedId, onSelect, vocab, splitBySource, actionable, focus, actionCounts, onOpenAllJobs }) {
  return (
    <aside data-screen-label="Saved jobs rail" style={{
      width: 310, background: JRC.shade[880], color: '#fff',
      display: 'flex', flexDirection: 'column', flex: 'none', minHeight: '100vh',
    }}>
      {/* Header */}
      <div style={{ padding: '20px 20px 12px', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <h2 style={{ margin:0, fontSize:18, fontWeight:800, color:'#fff', letterSpacing:'-.01em' }}>Saved jobs</h2>
        <button style={{
          display:'inline-flex', alignItems:'center', gap:4, padding:'6px 11px',
          background: JRC.highlight[500], color:'#fff', border:0, borderRadius:8,
          fontSize:13, fontWeight:600, cursor:'pointer'
        }}>
          <span style={{ fontWeight:700 }}>＋</span> New job
        </button>
      </div>

      {/* Search */}
      <div style={{ padding:'4px 20px 12px' }}>
        <div style={{ position:'relative' }}>
          <input placeholder="Search by job name or ATS Req ID" style={{
            width:'100%', boxSizing:'border-box', padding:'9px 12px 9px 12px',
            background: JRC.shade[860], border:`1px solid ${JRC.shade[840]}`,
            borderRadius:8, color:'#fff', fontSize:13, fontFamily: JRF.sans, outline:'none',
          }}/>
        </div>
      </div>

      {/* My jobs / All jobs toggle */}
      <div style={{ padding:'0 20px 12px' }}>
        <div style={{
          display:'flex', background: JRC.shade[860], borderRadius:8, padding:3,
        }}>
          <button style={{
            flex:1, padding:'7px 10px', background:'#fff', color: JRC.shade[880],
            border:0, borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer'
          }}>My jobs</button>
          <button style={{
            flex:1, padding:'7px 10px', background:'transparent', color:'#fff',
            border:0, borderRadius:6, fontSize:13, fontWeight:500, cursor:'pointer', opacity:.7
          }}>All jobs</button>
        </div>
      </div>

      {/* Filters row */}
      <div style={{ padding:'0 20px 14px', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <button style={{
          display:'inline-flex', alignItems:'center', gap:6, background:'transparent', color:'#fff',
          border:0, fontSize:13, fontWeight:500, cursor:'pointer', padding:0,
        }}>
          <img src="assets/icons/filter-lines-20.svg" width={14} height={14} style={{ filter:'brightness(0) invert(1)', opacity:.85 }}/>
          Filters
        </button>
        <div style={{ display:'flex', alignItems:'center', gap:8, fontSize:12, color:'#94A3B8' }}>
          Show active jobs only
          <span style={{
            width:28, height:16, borderRadius:9999, background: JRC.shade[840], position:'relative',
            display:'inline-block'
          }}>
            <span style={{ position:'absolute', top:2, left:2, width:12, height:12, borderRadius:'50%', background:'#fff' }}/>
          </span>
        </div>
      </div>

      {/* Attention filter — a sibling of "Show active jobs only", not a new
          navigation concept. Scopes every stage in the candidates panel. */}
      {focus && (
        <div style={{ padding:'0 20px 12px', display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ flex:1, fontSize:12, color: focus.on ? '#fff' : '#94A3B8' }}>Only candidates who need my action</span>
          <button onClick={focus.onToggle} role="switch" aria-checked={focus.on} style={{
            flex:'none', width:28, height:16, borderRadius:9999, border:0, cursor:'pointer', padding:2,
            background: focus.on ? JRC.primary[500] : JRC.shade[840], transition:'background .12s',
          }}>
            <span style={{
              display:'block', width:12, height:12, borderRadius:'50%', background:'#fff',
              transform: focus.on ? 'translateX(12px)' : 'none', transition:'transform .12s',
            }}/>
          </button>
        </div>
      )}

      {/* Cross-job entry point. The rail is the only panel that is already
          unscoped from a single req, so the aggregate belongs here — the cards
          below give the per-job breakdown, this opens all of it at once. */}
      {onOpenAllJobs && (() => {
        const total = Object.values(actionCounts || {}).reduce((a, n) => a + n, 0);
        if (!total) return null;
        return (
          <div style={{ padding:'0 14px 10px' }}>
            <button onClick={onOpenAllJobs} style={{
              width:'100%', display:'flex', alignItems:'center', gap:9, textAlign:'left', cursor:'pointer',
              padding:'10px 12px', borderRadius:10,
              background: JRC.primary[500] + '1F', border:`1px solid ${JRC.primary[500]}59`,
            }}>
              <span style={{ width:7, height:7, borderRadius:'50%', flex:'none', background: JRC.primary[500] }}/>
              <span style={{ flex:1, minWidth:0 }}>
                <span style={{ display:'block', fontSize:12.5, fontWeight:700, color:'#fff' }}>{total} need you</span>
                <span style={{ display:'block', fontSize:11, color:'#94A3B8' }}>across {Object.keys(actionCounts).length} jobs</span>
              </span>
              <span style={{ flex:'none', fontSize:11.5, fontWeight:700, color: JRC.primary[300] || '#fff' }}>Work all →</span>
            </button>
          </div>
        );
      })()}

      {/* Job cards */}
      <div style={{ flex:1, overflow:'auto', padding:'4px 14px 20px', display:'flex', flexDirection:'column', gap:8 }}>
        {jobs.map(j => (
          <JobCard
            key={j.id}
            job={j}
            selected={j.id === selectedId}
            actionCount={actionCounts ? (actionCounts[j.id] || 0) : null}
            onClick={()=>onSelect?.(j.id)}
            vocab={vocab}
            splitBySource={splitBySource}
            actionable={actionable}
          />
        ))}
      </div>

      {/* Footer */}
      <div style={{ padding:'12px 20px 18px', borderTop:`1px solid ${JRC.shade[860]}`, display:'flex', alignItems:'center', justifyContent:'space-between', fontSize:11, color:'#94A3B8' }}>
        <span>Job Slots</span>
        <span style={{ color:'#fff', fontWeight:700 }}>8 / 30</span>
      </div>
    </aside>
  );
}

function JobCard({ job, selected, onClick, vocab, splitBySource, actionable, actionCount }) {
  return (
    <div onClick={onClick} style={{
      // Production truth: the selected job card carries a subtle purple
      // gradient, not a flat slate fill.
      background: selected
        ? `linear-gradient(115deg, ${JRC.highlight[500]}2E 0%, ${JRC.highlight[500]}0F 45%, ${JRC.shade[860]} 100%)`
        : 'transparent',
      borderRadius: 10,
      padding: '12px 14px',
      cursor: 'pointer',
      position: 'relative',
      border: selected ? `1px solid ${JRC.highlight[500]}59` : '1px solid transparent',
    }}>
      {selected && <div style={{ position:'absolute', left:-1, top:8, bottom:8, width:3, background: JRC.highlight[500], borderRadius:2 }}/>}

      {/* Title row */}
      <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:8 }}>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:2 }}>
            <h3 style={{
              margin:0, fontSize:14, fontWeight:700, color:'#fff',
              whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
            }}>{job.title}</h3>
          </div>
          <div style={{ fontSize:11, color:'#94A3B8' }}>
            {job.loc} <span style={{ opacity:.5 }}>|</span> {job.reqId}
          </div>
        </div>
        <div style={{ display:'flex', gap:4, alignItems:'center', color:'#94A3B8' }}>
          <img src="assets/icons/file-20.svg" width={15} height={15} style={{ filter:'brightness(0) invert(1)', opacity:.55 }}/>
          <img src="assets/icons/dots-vertical-20.svg" width={15} height={15} style={{ filter:'brightness(0) invert(1)', opacity:.55 }}/>
        </div>
      </div>

      {/* Action-needed indicator — sits above the pipeline counts because it
          answers a different question: not "how many are here" but "how many
          are waiting on me". Absent when nothing is. */}
      {actionCount != null && actionCount > 0 && (
        <div style={{
          marginTop:9, display:'inline-flex', alignItems:'center', gap:6,
          padding:'3px 9px 3px 7px', borderRadius:9999,
          background: JRC.primary[500] + '26', border:`1px solid ${JRC.primary[500]}66`,
        }}>
          <span style={{ width:6, height:6, borderRadius:'50%', background: JRC.primary[500] }}/>
          <span style={{ fontSize:11, fontWeight:700, color: JRC.primary[300] || '#fff' }}>
            {actionCount} need{actionCount === 1 ? 's' : ''} you
          </span>
        </div>
      )}

      {/* Pipeline counts */}
      {actionable ? (
        <ActionableCounts job={job}/>
      ) : splitBySource ? (
        <SplitPipelineCounts job={job} vocab={vocab}/>
      ) : (
        <AggregatedPipelineCounts job={job}/>
      )}

      {/* Status row — production order: team avatars left, job status + the
          Copilot bolt pill right. The pill colour carries active/inactive. */}
      <div style={{ marginTop:10, display:'flex', alignItems:'center', justifyContent:'space-between', gap:8 }}>
        <div style={{ display:'flex', alignItems:'center' }}>
          {(job.members || ['MS']).slice(0, 2).map((m, i) => (
            <span key={m} style={{
              width:22, height:22, borderRadius:'50%', flex:'none',
              background: i === 0 ? JRC.primary[500] : JRC.highlight[500], color:'#fff',
              fontSize:9, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center',
              marginLeft: i ? -6 : 0, border:`1.5px solid ${JRC.shade[880]}`,
            }}>{m}</span>
          ))}
          {(job.members || []).length > 2 && (
            <span style={{ fontSize:10, color:'#94A3B8', marginLeft:5 }}>+{job.members.length - 2}</span>
          )}
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:7 }}>
          <span style={{ fontSize:11, color:'#94A3B8', whiteSpace:'nowrap' }}>
            {job.active ? 'Active job status' : 'Inactive'}
          </span>
          <span style={{
            display:'inline-flex', alignItems:'center', justifyContent:'center', width:26, height:20,
            borderRadius:5, background: job.active ? JRC.copilot[600] : JRC.shade[840],
          }}>
            <img src="assets/icons/lightning-20.svg" width={11} height={11} style={{ filter:'brightness(0) invert(1)' }}/>
          </span>
        </div>
      </div>
    </div>
  );
}

function ActionableCounts({ job }) {
  // Derive action buckets from the funnel deterministically.
  const needsReview = Math.max(1, Math.round(job.counts.engaged * 0.35));
  const needsAttention = Math.max(0, Math.round(job.counts.engaged * 0.22));
  const cell = (label, n, color, dim) => (
    <div style={{ flex:1, display:'flex', alignItems:'center', gap:7 }}>
      <span style={{ width:7, height:7, borderRadius:'50%', background: dim ? JRC.shade[700] : color, flex:'none' }}/>
      <span style={{ fontSize:16, fontWeight:800, color: dim ? '#94A3B8' : '#fff', lineHeight:1, fontVariantNumeric:'tabular-nums' }}>{n}</span>
      <span style={{ fontSize:11, color:'#94A3B8' }}>{label}</span>
    </div>
  );
  return (
    <div style={{ marginTop:10, display:'flex', flexDirection:'column', gap:6 }}>
      {cell('Needs review', needsReview, JRC.primary[500], needsReview === 0)}
      {cell('Needs attention', needsAttention, JRC.caution[500], needsAttention === 0)}
    </div>
  );
}

function AggregatedPipelineCounts({ job }) {
  const cell = (label, n, color) => (
    <div style={{ flex:1 }}>
      <div style={{ fontSize:16, fontWeight:700, color: color || '#fff', lineHeight:1.1 }}>{n}</div>
      <div style={{ fontSize:11, color:'#94A3B8', marginTop:2 }}>{label}</div>
    </div>
  );
  return (
    <div style={{ marginTop:10, display:'flex', gap:8 }}>
      {cell('New', job.counts.new)}
      {cell('Engaged', job.counts.engaged)}
      {cell('Review', job.counts.review, job.counts.review === 0 ? '#94A3B8' : undefined)}
    </div>
  );
}

function SplitPipelineCounts({ job, vocab }) {
  const v = window.FFLIB.vocab(vocab);
  const row = (label, color, b) => (
    <div style={{ display:'flex', alignItems:'center', gap:8, padding:'4px 0' }}>
      <div style={{ display:'flex', alignItems:'center', gap:6, width:78, flex:'none' }}>
        <span style={{ width:6, height:6, borderRadius:'50%', background: color }}/>
        <span style={{ fontSize:10, color:'#fff', fontWeight:600, textTransform:'uppercase', letterSpacing:'.04em' }}>{label}</span>
      </div>
      <div style={{ display:'flex', gap:14, flex:1 }}>
        <Stat n={b.sourcing || b.new} label={label === v.sourced ? 'Sourcing' : 'New'} />
        <Stat n={b.engaged} label="Eng." />
        <Stat n={b.review} label="Rev." />
      </div>
    </div>
  );
  return (
    <div style={{ marginTop:10, background: JRC.shade[880], borderRadius:6, padding:'4px 10px' }}>
      {row(v.applied, JRC.inform[500], job.bySource.applied)}
      <div style={{ height:1, background: JRC.shade[840] }}/>
      {row(v.sourced, JRC.copilot[500], job.bySource.sourced)}
    </div>
  );
}

function Stat({ n, label }) {
  return (
    <div style={{ flex:1, display:'flex', alignItems:'baseline', gap:4 }}>
      <span style={{ fontSize:13, fontWeight:700, color: n ? '#fff' : '#64748B' }}>{n}</span>
      <span style={{ fontSize:10, color:'#94A3B8' }}>{label}</span>
    </div>
  );
}

Object.assign(window, { JobsRail });
