// Method8 — demo · AI Gap Assessment (Assure).
// Same dual-answer layout as the Standard Gap Assessment, but you drag in the
// raw documents, see the document list, and Method8 prepopulates the answers —
// with tags over each question showing what's been done and which doc evidenced it.

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

const YNNA = [['yes', 'Yes'], ['no', 'No'], ['na', 'N/A']];

// dropped raw documents
const DOCS = [
  ['WHS-MP-002 Health Management Plan.pdf', 'PDF', '#d92d20', '2.4 MB'],
  ['ADM-ST-0012 PPE Standard.docx', 'DOC', '#175cd3', '480 KB'],
  ['WHS-ST-0016 Safe Work Instruction.docx', 'DOC', '#175cd3', '512 KB'],
  ['MGT-PY-002 WHS Policy Statement.pdf', 'PDF', '#d92d20', '1.1 MB'],
  ['Job Role Profiles x60.xlsx', 'XLS', '#067647', '890 KB'],
  ['Monthly HSE Report Q1.pdf', 'PDF', '#d92d20', '3.2 MB'],
];

// AI prepopulation per question id: which doc it came from (null = couldn't determine)
const AI_SRC = {
  'q-mandate': 'MGT-PY-002 WHS Policy Statement',
  'q-interfaces': 'Service catalogue',
  'q-roles': null,
  'q-standards': 'ADM-ST-0012 · WHS-ST-0016',
  'q-docs': null,
  'q-risks': 'WHS-MP-002 Health Mgmt Plan',
  'q-proc': 'ADM-PR procedures',
  'q-raci': null,
  'q-apps': null,
  'q-report': 'Monthly HSE Report Q1',
  'q-metrics': null,
  'q-routines': 'Monthly HSE Report Q1',
};

function ReadSeg({ value }) {
  return (
    <div className="ga-seg">
      {YNNA.map(([v, l]) => <button key={v} className={value === v ? `sel ${v}` : ''} style={{ cursor: 'default' }} type="button">{l}</button>)}
    </div>
  );
}

function AIQuestion({ q }) {
  const GI = window.GAP_GI; const isQDone = window.gapIsQDone;
  const main = q.main || null;
  const evidence = q.evidence || null;
  const findings = q.findings || '';
  const showEvidence = main === 'yes';
  const showFindings = main === 'no' || (main === 'yes' && evidence === 'no');
  const showConformant = main === 'yes' && (evidence === 'yes' || evidence === 'na');
  const done = isQDone({ main, evidence, findings });
  const src = AI_SRC[q.id];
  const auto = !!main;            // AI managed to set an answer
  const needs = !done || !src;    // needs human review

  return (
    <div className={`ga-q gai-q ${done ? 'done' : ''}`}>
      <div className="ga-q-bar"/>
      <div className="ga-q-body">
        {/* AI tag bar */}
        <div className="gai-tagbar">
          {auto ? <span className="gai-tag ai"><Ico d={I.spark} sw={2.2}/> AI prepopulated</span> : <span className="gai-tag need"><Ico d={GI.alert} sw={2}/> Couldn’t determine</span>}
          {src && <span className="gai-tag src"><Ico d={I.file} sw={2}/> {src}</span>}
          {needs ? <span className="gai-tag need"><Ico d={GI.alert} sw={2}/> Needs review</span> : <span className="gai-tag done"><Ico d={GI.checkc} sw={2.4}/> Ready</span>}
        </div>
        {q.highPriority && <span className="ga-hp">HIGH PRIORITY</span>}
        <div className="ga-q-title">{q.title}</div>

        <div>
          <span className="ga-lbl">Do we have this in a process / system?</span>
          <ReadSeg value={main}/>
          {src && main && <div className="gai-prefill">Answered from <b>{src}</b></div>}
        </div>

        {showEvidence && (
          <div className="ga-sub">
            <span className="ga-lbl">Do you have evidence?</span>
            <ReadSeg value={evidence}/>
          </div>
        )}

        {showFindings && (
          <div className="ga-sub">
            <div className="ga-row-h"><span className="ga-lbl">Finding</span><Ico d={findings ? GI.checkc : GI.alert} sw={2} size={16} style={{ color: findings ? '#067647' : '#b42318' }}/></div>
            <textarea className="ga-ta" readOnly value={findings || '— Method8 could not draft a finding from the documents provided. Add detail to complete.'} style={{ background: 'var(--wash)' }}/>
            <button className="ga-addaction" type="button" style={{ marginTop: 12 }}><span className="txt">+ Add action</span><Ico d={GI.alert} sw={2} size={16} style={{ color: '#f79009' }}/></button>
          </div>
        )}

        {showConformant && (
          <div className="ga-sub">
            <span className="ga-lbl">Evidence Details</span>
            <textarea className="ga-ta" readOnly value={src ? `Evidenced from ${src}.` : ''} placeholder="Link or details" style={{ background: 'var(--wash)' }}/>
          </div>
        )}
      </div>
    </div>
  );
}

