/* ELEV8 ATS - per-job workspace tabs: Inbound, Advertising, Campaigns, Files, Notes,
   the client-facing Company Portal, and the structured Job-details rail block.
   Each takes the job J; the flagship JO-44219 is fully populated, others fall back cleanly. */

const DSt = window.Stand8DesignSystem_b5c975;

/* ---------- Inbound applicants: the full Applicants board, scoped to this job ---------- */
function JobInboundTab({ J }) {
  return <window.ApplicantsBoard jobId={J.id} />;
}

/* ---------- Advertising ---------- */
const AD_STATUS = { Live: 'success', Paused: 'neutral', Draft: 'info' };

function JobAdvertisingTab({ J }) {
  const D = window.E8DATA;
  const { showToast, density } = React.useContext(window.E8Ctx);
  const seed = D.jobAds[J.id] || [];
  const [ads, setAds] = React.useState(seed);

  if (!seed.length) {
    return <div style={{ maxWidth: 460, margin: '24px auto' }}>
      <DSt.EmptyState icon="campaign" title="Not advertised yet" body="Post this job to LinkedIn, Indeed and niche boards, then track views, applies and spend per channel here."
        cta={<DSt.Button variant="secondary" size="sm" className="e8-empty-cta" onClick={() => showToast('Pick boards to post to')}>Post to a board</DSt.Button>} />
    </div>;
  }

  const num = (s) => parseInt(String(s).replace(/[^0-9]/g, ''), 10) || 0;
  const totals = ads.reduce((t, a) => ({ views: t.views + num(a.views), applies: t.applies + num(a.applies), spend: t.spend + num(a.spend) }), { views: 0, applies: 0, spend: 0 });
  const toggle = (id) => setAds((x) => x.map((a) => a.id === id ? { ...a, status: a.status === 'Live' ? 'Paused' : 'Live' } : a));

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 16, maxWidth: 620 }}>
        {[['Channels live', ads.filter((a) => a.status === 'Live').length], ['Total views', totals.views.toLocaleString()], ['Applies', totals.applies], ['Spend', '$' + totals.spend]].map(([k, v]) => (
          <div key={k} style={{ border: '1px solid var(--ui-border)', borderRadius: 'var(--ui-radius-lg)', padding: '10px 14px' }}>
            <div style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-tertiary)' }}>{k}</div>
            <div className="tnum" style={{ fontSize: 'var(--ui-text-xl)', fontWeight: 500, marginTop: 2 }}>{v}</div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
        <span className="e8-sectionlabel">Channels</span>
        <span style={{ marginLeft: 'auto' }}><DSt.Button variant="secondary" size="sm" icon="add" onClick={() => showToast('Pick a board to post to')}>Post to a board</DSt.Button></span>
      </div>
      <ConfigurableTable listKey="job-advertising" primary={false}
        density={density}
        registry={[
          { key: 'board', label: 'Channel', render: (a) => <span style={{ fontWeight: 500 }}>{a.board}</span> },
          { key: 'status', label: 'Status', render: (a) => <DSt.Badge tone={AD_STATUS[a.status]} dot={a.status !== 'Draft'}>{a.status}</DSt.Badge> },
          { key: 'posted', label: 'Posted', secondary: true },
          { key: 'views', label: 'Views', num: true, render: (a) => <span className="tnum">{Number(a.views).toLocaleString()}</span> },
          { key: 'applies', label: 'Applies', num: true },
          { key: 'spend', label: 'Spend', num: true },
        ]}
        rows={ads}
        rowActions={(a) => (
          <DSt.Button variant="ghost" size="sm" icon={a.status === 'Live' ? 'pause' : 'play_arrow'} onClick={() => toggle(a.id)}>{a.status === 'Live' ? 'Pause' : 'Resume'}</DSt.Button>
        )}
      />
    </div>
  );
}

