/* AI Copilot + Candidate Comparison — built on the Greydigi DS. */
const { useState: useS, useRef, useEffect } = React;
const GC = window.GreydigiComponents;
const { Avatar: CAvatar, Badge: CBadge, Button: CButton, Tag: CTag } = GC;

const RISK_RANK = { Low: 0, Medium: 1, High: 2, Critical: 3 };
const REC_RANK = { shortlisted: 0, borderline: 1, rejected: 2 };
const REC_TEXT = { shortlisted: { label: 'Proceed', v: 'success' }, borderline: { label: 'Caution', v: 'warning' }, rejected: { label: 'Reject', v: 'error' } };
const RISK_BADGE = { Low: 'success', Medium: 'warning', High: 'error', Critical: 'error' };

/* =================================================================
   AI COPILOT
================================================================= */
const SUGGESTED = [
  { id: 'why', icon: 'caution', label: 'Why was this candidate rejected?' },
  { id: 'summary', icon: 'sparkles', label: 'Summarize candidate' },
  { id: 'interview', icon: 'calendar', label: 'Generate interview questions' },
  { id: 'compare', icon: 'analytics', label: 'Compare with previous' },
  { id: 'similar', icon: 'userSearch', label: 'Find similar candidates' },
];

/* Inline reference chip — links a phrase to candidate data */
function Ref({ children }) {
  return <span className="cop-ref"><Icon name="sparkles" size={10} />{children}</span>;
}