function GapAIView() {
  const { go } = useNav();
  const STANDARDS = window.GAP_STANDARDS; const GI = window.GAP_GI; const isQDone = window.gapIsQDone;
  const [activeStd, setActiveStd] = React.useState('gs');

  const allQs = STANDARDS.flatMap((s) => s.questions);
  const total = allQs.length;
  const auto = allQs.filter((q) => !!q.main).length;
  const needs = allQs.filter((q) => !q.main || !isQDone({ main: q.main, evidence: q.evidence, findings: q.findings }) || !AI_SRC[q.id]).length;
  const std = STANDARDS.find((s) => s.id === activeStd) || STANDARDS[0];
  const stdAuto = (s) => s.questions.every((q) => !!q.main && AI_SRC[q.id]);

  return (
    <>
      <AISum
        head={<>I read the <b>{DOCS.length} documents</b> you dropped in and prepopulated <b>{auto} of {total}</b> answers — getting the standard assessment as far as the raw docs allow. <b>{needs}</b> need your review.</>}
        act="Review the flagged questions, then accept to publish into the Standard Gap Assessment."/>

      <PageHead
        eyebrow={<><span>Assure · AI Gap Assessment</span><span className="dot"/><span>St Ives · Operating Model</span><span className="dot"/><span className="live">Auto-run · 6 min ago</span></>}
        title="AI Gap Assessment"
        sub={<>Drop the raw documents and Method8 prepopulates the same <b>process / system</b> and <b>evidence</b> answers as the standard assessment — tagging each with what it did and which document it used. You review and accept.</>}
        actions={<>
          <button className="btn btn-sec" onClick={() => go('gap')}>Open standard</button>
          <button className="btn btn-pri" onClick={() => go('gap')}><Ico d={GI.checkc} sw={2}/> Accept prepopulation</button>
        </>}/>

      {/* document dump */}
      <div className="gai-docs">
        <div className="gai-docs-h">
          <Ico d={I.spark} sw={2.2} size={18} style={{ color: '#5925dc' }}/>
          <span className="t">Documents</span>
          <span className="s">{DOCS.length} processed · {auto} answers prefilled</span>
          <span style={{ marginLeft: 'auto', font: '600 12px/16px Inter', color: '#067647', display: 'inline-flex', alignItems: 'center', gap: 6 }}><Ico d={GI.checkc} sw={2.4} size={14}/> Read &amp; indexed</span>
        </div>
        <div className="gai-drop" onClick={() => alert('Demo: would open the file picker.')}>
          <span className="di"><Ico d={I.plus} sw={2}/></span>
          <div><div className="dt"><b>Drop raw documents</b> or click to upload</div><div className="dd">PDF, Word, Excel — policies, standards, procedures, registers. Method8 reads them and fills what it can.</div></div>
        </div>
        <div className="gai-doclist">
          {DOCS.map(([name, ext, color, size]) => (
            <div key={name} className="gai-doc">
              <span className="fi" style={{ background: color }}>{ext}</span>
              <span className="fn" title={name}>{name}</span>
              <span className="fs">{size}</span>
              <Ico d={GI.checkc} sw={2.4} size={15} className="fok"/>
            </div>
          ))}
        </div>
      </div>

      {/* same layout as standard: sidebar + questions, but read-only AI-tagged */}
      <div className="ga-wrap">
        <div className="ga-side">
          <div className="ga-prog-track"><i style={{ width: `${Math.round(auto / total * 100)}%`, background: '#5925dc' }}/></div>
          <div className="ga-prog-meta"><span>{auto}/{total} auto-answered</span><span>{Math.round(auto / total * 100)}%</span></div>
          <div className="ga-side-divide"/>
          <div className="ga-side-h">Standards</div>
          {STANDARDS.map((s) => {
            const on = s.id === activeStd;
            const ok = stdAuto(s);
            return (
              <button key={s.id} className={`ga-std ${on ? 'on' : ''}`} onClick={() => setActiveStd(s.id)} type="button">
                <Ico d={GI.book} sw={1.8} className="bk"/>
                <span className="ga-std-t">{s.title}</span>
                {ok ? <Ico d={GI.checkc} sw={2} size={18} className="ga-std-s" style={{ color: '#5925dc' }}/> : <Ico d={GI.alert} sw={2} size={17} className="ga-std-s" style={{ color: '#f79009' }}/>}
              </button>
            );
          })}
        </div>

        <div className="ga-content">
          <div className="ga-chap-h">{std.title}</div>
          <div className="ga-chap-d">Method8 prepopulated these from your documents — tags show what it did and the source. Accept to publish, or open the standard to edit.</div>
          <div className="ga-qlist">
            {std.questions.map((q) => <AIQuestion key={q.id} q={q}/>)}
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { GapAIView });
