// Interview pipeline — kanban-ish per-stage layout with next-action dates.

const PIPELINE_STAGES = ['Applied', 'Recruiter Call', 'Phone Screen', 'Onsite', 'Offer', 'Rejected'];

function PipelineView() {
  const { state, update } = useStore();
  const data = window.PLAN_DATA;
  const TODAY = useToday();
  const today = fmtDate(TODAY);

  const setPipe = (num, patch) => {
    update(prev => ({
      ...prev,
      pipeline: { ...prev.pipeline, [num]: { ...prev.pipeline[num], ...patch } }
    }));
  };

  function moveTo(num, stage) {
    const prev = state.pipeline[num] || {};
    const history = [...(prev.history || []), { stage, date: today }];
    setPipe(num, { stage, history });
  }

  // For each stage, collect companies
  const byStage = {};
  for (const st of PIPELINE_STAGES) byStage[st] = [];
  for (const a of data.apps) {
    const p = state.pipeline[a.num];
    if (p?.stage) byStage[p.stage]?.push({ ...a, ...p });
  }
  const active = PIPELINE_STAGES.filter(s => s !== 'Rejected').reduce((sum, s) => sum + byStage[s].length, 0);

  // Upcoming actions across all companies, sorted
  const upcoming = data.apps
    .map(a => ({ a, p: state.pipeline[a.num] || {} }))
    .filter(x => x.p.nextDate && x.p.stage && x.p.stage !== 'Rejected')
    .sort((x, y) => x.p.nextDate.localeCompare(y.p.nextDate));

  const stageColor = {
    'Applied': 'oklch(0.7 0.04 250)',
    'Recruiter Call': 'oklch(0.85 0.15 80)',
    'Phone Screen': 'oklch(0.86 0.13 200)',
    'Onsite': 'oklch(0.84 0.14 165)',
    'Offer': 'var(--accent)',
    'Rejected': 'var(--rose)',
  };

  return (
    <div className="fade-in">
      <div className="section-h">
        <div>
          <div className="kicker">Live pipeline · {active} active across stages</div>
          <h1 className="h-title">The <em>funnel</em>.</h1>
        </div>
        <div style={{display:'flex',gap:'14px'}}>
          <Stat label="Active" value={<CountUp to={active} />} accent />
          <Stat label="Offers" value={<CountUp to={byStage['Offer'].length} />} sub={`${byStage['Rejected'].length} rejected`} />
        </div>
      </div>

      {upcoming.length > 0 && (
        <div className="card" style={{marginBottom:'24px'}}>
          <div className="kicker" style={{marginBottom:'10px'}}>Next actions</div>
          <div className="col" style={{gap:'8px'}}>
            {upcoming.slice(0, 8).map(({a, p}) => {
              const overdue = p.nextDate < today;
              return (
                <div key={a.num} style={{display:'grid', gridTemplateColumns:'90px 1fr 140px 1fr', gap:'12px', alignItems:'center', padding:'8px 0'}}>
                  <span className="mono" style={{fontSize:'11px', color: overdue ? 'var(--rose)' : 'var(--accent)'}}>{p.nextDate}{overdue ? ' (late)' : ''}</span>
                  <span style={{fontSize:'13px', fontWeight:500}}>{a.company}</span>
                  <Pill kind={p.stage === 'Offer' ? 'accent' : ''}>{p.stage}</Pill>
                  <span className="muted" style={{fontSize:'12px'}}>{p.nextNote || '—'}</span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Stage columns */}
      <div style={{display:'grid', gridTemplateColumns:`repeat(${PIPELINE_STAGES.length}, 1fr)`, gap:'10px'}}>
        {PIPELINE_STAGES.map(stage => (
          <div key={stage} className="card" style={{padding:'14px 12px', minHeight:'200px'}}>
            <div style={{display:'flex',alignItems:'center',gap:'8px',marginBottom:'12px'}}>
              <div style={{width:'8px',height:'8px',borderRadius:'50%', background: stageColor[stage]}}/>
              <div className="mono" style={{fontSize:'10px', letterSpacing:'0.1em', color:'var(--ink-2)'}}>{stage.toUpperCase()}</div>
              <div className="mono muted" style={{fontSize:'10px', marginLeft:'auto'}}>{byStage[stage].length}</div>
            </div>
            <div className="col" style={{gap:'6px'}}>
              {byStage[stage].map(c => (
                <div key={c.num} className="card" style={{padding:'8px 10px', background:'var(--bg-3)', border:'1px solid var(--line-soft)'}}>
                  <div style={{fontSize:'12px', fontWeight:600}}>{c.company}</div>
                  <div className="mono muted" style={{fontSize:'9px', letterSpacing:'0.06em', marginTop:'2px'}}>{c.tier} · {c.role}</div>
                  {c.nextDate && <div className="mono" style={{fontSize:'10px', marginTop:'4px', color: c.nextDate < today ? 'var(--rose)' : 'var(--accent)'}}>→ {c.nextDate}</div>}
                </div>
              ))}
              {byStage[stage].length === 0 && <div className="muted" style={{fontSize:'10px', textAlign:'center', padding:'12px 0'}}>—</div>}
            </div>
          </div>
        ))}
      </div>

      {/* Per-company editor table */}
      <div className="card" style={{marginTop:'24px', padding:'0'}}>
        <div style={{padding:'14px 18px', borderBottom:'1px solid var(--line-soft)'}}>
          <div className="kicker">All companies · move + schedule next action</div>
        </div>
        <div>
          {data.apps.map(a => {
            const p = state.pipeline[a.num] || {};
            return (
              <div key={a.num} style={{display:'grid', gridTemplateColumns:'30px 1fr 150px 130px 1fr', gap:'12px', padding:'10px 18px', alignItems:'center', borderBottom:'1px solid var(--line-soft)'}}>
                <span className="mono muted" style={{fontSize:'10px'}}>{a.num.padStart(2,'0')}</span>
                <div>
                  <div style={{fontSize:'13px', fontWeight:500}}>{a.company}</div>
                  <div className="mono muted" style={{fontSize:'10px'}}>{a.tier} · {a.role}</div>
                </div>
                <select className="select" value={p.stage || ''} onChange={e => moveTo(a.num, e.target.value)} style={{padding:'6px 8px', fontSize:'11px'}}>
                  <option value="">— stage —</option>
                  {PIPELINE_STAGES.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
                <input className="input" type="date" value={p.nextDate || ''} onChange={e => setPipe(a.num, { nextDate: e.target.value })} style={{padding:'6px 8px', fontSize:'11px'}}/>
                <input className="input" placeholder="next action (e.g. recruiter call 4pm IST)" value={p.nextNote || ''} onChange={e => setPipe(a.num, { nextNote: e.target.value })} style={{padding:'6px 8px', fontSize:'11px'}}/>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.PipelineView = PipelineView;