function buildAnswer(id, p, d, pool) {
  const first = p.name.split(' ')[0];
  const others = (pool || CANDIDATES).filter((c) => c.id !== p.id);

  if (id === 'why') {
    if (p.decision === 'rejected') {
      return (
        <div className="cop-ans">
          <p>{first} was flagged <CBadge label="Reject" variant="error" /> primarily on skills depth. The ATS score of <Ref>{p.ats}/100</Ref> sits below the role bar, and required-skills coverage is only <Ref>{p.skills_pct}%</Ref>.</p>
          <p>Key gaps driving the decision:</p>
          <div className="cop-tags">{p.gaps.map((g) => <CTag key={g} label={g} variant="gap" />)}</div>
          <p className="cop-foot">Risk is rated <CBadge label={`${p.risk}`} variant={RISK_BADGE[p.risk]} /> — see Risk Assessment for the full breakdown.</p>
        </div>
      );
    }
    return (
      <div className="cop-ans">
        <p>{first} was <strong>not</strong> rejected — current recommendation is <CBadge label={REC_TEXT[p.decision].label} variant={REC_TEXT[p.decision].v} /> with <Ref>{d.confidence}% confidence</Ref>.</p>
        <p>{p.gaps.length ? <>The only watch-areas are <span className="cop-tags-inline">{p.gaps.map((g) => <CTag key={g} label={g} variant="gap" />)}</span> — worth probing in interview, but not disqualifying.</> : 'No material concerns were detected against the role scorecard.'}</p>
      </div>
    );
  }

  if (id === 'summary') {
    return (
      <div className="cop-ans">
        <p><strong>{p.name}</strong> — {p.headline} at <Ref>{p.company}</Ref>, based in {p.location} with <Ref>{p.years} yrs</Ref> of relevant experience.</p>
        <p>Scorecard: ATS <Ref>{p.ats}</Ref> · Required match <Ref>{p.skills_pct}%</Ref> · Leadership <Ref>{d.scores.leadership}</Ref>. Recommendation is <CBadge label={REC_TEXT[p.decision].label} variant={REC_TEXT[p.decision].v} /> at {d.confidence}% confidence.</p>
        <p>Strongest signals:</p>
        <div className="cop-tags">{p.strengths.slice(0, 3).map((s) => <CTag key={s} label={s} variant="strength" />)}</div>
      </div>
    );
  }

  if (id === 'interview') {
    const top = [...p.skillbars].sort((a, b) => b.percentage - a.percentage)[0].name;
    const gap = p.gaps[0] || 'a preferred skill';
    const qs = [
      `Walk me through your most complex ${top} engagement end-to-end — your specific ownership, not the team's.`,
      `Your profile shows lighter coverage on ${gap}. How would you ramp up, and where have you touched it before?`,
      `Describe a delivery that slipped. What was the root cause and what did you change afterward?`,
      `How do you handle a scoping workshop when the client wants to automate a process that isn't ready for it?`,
    ];
    return (
      <div className="cop-ans">
        <p>Tailored to {first}'s profile — probing strengths in <Ref>{top}</Ref> and the gap on <Ref>{gap}</Ref>:</p>
        <ol className="cop-qs">{qs.map((q, i) => <li key={i}>{q}</li>)}</ol>
      </div>
    );
  }

  if (id === 'compare') {
    if (!others.length) return <div className="cop-ans"><p>{first} is the only candidate in this pipeline so far — no one to compare against yet.</p></div>;
    const prev = [...others].sort((a, b) => b.ats - a.ats)[0];
    const diff = p.ats - prev.ats;
    return (
      <div className="cop-ans">
        <p>Comparing {first} with <Ref>{prev.name}</Ref> (next strongest in the pipeline):</p>
        <div className="cop-compare">
          <div><span className="cop-cl">{first}</span> ATS <strong>{p.ats}</strong> · {p.skills_pct}% match · {p.risk} risk</div>
          <div><span className="cop-cl">{prev.name.split(' ')[0]}</span> ATS <strong>{prev.ats}</strong> · {prev.skills_pct}% match · {prev.risk} risk</div>
        </div>
        <p className="cop-foot">{diff >= 0 ? `${first} leads by ${diff} ATS points.` : `${prev.name.split(' ')[0]} leads by ${-diff} ATS points.`} Open the full <strong>Comparison</strong> view for a row-by-row breakdown.</p>
      </div>
    );
  }

  if (id === 'similar') {
    if (!others.length) return <div className="cop-ans"><p>No other candidates in this pipeline yet to find matches against.</p></div>;
    const mySkills = new Set(p.skillbars.map((s) => s.name));
    const ranked = others
      .map((c) => ({ c, overlap: c.skillbars.filter((s) => mySkills.has(s.name)).length }))
      .sort((a, b) => b.overlap - a.overlap).slice(0, 3);
    return (
      <div className="cop-ans">
        <p>Candidates with the most skill overlap with {first}:</p>
        <div className="cop-similar">
          {ranked.map(({ c, overlap }) => (
            <div key={c.id} className="cop-sim">
              <CAvatar initials={c.initials} size="sm" color="charcoal" />
              <div className="cop-sim-id"><span className="cop-sim-name">{c.name}</span><span className="cop-sim-sub">{c.company} · {c.years} yrs</span></div>
              <Ref>{overlap} shared skills</Ref>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return <div className="cop-ans"><p>Here's what I found for {first}.</p></div>;
}

function Copilot({ person, pool }) {
  const [open, setOpen] = useS(false);
  const [msgs, setMsgs] = useS([]);
  const [text, setText] = useS('');
  const [thinking, setThinking] = useS(false);
  const bodyRef = useRef(null);
  const d = person ? getDetail(person) : null;

  useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [msgs, thinking, open]);
  useEffect(() => { setMsgs([]); }, [person && person.id]);

  function ask(promptId, promptLabel) {
    if (!person) return;
    const userMsg = { role: 'user', text: promptLabel };
    setMsgs((m) => [...m, userMsg]);
    setThinking(true);
    setText('');
    setTimeout(() => {
      setMsgs((m) => [...m, { role: 'ai', node: buildAnswer(promptId, person, d, pool) }]);
      setThinking(false);
    }, 650);
  }
  function detectIntent(t) {
    const s = t.toLowerCase();
    if (s.includes('reject') || s.includes('why')) return 'why';
    if (s.includes('summ')) return 'summary';
    if (s.includes('interview') || s.includes('question')) return 'interview';
    if (s.includes('compare') || s.includes('previous')) return 'compare';
    if (s.includes('similar') || s.includes('like')) return 'similar';
    return 'summary';
  }
  function submit(e) {
    e.preventDefault();
    if (!text.trim()) return;
    ask(detectIntent(text), text.trim());
  }

  const empty = msgs.length === 0;

  return (
    <div className="cop-root">
      {!open && (
        <button className="cop-fab" onClick={() => setOpen(true)} aria-label="Open AI Copilot">
          <Icon name="sparkles" size={20} />
          <span>Ask Copilot</span>
        </button>
      )}
      {open && (
        <div className="cop-panel">
          <div className="cop-head">
            <div className="cop-head-id">
              <span className="cop-head-mark"><Icon name="sparkles" size={15} /></span>
              <div>
                <div className="cop-head-title">AI Copilot</div>
                <div className="cop-head-sub">{person ? `Context · ${person.name}` : 'No candidate selected'}</div>
              </div>
            </div>
            <button className="cop-x" onClick={() => setOpen(false)} aria-label="Close"><Icon name="reject" size={18} /></button>
          </div>

          <div className="cop-body" ref={bodyRef}>
            {empty && (
              <div className="cop-intro">
                <p>Ask anything about {person ? person.name.split(' ')[0] : 'this candidate'} — I'll answer using their scorecard and resume.</p>
              </div>
            )}
            {msgs.map((m, i) => (
              m.role === 'user'
                ? <div key={i} className="cop-msg-user">{m.text}</div>
                : <div key={i} className="cop-msg-ai"><span className="cop-msg-mark"><Icon name="sparkles" size={13} /></span><div className="cop-msg-content">{m.node}</div></div>
            ))}
            {thinking && <div className="cop-msg-ai"><span className="cop-msg-mark"><Icon name="sparkles" size={13} /></span><div className="cop-typing"><span /><span /><span /></div></div>}
          </div>

          <div className="cop-suggest">
            {SUGGESTED.map((s) => (
              <button key={s.id} className="cop-chip" onClick={() => ask(s.id, s.label)} disabled={!person}>
                <Icon name={s.icon} size={13} />{s.label}
              </button>
            ))}
          </div>

          <form className="cop-input" onSubmit={submit}>
            <input value={text} onChange={(e) => setText(e.target.value)} placeholder="Ask a follow-up…" disabled={!person} />
            <button type="submit" className="cop-send" disabled={!person || !text.trim()} aria-label="Send"><Icon name="chevronRight" size={18} /></button>
          </form>
        </div>
      )}
    </div>
  );
}

/* =================================================================
   CANDIDATE COMPARISON MODAL
================================================================= */
const CMP_ROWS = [
  { key: 'ats', label: 'ATS Score', get: (p, d) => p.ats, fmt: (v) => v, better: 'max', kind: 'num' },
  { key: 'req', label: 'Required Match', get: (p, d) => p.skills_pct, fmt: (v) => v + '%', better: 'max', kind: 'num' },
  { key: 'pref', label: 'Preferred Match', get: (p, d) => d.scores.preferredMatch, fmt: (v) => v + '%', better: 'max', kind: 'num' },
  { key: 'lead', label: 'Leadership', get: (p, d) => d.scores.leadership, fmt: (v) => v, better: 'max', kind: 'num' },
  { key: 'risk', label: 'Risk', get: (p) => p.risk, better: 'risk', kind: 'risk' },
  { key: 'rec', label: 'Recommendation', get: (p) => p.decision, better: 'rec', kind: 'rec' },
  { key: 'ent', label: 'Enterprise Experience', get: (p) => p.years, fmt: (v, p) => `${v} yrs · ${p.company}`, better: 'max', kind: 'num' },
  { key: 'str', label: 'Top Strengths', get: (p) => p.strengths, better: 'maxlen', kind: 'tags-good' },
  { key: 'con', label: 'Top Concerns', get: (p) => p.gaps, better: 'minlen', kind: 'tags-bad' },
];

function winnersFor(row, cards) {
  const vals = cards.map(({ p, d }) => row.get(p, d));
  let best, cmp;
  if (row.better === 'max') { best = Math.max(...vals); cmp = (v) => v === best; }
  else if (row.better === 'risk') { best = Math.min(...vals.map((v) => RISK_RANK[v])); cmp = (v) => RISK_RANK[v] === best; }
  else if (row.better === 'rec') { best = Math.min(...vals.map((v) => REC_RANK[v])); cmp = (v) => REC_RANK[v] === best; }
  else if (row.better === 'maxlen') { best = Math.max(...vals.map((v) => v.length)); cmp = (v) => v.length === best; }
  else if (row.better === 'minlen') { best = Math.min(...vals.map((v) => v.length)); cmp = (v) => v.length === best; }
  // Only highlight if there's a meaningful differentiator (not everyone tied)
  const allSame = vals.every((v) => JSON.stringify(v) === JSON.stringify(vals[0]));
  return vals.map((v) => (!allSame && cmp(v)));
}

function CompareCell({ row, p, d, win }) {
  let content;
  if (row.kind === 'risk') content = <CBadge label={`${p.risk} risk`} variant={RISK_BADGE[p.risk]} />;
  else if (row.kind === 'rec') content = <CBadge label={REC_TEXT[p.decision].label} variant={REC_TEXT[p.decision].v} />;
  else if (row.kind === 'tags-good') content = <div className="cmp-tags">{p.strengths.map((s) => <CTag key={s} label={s} variant="strength" />)}</div>;
  else if (row.kind === 'tags-bad') content = <div className="cmp-tags">{p.gaps.length ? p.gaps.map((s) => <CTag key={s} label={s} variant="gap" />) : <span className="cmp-none">None</span>}</div>;
  else content = <span className="cmp-num">{row.fmt(row.get(p, d), p)}</span>;
  return <div className={'cmp-cell' + (win ? ' is-win' : '')}>{win && <span className="cmp-win"><Icon name="check" size={11} />Best</span>}{content}</div>;
}

function CompareModal({ open, initialId, onClose, pool, job }) {
  const [ids, setIds] = useS([]);
  const [picker, setPicker] = useS(false);
  useEffect(() => { if (open) { setIds(initialId ? [initialId] : []); setPicker(false); } }, [open, initialId]);
  if (!open) return null;

  const POOL = pool || CANDIDATES;
  const cards = ids.map((id) => { const p = POOL.find((c) => c.id === id); return { p, d: getDetail(p) }; }).filter((x) => x.p);
  const canAdd = cards.length < 3;
  const available = POOL.filter((c) => !ids.includes(c.id));
  const winMap = {};
  if (cards.length >= 2) CMP_ROWS.forEach((r) => { winMap[r.key] = winnersFor(r, cards); });

  return (
    <div className="cmp-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="cmp-modal">
        <div className="cmp-head">
          <div className="cmp-head-id">
            <span className="cmp-head-mark"><Icon name="analytics" size={17} /></span>
            <div>
              <h2 className="cmp-title">Candidate Comparison</h2>
              <div className="cmp-sub">{(job ? job.title : JOB.title)} · comparing {cards.length} of 3</div>
            </div>
          </div>
          <button className="cmp-x" onClick={onClose} aria-label="Close"><Icon name="reject" size={20} /></button>
        </div>

        <div className="cmp-scroll">
          <div className="cmp-grid" style={{ gridTemplateColumns: `180px repeat(${Math.max(cards.length, 1)}, minmax(200px, 1fr))${canAdd ? ' 200px' : ''}` }}>
            {/* header row */}
            <div className="cmp-corner">Criteria</div>
            {cards.map(({ p }) => (
              <div key={p.id} className="cmp-col-head">
                <button className="cmp-remove" onClick={() => setIds((x) => x.filter((id) => id !== p.id))} aria-label="Remove"><Icon name="reject" size={14} /></button>
                <CAvatar initials={p.initials} size="lg" color="charcoal" />
                <div className="cmp-col-name">{p.name}</div>
                <div className="cmp-col-sub">{p.headline}</div>
                <div className="cmp-col-co">{p.company} · {p.location}</div>
              </div>
            ))}
            {canAdd && (
              <div className="cmp-col-add">
                {!picker ? (
                  <button className="cmp-add-btn" onClick={() => setPicker(true)}>
                    <span className="cmp-add-ico"><Icon name="plus" size={20} /></span>
                    Add candidate
                  </button>
                ) : (
                  <div className="cmp-picker">
                    <div className="cmp-picker-title">Add to comparison</div>
                    {available.map((c) => (
                      <button key={c.id} className="cmp-picker-item" onClick={() => { setIds((x) => [...x, c.id]); setPicker(false); }}>
                        <CAvatar initials={c.initials} size="sm" color="charcoal" />
                        <div className="cmp-picker-id"><span>{c.name}</span><small>ATS {c.ats} · {c.years} yrs</small></div>
                      </button>
                    ))}
                    <button className="cmp-picker-cancel" onClick={() => setPicker(false)}>Cancel</button>
                  </div>
                )}
              </div>
            )}

            {/* data rows */}
            {CMP_ROWS.map((row) => (
              <React.Fragment key={row.key}>
                <div className="cmp-rowlabel">{row.label}</div>
                {cards.map(({ p, d }, i) => (
                  <CompareCell key={p.id} row={row} p={p} d={d} win={winMap[row.key] ? winMap[row.key][i] : false} />
                ))}
                {canAdd && <div className="cmp-cell cmp-cell-empty" />}
              </React.Fragment>
            ))}
          </div>

          {cards.length < 2 && (
            <div className="cmp-hint">Add at least one more candidate to see a side-by-side comparison with per-row winners.</div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Copilot, CompareModal });
