// Method 8 — demo · Gap assessment runtime (interactive).
// The REAL Gold Fields Safety Standard gap assessment, lifted from the live
// Method8 module form_data: 18 chapters, Yes/No (boolean) conformance criteria,
// "Example of evidence" prompts, High-Priority flags, gaps -> drafted actions.

const { Ico, I, AISum, PageHead, useNav } = window;

// Real Safety Standard chapters (from Safety Standard EN.json — 18 pages, 62 criteria).
const GAP_CHAPTERS = [
  ['2.1', 'Policy & Leadership Commitment', 'done'],
  ['2.2', 'Visible Felt Leadership', 'done'],
  ['2.3', 'Targets, Objectives & Performance Mgmt', 'done'],
  ['2.4', 'Legal & Compliance Management', 'done'],
  ['2.5', 'Business Partner Management', 'on'],
  ['2.6', 'Competency, Training & Fitness to Work', ''],
  ['2.7', 'Communication & Consultation', ''],
  ['2.8', 'Incident Reporting & Investigation', ''],
  ['2.9', 'Emergency Preparedness & Response', ''],
  ['2.10', 'Management Review', ''],
  ['2.11', 'Document Control & Records', ''],
  ['2.12', 'Risk Management & Work Management', ''],
  ['2.13', 'Critical Safety Processes', ''],
  ['2.12.1.1', 'Fitness for Work', ''],
  ['2.13.2', 'Permit to Work', ''],
  ['2.14.5', 'Management of Change', ''],
  ['2.13.6', 'Process Safety Management', ''],
  ['5', 'Compliance', ''],
];

// Active chapter 2.5 — verbatim criteria + evidence examples from the live module.
// hp = High Priority (Safety Standard HP set includes Q17).
const GAP_QS = [
  { n: '15', q: 'Business Partner selection criteria include safety requirements.',
    ev: 'Prequalification forms, contractor risk ratings', hp: false, a: 'yes', note: null },
  { n: '16', q: 'Business Partner work is risk-assessed, planned and managed.',
    ev: 'JHAs, authorisation for work, method statements / work plans, in-field checks', hp: false, a: 'yes', note: null },
  { n: '17', q: 'Business Partner work is sufficiently supervised and verified.',
    ev: 'Inspection records, Planned Task Observations', hp: true, a: 'no',
    note: 'Supervision is rostered but field verification is thin — PTO records cover 6 of 9 critical controls this quarter. Suggested action: a weekly field-leader verification routine for Business Partner high-risk work, with priority + owner.' },
  { n: '18', q: 'Business Partner training, induction and competency are verified.',
    ev: 'Training certificates, competency assessments, license checks', hp: false, a: 'yes', note: null },
  { n: '19', q: 'Business Partner safety performance is monitored.',
    ev: 'KPI reports, incident stats, inspection findings', hp: false, a: null,
    note: 'Not yet answered. Contractor KPI packs exist for 2 of 3 major partners — confirm the third is reporting before this is marked conformant.' },
];

const SCORE = { yes: 1, no: 0 };

