// Method 8 — demo · Formative Health Report (Operating Model Health playback).
// De-branded reproduction of the Talison OMH executive playback STRUCTURE,
// populated with Gold Fields critical-risk content. Driven by one REPORT dict
// (same shape as the Talison fixture.CONTENT) so it's fully swappable.

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

const REPORT = {
  deck: {
    client: 'Gold Fields',
    function_name: 'Critical Risk Management — Operating Model Health',
    subtitle: 'Formative Health Assessment · Executive Summary',
    site: 'St Ives leadership team',
    date: '9 June 2026',
    prepared_by: 'Method 8',
  },
  overall: {
    health_pct: 53, avg_5: 3.4,
    categories: [
      { name: 'Understanding', pct: 82, avg_5: 4.0 },
      { name: 'Alignment', pct: 41, avg_5: 2.9 },
      { name: 'Performance Belief', pct: 80, avg_5: 4.0 },
    ],
    session_quality: { pct: 94, avg_5: 4.6,
      note: '17 of 18 participants rated the session high-quality and well-facilitated.' },
    key_findings: (
      'Critical controls are well understood (82%) and the team believes the system works when ' +
      "it's followed (80%). But alignment on how controls are executed in the field sits at just 41%, " +
      'dragging overall health to 53%. The gap concentrates in field verification — documented ' +
      'sign-off has outrun what is actually checked at the face.'
    ),
  },
  understanding: {
    statement: '"I understand the critical controls and how they apply to my work."',
    before_pct: 31, before_avg: 3.2,
    after_pct: 84, after_avg: 3.9,
    before_note: 'Only 31% agreed or strongly agreed before the session.',
    after_note: 'After the session, 84% agreed or strongly agreed — a clear lift in shared understanding.',
    insight: (
      'The workshop lifted understanding of the critical-risk model by +53pp. The expectations are ' +
      'clear once articulated — the challenge is embedding them into day-to-day field execution, not ' +
      'explaining them.'
    ),
  },
  elements: [
    { num: 1, name: 'Critical controls defined', health_pct: 78, avg_5: 4.1, distribution: [0, 1, 3, 8, 6],
      statement: '"Our critical controls are clearly defined for every material risk."',
      summary: 'The high-water mark of the session. Controls are well defined on paper and ownership is mostly clear. The work now is what happens after definition.',
      opportunities: 'Re-confirm a named owner for every material-risk control set, then move the focus from defining controls to verifying them.',
      notes: '"On paper we are in good shape — every material risk has its controls written down and owned."' },
    { num: 2, name: 'Frontline empowerment', health_pct: 56, avg_5: 3.5, distribution: [1, 2, 5, 7, 3],
      statement: '"Frontline workers feel able to stop a job when a critical control is missing."',
      summary: 'Stop-work authority exists but is not felt evenly. A meaningful minority — concentrated among contractors and newer crews — do not feel able to call a stop without blame.',
      opportunities: 'Brief a single stop-work standard across crews and contractors, and have leaders publicly back the next stop that is called.',
      notes: '"Our own crews will call it. With contractors it is patchier — they are not sure it will be backed."' },
    { num: 3, name: 'Field verification', health_pct: 22, avg_5: 2.6, distribution: [3, 6, 5, 3, 1],
      statement: '"Critical controls are verified in the field — not just signed off on paper."',
      summary: 'Lowest-scoring expectation, and the priority. Verification is documented but not consistently done at the face — isolation, working-at-height and confined-space checks are the weakest.',
      opportunities: 'Stand up field-leader verification routines for the unverified critical controls before the next gap assessment. Measure verifications done, not sign-offs collected.',
      notes: '"The sign-off is there. Whether someone actually walked the control at the face — that is the bit we cannot prove."' },
    { num: 4, name: 'Learning from incidents', health_pct: 44, avg_5: 3.3, distribution: [1, 3, 6, 6, 2],
      statement: '"We learn from incidents and near-misses, and visibly act on them."',
      summary: 'Reporting happens, but closing the loop back to crews is inconsistent. Lessons are captured centrally and do not always return to the people who need them.',
      opportunities: 'Set a 7-day standard for feeding incident and near-miss learnings back to the originating crew, with a visible action.',
      notes: '"We report it. What we do not always see is what changed because of it."' },
    { num: 5, name: 'Visible leadership', health_pct: 67, avg_5: 3.8, distribution: [0, 2, 4, 8, 4],
      statement: '"Leaders are visible and consistent on critical-risk discipline."',
      summary: 'Solid. Leadership presence is felt, especially on day shift. The opportunity is to sustain that consistency into night shift and across the contractor workforce.',
      opportunities: 'Extend the day-shift leadership rhythm into night shift; make critical-risk discipline a standing item in shift handovers.',
      notes: '"Day shift you see the leaders out there. Night shift it goes quiet."' },
  ],
  actions: [
    { num: 1, title: 'Stand up field-leader verification routines for the 3 unverified critical controls (isolation, working-at-height, confined space).', element: '3. Field verification', owner: 'Site Safety Lead · St Ives', priority: 'High', status: 'Open' },
    { num: 2, title: 'Formalise stop-work authority across crews and contractors with a single briefed standard.', element: '2. Frontline empowerment', owner: 'Operations Manager', priority: 'High', status: 'In progress' },
    { num: 3, title: 'Close the loop: feed incident & near-miss learnings back to crews within 7 days.', element: '4. Learning from incidents', owner: 'HSE Lead', priority: 'Medium', status: 'Open' },
    { num: 4, title: 'Sustain day-shift leadership visibility into night shift via shift-handover discipline.', element: '5. Visible leadership', owner: 'Shift Superintendents', priority: 'Medium', status: 'Noted' },
    { num: 5, title: 'Re-confirm critical-control ownership for every material risk.', element: '1. Critical controls defined', owner: 'Risk Lead', priority: 'Low', status: 'Closed' },
  ],
};