/* ---------- Campaigns (job-scoped outreach) ---------- */
function JobCampaignsTab({ J }) {
  const D = window.E8DATA;
  const { showToast } = React.useContext(window.E8Ctx);
  const flagship = J.id === 'JO-44219';
  const seqs = flagship ? D.sequences.filter((s) => s.id === 'sq-jvm') : [];

  return (
    <div style={{ display: 'grid', gap: 16, maxWidth: 760 }}>
      <div className="e8-card e8-aibrief">
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
          <span className="e8-sectionlabel">Sourcing for this job</span>
          <DSt.ProvenanceBadge kind="advised" />
        </div>
        <p style={{ margin: 0, fontSize: 'var(--ui-text-base)', lineHeight: 1.5, color: 'var(--ui-text)' }}>
          The Matching agent surfaced {J.pipeline.source} candidate{J.pipeline.source === 1 ? '' : 's'} for review, and outreach sequences re-engage warm profiles. A reply pauses a candidate’s sequence automatically.
        </p>
      </div>

      {seqs.length ? seqs.map((s) => (
        <div key={s.id} className="e8-card" style={{ padding: '13px 16px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 'var(--ui-text-md)', fontWeight: 500 }}>{s.name}</span>
            <DSt.Badge tone={s.state === 'running' ? 'success' : 'neutral'} dot>{s.state === 'running' ? 'Running' : 'Paused'}</DSt.Badge>
            <span style={{ marginLeft: 'auto', display: 'inline-flex', gap: 16 }}>
              {[['Enrolled', s.enrolled], ['Replies', s.replied + ' · ' + s.replyRate], ['Meetings', s.meetings]].map(([k, v]) => (
                <span key={k} style={{ textAlign: 'right' }}>
                  <span style={{ display: 'block', fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>{k}</span>
                  <span className="tnum" style={{ display: 'block', fontSize: 'var(--ui-text-base)', fontWeight: 500 }}>{v}</span>
                </span>
              ))}
            </span>
          </div>
          <div className="e8-seq-flow">
            {s.steps.map((st, i) => (
              <React.Fragment key={i}>
                {i > 0 ? <span className="material-symbols-outlined e8-seq-arrow">arrow_forward</span> : null}
                <span className="e8-seq-step">
                  <window.ChannelDot ch={st.ch} size={15} />
                  <span style={{ minWidth: 0 }}>
                    <span style={{ display: 'block', fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>{st.day}</span>
                    <span style={{ display: 'block', fontSize: 'var(--ui-text-sm)', fontWeight: 500, whiteSpace: 'nowrap' }}>{st.label}</span>
                  </span>
                </span>
              </React.Fragment>
            ))}
          </div>
          <div style={{ marginTop: 10 }}>
            <DSt.Button variant="ghost" size="sm" icon="open_in_new" onClick={() => navigate('sequences')}>Open in Sequences</DSt.Button>
          </div>
        </div>
      )) : (
        <DSt.EmptyState icon="campaign" title="No campaigns on this job yet" body="Enroll sourced or stale candidates into a multi-channel sequence to re-engage them."
          cta={<DSt.Button variant="secondary" size="sm" className="e8-empty-cta" onClick={() => navigate('sequences')}>New sequence</DSt.Button>} />
      )}
    </div>
  );
}

/* ---------- Files ---------- */
function JobFilesTab({ J }) {
  const { showToast, density } = React.useContext(window.E8Ctx);
  const files = window.E8DATA.jobFiles[J.id] || [];
  if (!files.length) {
    return <div style={{ maxWidth: 460, margin: '24px auto' }}>
      <DSt.EmptyState icon="folder_open" title="No files yet" body="The JD, intake notes, submittal packets and signed docs for this job live here." cta={<DSt.Button variant="secondary" size="sm" className="e8-empty-cta" onClick={() => showToast('Upload a file')}>Upload</DSt.Button>} />
    </div>;
  }
  return (
    <div style={{ maxWidth: 760 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <span className="e8-sectionlabel">Files</span>
        <span className="tnum" style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-tertiary)' }}>{files.length}</span>
        <span style={{ marginLeft: 'auto' }}><DSt.Button variant="secondary" size="sm" icon="upload" onClick={() => showToast('Upload a file')}>Upload</DSt.Button></span>
      </div>
      <div className="e8-card" style={{ boxShadow: 'none', padding: '2px 0' }}>
        {files.map((f) => (
          <div key={f.id} className="e8-filerow">
            <span className="e8-fileicon"><span className="material-symbols-outlined">{f.kind}</span></span>
            <span style={{ flex: 1, minWidth: 0 }}>
              <span style={{ display: 'block', fontSize: 'var(--ui-text-base)', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.name}</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>
                {f.size} · <ActorChip name={f.by} ai={!!f.ai} /> · {f.when}
              </span>
            </span>
            <DSt.Button variant="ghost" size="sm" icon="download" iconOnly title="Download" onClick={(e) => { e.stopPropagation(); showToast('Downloading ' + f.name); }}></DSt.Button>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Notes (job-scoped) ---------- */
function JobNotesTab({ J }) {
  const D = window.E8DATA;
  const { showToast } = React.useContext(window.E8Ctx);
  const cap = React.useContext(window.CaptureCtx);
  const [, setJnTick] = React.useState(0);
  React.useEffect(() => (window.E8Events ? window.E8Events.subscribe(['store:changed'], () => setJnTick((t) => t + 1)) : undefined), []);
  const openJobNote = () => (cap ? cap.open({ target: 'note', entityLabel: J.client + ' · ' + J.id, refType: 'job', refId: J.id }) : null);
  const notes = D.notes.filter((n) => n.refId === J.id || (n.entity || '').indexOf(J.id) > -1 || (n.entity || '').indexOf(J.client) > -1);
  if (!notes.length) {
    return <div style={{ maxWidth: 460, margin: '24px auto' }}>
      <DSt.EmptyState icon="sticky_note_2" title="No notes on this job yet" body="Call summaries and meeting notes tagged to this job or client show up here." cta={<DSt.Button variant="secondary" size="sm" className="e8-empty-cta" onClick={openJobNote}>Add note</DSt.Button>} />
    </div>;
  }
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <span className="e8-sectionlabel">Notes</span>
        <span className="tnum" style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-tertiary)' }}>{notes.length}</span>
        <span style={{ marginLeft: 'auto' }}><DSt.Button variant="secondary" size="sm" icon="add" onClick={openJobNote}>Add note</DSt.Button></span>
      </div>
      <div className="e8-notes-grid">
        {notes.map((n) => (
          <div key={n.id} className="e8-note-card" style={{ cursor: 'default' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap' }}>
              <span className="e8-note-src"><span className="material-symbols-outlined" style={{ fontSize: 13 }}>{n.icon}</span>{n.source}</span>
              {n.ai ? <DSt.ProvenanceBadge kind="drafted" /> : null}
            </div>
            <div style={{ fontSize: 'var(--ui-text-base)', fontWeight: 500, lineHeight: 1.35 }}>{n.title}</div>
            <ul style={{ margin: 0, paddingLeft: 16, display: 'grid', gap: 3 }}>
              {n.points.map((p, i) => <li key={i} style={{ fontSize: 'var(--ui-text-sm)', lineHeight: 1.45, color: 'var(--ui-text-secondary)' }}>{p}</li>)}
            </ul>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 'auto', paddingTop: 8, borderTop: '1px solid var(--ui-border)' }}>
              <ActorChip name={n.by} ai={!!n.agent} />
              <span className="tnum" style={{ marginLeft: 'auto', fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>{n.when}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Job details rail block (structured field list) ---------- */
function JobDetailsRail({ J, status }) {
  status = status || 'open';
  const statusLabel = status === 'closed' ? 'Closed' : status === 'filled' ? 'Filled' : 'Open';
  const locStr = window.jobLocSummary ? window.jobLocSummary(J) : J.location;
  const fields = [
    ['Company', J.client],
    ['Status', statusLabel],
    ['Location', locStr],
    ['Type', J.type],
    ['Bill rate', J.rate],
    ['Openings', J.openings != null ? String(J.openings) : '-'],
  ];
  if (status === 'open') {
    fields.push(['Priority', (JOB_PRIORITIES[J.priority] || JOB_PRIORITIES[3]).label]);
    if (J.day != null && J.days != null) fields.push(['Aging', 'day ' + J.day + ' of ' + J.days]);
  } else if (status === 'closed') {
    if (J.closeReason || J.reason) fields.push(['Outcome', J.closeReason || J.reason]);
    if (J.closedDate) fields.push(['Closed', J.closedDate]);
    if (J.daysOpen != null) fields.push(['Days open', String(J.daysOpen)]);
  } else if (status === 'filled') {
    if (J.consultant) fields.push(['Placed', J.consultant]);
    if (J.filledDate) fields.push(['Filled', J.filledDate]);
    if (J.fillDays != null) fields.push(['Time to fill', J.fillDays + ' days']);
  }
  const multi = J.team && J.team.length > 1;
  return (
    <div className="e8-rail-block">
      <div className="e8-rail-title">Job details</div>
      {fields.map(([k, v]) => (
        <div className="e8-kv" key={k}><span className="e8-kv-k">{k}</span><span className="e8-kv-v">{v}</span></div>
      ))}
      <div className="e8-kv">
        <span className="e8-kv-k">{multi ? 'Team' : 'Owner'}</span>
        <span className="e8-kv-v"><window.OwnerStack owner={J.owner} team={J.team} /></span>
      </div>
    </div>
  );
}

/* ============================== ★ COMPANY PORTAL ============================== */
/* The client-facing view of this job. Your client (the sponsor) logs in and sees a
   clean, rate-free shortlist of the candidates you've submitted - and can ask for an
   interview or pass, with feedback flowing straight back to your pipeline. Toggle
   between the recruiter's "internal" view and exactly what the client sees. */
const PORTAL_TONES = { New: 'neutral', Reviewing: 'info', 'Interview requested': 'success', Passed: 'danger' };

function CompanyPortalTab({ J }) {
  const D = window.E8DATA;
  const { showToast } = React.useContext(window.E8Ctx);
  const portal = D.portal[J.id];
  const [view, setView] = React.useState('internal');
  const [statuses, setStatuses] = React.useState(() => portal ? Object.fromEntries(portal.candidates.map((c) => [c.candId, c.status])) : {});

  if (!portal) {
    return <div style={{ maxWidth: 460, margin: '24px auto' }}>
      <DSt.EmptyState icon="captive_portal" title="Portal opens once you’ve submitted candidates"
        body="Submit a shortlist and your client gets a private, rate-free portal to review them, request interviews and leave feedback - no email threads."
        cta={<DSt.Button variant="secondary" size="sm" className="e8-empty-cta" onClick={() => navigate('job/JO-44219/portal')}>See the JO-44219 portal</DSt.Button>} />
    </div>;
  }

  const client = view === 'client';
  const setStatus = (candId, s) => {
    setStatuses((m) => ({ ...m, [candId]: s }));
    const nm = (D.matches.find((m) => m.id === candId) || {}).name;
    showToast(client ? 'Sent to Stand8 · ' + s : nm + ' → ' + s, 'Undo', () => setStatuses((m) => ({ ...m, [candId]: portal.candidates.find((c) => c.candId === candId).status })));
  };

  return (
    <div className="e8-portal">
      {/* Portal chrome */}
      <div className="e8-portal-bar">
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
          <span className="e8-logomark" aria-hidden="true" style={{ width: 22, height: 22 }}>8</span>
          <span style={{ minWidth: 0 }}>
            <span style={{ display: 'block', fontSize: 'var(--ui-text-base)', fontWeight: 500 }}>{J.title} · candidate review</span>
            <span style={{ display: 'block', fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>Shared with {portal.sponsor} · {portal.client}</span>
          </span>
        </span>
        <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 10, flex: 'none' }}>
          <DSt.SubTabs items={[{ id: 'internal', label: 'Internal view' }, { id: 'client', label: 'Client view' }]} active={view} onChange={setView} />
          <DSt.Button variant="secondary" size="sm" icon="link" onClick={() => showToast('Portal link copied - ' + portal.client + ' signs in with SSO')}>Copy link</DSt.Button>
        </span>
      </div>

      {view === 'internal' ? (
        <div className="e8-portal-stats">
          <span><span className="material-symbols-outlined" style={{ fontSize: 14 }}>share</span> Shared {portal.shared}</span>
          <span><span className="material-symbols-outlined" style={{ fontSize: 14 }}>visibility</span> Last viewed {portal.lastViewed}</span>
          <span><span className="material-symbols-outlined" style={{ fontSize: 14 }}>bar_chart</span> {portal.views} views</span>
          <span style={{ marginLeft: 'auto', color: 'var(--ui-text-tertiary)' }}>Rates, contact details and internal notes are never shown to the client.</span>
        </div>
      ) : (
        <div className="e8-portal-hello">
          <div style={{ fontSize: 'var(--ui-text-md)', fontWeight: 500 }}>Hi {portal.sponsor.split(' ')[0]} - here’s your shortlist for {J.title}</div>
          <div style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)', marginTop: 2 }}>Review each candidate and let us know who you’d like to meet. Stand8 handles scheduling.</div>
        </div>
      )}

      <div className="e8-portal-grid">
        {portal.candidates.map((pc) => {
          const c = D.matches.find((m) => m.id === pc.candId);
          if (!c) return null;
          const prof = window.profileOf(c, D.candidates.find((x) => x.id === c.id) || {});
          const status = statuses[pc.candId];
          const fits = c.reasons.filter((r) => r.weight > 0 && !/rate|budget|\$|w2|c2c/i.test(r.label)).slice(0, 3);
          return (
            <div key={pc.candId} className="e8-portal-card">
              <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                <DSt.Avatar name={c.name} size="lg" />
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 'var(--ui-text-md)', fontWeight: 500 }}>{c.name}</div>
                  <div style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)' }}>{c.title} · {c.years}y experience</div>
                </div>
                <DSt.Badge tone={PORTAL_TONES[status] || 'neutral'} dot>{status}</DSt.Badge>
              </div>

              <p style={{ margin: '11px 0 0', fontSize: 'var(--ui-text-sm)', lineHeight: 1.55, color: 'var(--ui-text-secondary)', textWrap: 'pretty' }}>{c.aiSummary || prof.about}</p>

              <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', margin: '10px 0' }}>
                {prof.techStack.slice(0, 6).map((s) => <DSt.SkillChip key={s}>{s}</DSt.SkillChip>)}
              </div>

              {fits.length ? (
                <div style={{ display: 'grid', gap: 4, marginBottom: 4 }}>
                  {fits.map((r, i) => (
                    <div key={i} style={{ display: 'flex', gap: 6, fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)' }}>
                      <span className="material-symbols-outlined" style={{ fontSize: 14, color: 'var(--ui-success-text)' }}>check_circle</span>
                      {r.label}
                    </div>
                  ))}
                </div>
              ) : null}

              {view === 'internal' && pc.clientNote ? (
                <div className="e8-portal-note"><span className="material-symbols-outlined" style={{ fontSize: 14 }}>format_quote</span>{pc.clientNote}</div>
              ) : null}

              <div className="e8-portal-actions">
                {client ? (
                  <React.Fragment>
                    <DSt.Button variant="accept" size="sm" icon="event" onClick={() => setStatus(pc.candId, 'Interview requested')}>Request interview</DSt.Button>
                    <DSt.Button variant="ghost" size="sm" icon="close" onClick={() => setStatus(pc.candId, 'Passed')}>Pass</DSt.Button>
                  </React.Fragment>
                ) : (
                  <React.Fragment>
                    <DSt.Button variant="ghost" size="sm" icon="open_in_new" onClick={() => navigate('candidate/' + c.id)}>Open record</DSt.Button>
                    {status === 'Interview requested'
                      ? <DSt.Button variant="primary" size="sm" icon="event" onClick={() => showToast('Scheduling interview with ' + c.name + ' for ' + portal.sponsor)}>Schedule</DSt.Button>
                      : <DSt.Button variant="secondary" size="sm" icon="mail" onClick={() => showToast('Nudge drafted to ' + portal.sponsor + ' - review in Approvals', 'Open approvals', () => navigate('approvals'))}>Nudge client</DSt.Button>}
                  </React.Fragment>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { JobInboundTab, JobAdvertisingTab, JobCampaignsTab, JobFilesTab, JobNotesTab, JobDetailsRail, CompanyPortalTab });