function GapView() {
  const { go } = useNav();
  const [ans, setAns] = React.useState(() => Object.fromEntries(GAP_QS.map(q => [q.n, q.a])));

  const answered = GAP_QS.filter(q => ans[q.n] != null);
  const pct = answered.length ? Math.round(answered.reduce((s, q) => s + SCORE[ans[q.n]], 0) / answered.length * 100) : 0;
  const gaps = GAP_QS.filter(q => ans[q.n] === 'no').length;
  const hpGaps = GAP_QS.filter(q => ans[q.n] === 'no' && q.hp).length;
  const label = pct >= 70 ? 'conformant' : pct >= 55 ? 'partial' : 'gap';
  const badgeCls = pct >= 70 ? 'green' : pct >= 55 ? 'amber' : 'red';
  const allDone = answered.length === GAP_QS.length;

  const set = (n, v) => setAns(a => ({ ...a, [n]: a[n] === v ? null : v }));

  return (
    <>
      <AISum
        head={<>Business Partner Management is at <b>{pct}%</b> — {answered.length} of {GAP_QS.length} criteria answered, <b>{gaps} gap{gaps !== 1 ? 's' : ''}</b> found{hpGaps ? <> (<b>{hpGaps} High&nbsp;Priority</b>)</> : ''}.</>}
        act={allDone ? 'All criteria answered — submit for validation.' : 'Answer criterion 19, then submit for review.'}/>

      <PageHead
        eyebrow={<><span>Gap assessment</span><span className="dot"/><span>St Ives · Standard 1 of 11</span><span className="dot"/><span>Auto-saved</span></>}
        title="Safety Standard"
        sub={<>Method 8 prefilled this from your evidence and St Ives' records. <b>Confirm each answer or change it</b> — every gap becomes a drafted closure action with an owner and priority.</>}
        actions={<>
          <span className={`badge ${badgeCls}`} style={{ height: 30, fontSize: 12.5, padding: '0 11px' }}><span className="d"/> {pct}% · {label}</span>
          <button className="btn btn-pri" onClick={() => go('home')}>Submit for validation</button>
        </>}/>

      <div className="grid-2w">
        <div>
          <div className="card">
            <div className="card-head">
              <div className="card-head-l"><h2>2.5 · Business Partner Management</h2><div className="sub">AI prefilled · confirm or change. Try changing an answer — the score moves.</div></div>
              <div className="card-head-r"><span className="badge gray">{answered.length} / {GAP_QS.length} answered</span></div>
            </div>
            <div className="card-body">
              {GAP_QS.map(({ n, q, ev, hp, note }) => {
                const sel = ans[n];
                const flag = sel === 'no' || sel == null;
                return (
                  <div key={n} className={`asmt-q ${flag ? 'flag' : ''}`}>
                    <div className="asmt-qtop">
                      <span className="asmt-qn">{n}</span>
                      <span className="asmt-qt">{q}{hp && <span className="hp-badge"><Ico d={I.shield} sw={2.4} size={10}/> High Priority</span>}</span>
                    </div>
                    <div className="gap-ev"><span className="gap-ev-k">Evidence</span>{ev}</div>
                    <div className="asmt-opts">
                      <span className={`opt clk ${sel === 'yes' ? 'sel yes' : ''}`} onClick={() => set(n, 'yes')}>Conformant</span>
                      <span className={`opt clk ${sel === 'no' ? 'sel no' : ''}`} onClick={() => set(n, 'no')}>Gap</span>
                    </div>
                    {note && <div className="asmt-note"><span className="ai-tag"><Ico d={I.spark} sw={2.2} style={{ width: 11, height: 11 }}/> Method 8</span>{note}</div>}
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="card">
            <div className="card-head"><div className="card-head-l"><h2>Chapters</h2><div className="sub">18 chapters · 62 criteria</div></div></div>
            <div className="card-body" style={{ padding: 10 }}>
              <div className="arail">
                {GAP_CHAPTERS.map(([num, nm, st], i) => (
                  <div key={num} className={`arail-item ${st}`}>
                    <span className="rn">{st === 'done' ? <Ico d={I.check} sw={3} style={{ width: 11, height: 11 }}/> : num}</span>
                    {nm}
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-body" style={{ padding: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 9 }}>
                <div className="feed-ic ai" style={{ width: 32, height: 32 }}><Ico d={I.spark} sw={2.2}/></div>
                <div style={{ font: '600 13px/17px Inter' }}>Method 8 assist</div>
              </div>
              <div style={{ font: '400 12.5px/18px Inter', color: 'var(--ink3)' }}>
                {gaps === 0
                  ? 'No gaps in this chapter — nice. I\'ll mark it conformant on submit.'
                  : <>{gaps} gap{gaps !== 1 ? 's' : ''} found{hpGaps ? <>, <b>{hpGaps} High&nbsp;Priority</b></> : ''}. On submit I\'ll draft {gaps} closure action{gaps !== 1 ? 's' : ''} with an owner, priority and status, and route them to the St Ives site owner.</>}
              </div>
              <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, font: '500 12px/16px Inter', color: 'var(--ink3)' }}>
                  <span style={{ flex: 1 }}>Chapter conformance</span>
                  <span style={{ font: '700 14px/1 Inter', color: pct >= 70 ? '#067647' : pct >= 55 ? '#b54708' : '#b42318' }}>{pct}%</span>
                </div>
                <div style={{ height: 8, background: 'var(--wash2)', borderRadius: 4, overflow: 'hidden' }}>
                  <div style={{ width: `${pct}%`, height: '100%', borderRadius: 4, background: pct >= 70 ? '#17b26a' : pct >= 55 ? '#f79009' : '#f04438', transition: 'width .4s cubic-bezier(.2,.7,.3,1), background .3s' }}/>
                </div>
              </div>
              <button className="btn btn-sec btn-sm" style={{ marginTop: 13, width: '100%' }} disabled={gaps === 0} onClick={() => go('report')}>Preview {gaps} draft action{gaps !== 1 ? 's' : ''}</button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { GapView });