function hpColor(v) { return v >= 70 ? '#17b26a' : v >= 60 ? '#66c61c' : v >= 50 ? '#fdb022' : v >= 40 ? '#f79009' : '#f04438'; }
const STATUS_CLS = { 'Open': 'red', 'In progress': 'amber', 'Noted': 'gray', 'Closed': 'green' };
const PRIO_CLS = { 'High': 'red', 'Medium': 'amber', 'Low': 'gray' };

// compact 1..5 response-distribution strip
function DistStrip({ counts }) {
  const total = counts.reduce((a, b) => a + b, 0) || 1;
  const COL = ['#f04438', '#f79009', '#fdb022', '#66c61c', '#17b26a'];
  return (
    <div className="rep-dist">
      {counts.map((c, i) => (
        <div key={i} className="rep-dist-col" title={`${i + 1}: ${c}`}>
          <div className="rep-dist-bar" style={{ height: `${Math.max(6, (c / total) * 100)}%`, background: COL[i], opacity: c ? 1 : .25 }}/>
          <span className="rep-dist-n">{c}</span>
          <span className="rep-dist-x">{i + 1}</span>
        </div>
      ))}
    </div>
  );
}

function ReportView() {
  const { go } = useNav();
  const d = REPORT.deck, o = REPORT.overall, u = REPORT.understanding;

  return (
    <>
      <AISum
        head={<>Overall Operating Model Health is <b>{o.health_pct}%</b> ({o.avg_5.toFixed(1)}/5). <b>Field verification</b> ({REPORT.elements[2].health_pct}%) is the single drag; understanding lifted <b>+{u.after_pct - u.before_pct}pp</b> in the room.</>}
        act="Review the actions register — field-leader verification is the priority before the next gap assessment."/>

      {/* ---- cover band (de-branded) ---- */}
      <div className="rep-cover">
        <div className="rep-cover-l">
          <div className="rep-eyebrow">Formative Health Assessment · Operating Model Health</div>
          <h1>{d.function_name}</h1>
          <div className="rep-sub">{d.site} · {d.date}</div>
        </div>
        <div className="rep-cover-r">
          <Gauge value={o.health_pct} size={92} sw={8}/>
          <div className="rep-cover-meta">
            <div className="rep-prep"><span className="o-dot"/> Prepared by <b>{d.prepared_by}</b></div>
            <button className="btn btn-sec btn-sm" onClick={() => go('workshop')}><Ico d={I.arrowR} sw={2.2} size={13} style={{ transform: 'rotate(180deg)' }}/> Back to workshop</button>
          </div>
        </div>
      </div>

      {/* ---- executive summary: categories + session quality ---- */}
      <div className="card" style={{ marginBottom: 18 }}>
        <div className="card-head"><div className="card-head-l"><h2>Executive summary</h2><div className="sub">Health by score category · session quality</div></div></div>
        <div className="card-body">
          <div className="rep-cats">
            {o.categories.map(c => (
              <div key={c.name} className="rep-cat">
                <Gauge value={c.pct} size={62} sw={6}/>
                <div className="rep-cat-l"><div className="rep-cat-n">{c.name}</div><div className="rep-cat-a">{c.avg_5.toFixed(1)}/5 avg</div></div>
              </div>
            ))}
            <div className="rep-cat rep-cat-sq">
              <div className="rep-sq-n" style={{ color: '#067647' }}>{o.session_quality.pct}%</div>
              <div className="rep-cat-l"><div className="rep-cat-n">Session quality</div><div className="rep-cat-a">{o.session_quality.avg_5.toFixed(1)}/5 · facilitation</div></div>
            </div>
          </div>
          <div className="rep-findings"><span className="rep-kf-tag">Key findings</span>{o.key_findings}</div>
        </div>
      </div>

      <div className="grid-2" style={{ marginBottom: 18 }}>
        {/* ---- understanding before/after ---- */}
        <div className="card">
          <div className="card-head"><div className="card-head-l"><h2>Understanding · before → after</h2><div className="sub">{u.statement}</div></div><span className="badge green">+{u.after_pct - u.before_pct}pp</span></div>
          <div className="card-body">
            <div className="rep-ba">
              <div className="rep-ba-cell"><div className="rep-ba-k">Before</div><div className="rep-ba-v" style={{ color: hpColor(u.before_pct) }}>{u.before_pct}%</div><div className="rep-ba-a">{u.before_avg.toFixed(1)}/5</div></div>
              <Ico d={I.arrowR} sw={2.4} size={22} style={{ color: 'var(--ink4)', flex: 'none' }}/>
              <div className="rep-ba-cell"><div className="rep-ba-k">After</div><div className="rep-ba-v" style={{ color: hpColor(u.after_pct) }}>{u.after_pct}%</div><div className="rep-ba-a">{u.after_avg.toFixed(1)}/5</div></div>
            </div>
            <div className="rep-insight"><Ico d={I.spark} sw={2.2} size={14} style={{ color: '#5925dc', flex: 'none', marginTop: 2 }}/><span>{u.insight}</span></div>
          </div>
        </div>

        {/* ---- at a glance tiles ---- */}
        <div className="card">
          <div className="card-head"><div className="card-head-l"><h2>At a glance</h2><div className="sub">5 expectations · health %</div></div></div>
          <div className="card-body">
            <div className="rep-tiles">
              {REPORT.elements.map(e => (
                <div key={e.num} className="rep-tile" style={{ borderColor: hpColor(e.health_pct) + '55' }}>
                  <div className="rep-tile-v" style={{ color: hpColor(e.health_pct) }}>{e.health_pct}%</div>
                  <div className="rep-tile-n">{e.name}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* ---- per-element detail ---- */}
      <div className="card" style={{ marginBottom: 18 }}>
        <div className="card-head"><div className="card-head-l"><h2>By expectation</h2><div className="sub">Response distribution, what we heard, and the opportunity</div></div></div>
        <div className="card-body" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {REPORT.elements.map(e => (
            <div key={e.num} className="rep-el">
              <div className="rep-el-head">
                <div className="rep-el-num" style={{ background: hpColor(e.health_pct) }}>{e.num}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="rep-el-name">{e.name}</div>
                  <div className="rep-el-stmt">{e.statement}</div>
                </div>
                <div className="rep-el-score" style={{ color: hpColor(e.health_pct) }}>{e.health_pct}%<small>{e.avg_5.toFixed(1)}/5</small></div>
                <DistStrip counts={e.distribution}/>
              </div>
              <div className="rep-el-body">
                <div className="rep-el-col"><div className="rep-el-k">What we heard</div><p>{e.summary}</p><div className="rep-el-note">"{e.notes.replace(/^"|"$/g, '')}"</div></div>
                <div className="rep-el-col"><div className="rep-el-k ai"><Ico d={I.spark} sw={2.2} size={11}/> Opportunity</div><p>{e.opportunities}</p></div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ---- actions register ---- */}
      <div className="card">
        <div className="card-head"><div className="card-head-l"><h2>Actions register</h2><div className="sub">Drafted from the gaps · owner · priority · status</div></div><span className="badge violet"><Ico d={I.spark} sw={2} size={12}/> {REPORT.actions.length} actions</span></div>
        <div className="card-body" style={{ padding: '6px 8px 8px' }}>
          <table className="rep-actions">
            <thead><tr><th>#</th><th>Action</th><th>Expectation</th><th>Owner</th><th>Priority</th><th>Status</th></tr></thead>
            <tbody>
              {REPORT.actions.map(a => (
                <tr key={a.num}>
                  <td className="ra-n">{a.num}</td>
                  <td className="ra-t">{a.title}</td>
                  <td className="ra-e">{a.element}</td>
                  <td className="ra-o">{a.owner}</td>
                  <td><span className={`pill ${PRIO_CLS[a.priority]}`}>{a.priority}</span></td>
                  <td><span className={`pill ${STATUS_CLS[a.status]}`}>{a.status}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { ReportView });
