// Gold Fields engagement — multi-site gap-assessment rollout (wide & shallow).
// 15 locations × 30 gap assessments across 11 standards.

const { Ico, I, Sidebar, Topbar, Gauge, Blocks, StatCard, OSRail, AISum, tone } = window;

// ---- Data ----
const GF_STANDARDS = [
  ['SAF', 'Safety'], ['ENV', 'Environment'], ['CON', 'Contractor mgmt'],
  ['CRM', 'Critical risk'], ['TSF', 'Tailings & dams'], ['EMG', 'Emergency prep'],
  ['HYG', 'Health & hygiene'], ['ENE', 'Energy & climate'], ['WAT', 'Water stewardship'],
  ['COM', 'Community & land'], ['CYN', 'Cyanide mgmt'],
];

const GF_REGIONS = [
  { name: 'Australia', x: 82, y: 70, sites: [
    ['St Ives', 88], ['Agnew', 79], ['Granny Smith', 74], ['Gruyere', 91], ['Lefroy Mill', 62],
  ]},
  { name: 'West Africa', x: 47, y: 52, sites: [
    ['Tarkwa', 71], ['Damang', 58], ['Asanko', 44],
  ]},
  { name: 'Southern Africa', x: 54, y: 76, sites: [
    ['South Deep', 67], ['Westonaria Hub', 80],
  ]},
  { name: 'Americas', x: 26, y: 60, sites: [
    ['Cerro Corona', 73], ['Salares Norte', 39], ['Salares Plant', 51], ['Windfall', 28],
  ]},
];
const GF_SITES = GF_REGIONS.flatMap(r => r.sites.map(([n, p]) => ({ n, p, region: r.name })));

function pcTone(p) { return p >= 70 ? 'good' : p >= 50 ? 'ok' : 'bad'; }
function cellClass(v) {
  if (v == null) return 'todo';
  if (v >= 85) return 'g3'; if (v >= 70) return 'g2';
  if (v >= 55) return 'y2'; if (v >= 40) return 'y1'; return 'r1';
}

function Screen({ children, w = 1440, h = 900, sidebar, topbar, summary }) {
  return (
    <div className="e8 scr" style={{ width: w, height: h }}>
      {sidebar}
      <div className="main">
        {topbar}
        <div className="page" style={{ overflow: 'hidden' }}>{summary}{children}</div>
      </div>
    </div>
  );
}

/* ============================================================ GF1 — Onwards program builder */
function GF1_Builder() {
  return (
    <Screen w={1440} h={1108}
      sidebar={<Sidebar active="file" persona="admin"/>}
      topbar={<Topbar crumbs={['Method 8', 'Gold Fields', 'New program']} byline={<>Method 8 · <b>admin</b></>} search="Search clients, standards…"/>}>
      <header className="pg-head">
        <div className="pg-head-l">
          <div className="eyebrow"><span>Program builder</span><span className="dot"/><span>Gold Fields Group HSE</span></div>
          <h1>Assemble the engagement</h1>
          <div className="sub">Pick the <b>standards</b> and the <b>locations</b>. Method 8 generates one gap assessment per standard, per site, and schedules the rollout. <b>11 standards × 15 sites = 165 assessments</b>.</div>
        </div>
        <div className="pg-head-r">
          <button className="btn btn-sec">Save template</button>
          <button className="btn btn-pri"><Ico d={I.arrowR} sw={2}/> Publish to client</button>
        </div>
      </header>

      <div className="builder" style={{ minHeight: 560 }}>
        {/* Standards catalog */}
        <div className="bld-col">
          <div className="bld-h">Standards <span className="ct">11 / 11</span></div>
          {GF_STANDARDS.map(([ab, nm], i) => (
            <div key={ab} className="catitem on">
              <span className="ck"><Ico d={I.check} sw={3}/></span>
              <span className="nm">{nm}</span>
              <span className="mt">{[10,8,12,9,7,6,8,5,7,9,6][i]} criteria</span>
            </div>
          ))}
        </div>

        {/* Assembly */}
        <div className="bld-col mid">
          <div className="bld-h">Program structure <span className="ct">Gap assessment</span></div>
          <div className="bld-assembly">
            <div className="asm-line">
              <span className="asm-num">1</span>
              <div className="asm-body"><div className="asm-title">Baseline gap assessment</div><div className="asm-meta">11 standards · run once per site · self-assessment + evidence upload</div></div>
              <span className="badge blue">Assess</span>
            </div>
            <div className="asm-line">
              <span className="asm-num">2</span>
              <div className="asm-body"><div className="asm-title">Delivery review</div><div className="asm-meta">Specialist reviews evidence, confirms conformance rating</div></div>
              <span className="badge gray">Review</span>
            </div>
            <div className="asm-line">
              <span className="asm-num">3</span>
              <div className="asm-body"><div className="asm-title">Findings & action plan</div><div className="asm-meta">AI-drafted closure actions per non-conformance → site owner</div></div>
              <span className="badge violet">AI draft</span>
            </div>
            <div className="asm-line" style={{ borderStyle: 'dashed', opacity: .7 }}>
              <span className="asm-num" style={{ background: '#98a2b3' }}>4</span>
              <div className="asm-body"><div className="asm-title">Re-assessment (optional)</div><div className="asm-meta">Schedule 6-month follow-up to confirm closure</div></div>
              <span className="badge gray">Later</span>
            </div>
          </div>
          <hr className="hr"/>
          <div className="bld-h" style={{ marginBottom: 8 }}>Rollout schedule</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <span className="badge gray"><Ico d={I.cal} sw={2} style={{width:12,height:12}}/> Wave 1 · Australia · Mar</span>
            <span className="badge gray">Wave 2 · West Africa · Apr</span>
            <span className="badge gray">Wave 3 · Sthn Africa · Apr</span>
            <span className="badge gray">Wave 4 · Americas · May</span>
          </div>
        </div>

        {/* Locations + access */}
        <div className="bld-col">
          <div className="bld-h">Locations <span className="ct">15 / 15</span></div>
          {GF_REGIONS.map(r => (
            <div key={r.name} style={{ marginBottom: 10 }}>
              <div style={{ font: '600 11px/14px Inter', color: 'var(--ink4)', textTransform: 'uppercase', letterSpacing: '.4px', marginBottom: 6 }}>{r.name}</div>
              {r.sites.map(([nm]) => (
                <div key={nm} className="catitem on" style={{ padding: '6px 9px', marginBottom: 5 }}>
                  <span className="ck" style={{ width: 16, height: 16 }}><Ico d={I.check} sw={3}/></span>
                  <span className="nm" style={{ fontSize: 12.5 }}>{nm}</span>
                </div>
              ))}
            </div>
          ))}
          <hr className="hr"/>
          <div className="osrail" style={{ background: '#fff', padding: '11px 12px' }}>
            <div className="osrail-h" style={{ marginBottom: 7 }}>Client access</div>
            <div style={{ font: '400 12px/17px Inter', color: 'var(--ink3)' }}>Gold Fields will get keys to <b style={{color:'var(--ink2)'}}>Assessments</b> + <b style={{color:'var(--ink2)'}}>Actions</b> only. Operating Model, Health & Improve stay locked.</div>
          </div>
        </div>
      </div>
    </Screen>
  );
}

/* ============================================================ GF2 — Client control tower (region grid) */
function GF2_GridTower() {
  return (
    <Screen summary={<AISum head="Group conformance 68% (+6 QoQ). The Americas region lags at 54% — Salares Norte and Windfall are the weak spots." act="Open the Americas — 3 sites sit below 50%."/>} w={1440} h={1076}
      sidebar={<Sidebar active="grid" persona="client" locked={['model','target']}/>}
      topbar={<Topbar crumbs={['Gold Fields', 'Group HSE assurance']} byline={<>Powered by <b>Method 8</b></>} search="Search across 15 sites…"/>}>
      <header className="pg-head">
        <div className="pg-head-l">
          <div className="eyebrow"><span>Group HSE assurance</span><span className="dot"/><span>15 sites · 4 regions</span><span className="dot"/><span className="live">Live — synced 8 min ago</span></div>
          <h1>Standards gap assessment · portfolio</h1>
          <div className="sub">Every site, scored against the same <b>11 group standards</b>. <b>165 gap assessments</b> in flight, independently reviewed.</div>
        </div>
        <div className="pg-head-r">
          <button className="btn btn-ai"><Ico d={I.spark} sw={2}/> Ask Method 8</button>
          <button className="btn btn-sec"><Ico d={I.ext} sw={2}/> Export board pack</button>
        </div>
      </header>

      <section className="stats">
        <StatCard hue="sky" icon={I.map} trend="4 regions" trendDir="flat" label="Operating sites" value="15" unit="active" foot={<><b>Australia 5</b><span className="pip"/><b>Africa 6</b><span className="pip"/><b>Americas 4</b></>}/>
        <StatCard hue="violet" icon={I.shield} trend="+6 pts QoQ" trendDir="up" label="Group conformance" value="68" unit="%" foot={<><b>Aligned</b><span className="pip"/>3 sites below 50%</>}/>
        <StatCard hue="fuchsia" icon={I.file} trend="71% done" trendDir="up" label="Gap assessments" value="117" unit="/ 165" foot={<><b>117 complete</b><span className="pip"/><b>48</b> in progress</>}/>
        <StatCard hue="orange" icon={I.target} trend="9 new" trendDir="up" label="Open closure actions" value="214" unit="open" foot={<><b>38 high</b><span className="pip"/>across 11 standards</>}/>
      </section>

      <div className="grid-2">
        <div className="card">
          <div className="card-head">
            <div className="card-head-l"><h2>Sites by region</h2><div className="sub">Average conformance across the 11 standards</div></div>
            <div className="card-head-r">
              <div className="pill-tabs"><button className="pill-tab active">By region</button><button className="pill-tab">By standard</button><button className="pill-tab">Needs attention</button></div>
            </div>
          </div>
          <div className="card-body">
            <div className="regions">
              {GF_REGIONS.map(r => {
                const avg = Math.round(r.sites.reduce((a, [, p]) => a + p, 0) / r.sites.length);
                return (
                  <div key={r.name} className="region">
                    <div className="region-h"><span>{r.name}</span><span className="badge gray">{r.sites.length}</span></div>
                    {r.sites.map(([nm, p]) => (
                      <div key={nm} className="site-chip">
                        <Gauge value={p} size={34} sw={4}/>
                        <span className="nm">{nm}</span>
                        <span className="pct" style={{ color: p >= 70 ? '#067647' : p >= 50 ? '#b54708' : '#b42318' }}>{p}%</span>
                      </div>
                    ))}
                    <div style={{ font: '400 11px/14px Inter', color: 'var(--ink4)', marginTop: 4, textAlign: 'right' }}>region avg <b style={{ color: 'var(--ink2)' }}>{avg}%</b></div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="card">
            <div className="card-head"><div className="card-head-l"><h2>Lowest conformance</h2><div className="sub">Standards needing group attention</div></div></div>
            <div className="card-body" style={{ paddingTop: 10 }}>
              {[['Cyanide mgmt', 'Salares Norte', 39], ['Tailings & dams', 'Asanko', 44], ['Contractor mgmt', 'Windfall', 41], ['Water stewardship', 'Damang', 52]].map(([std, site, v], i) => (
                <div key={i} className="feed-item" style={{ gridTemplateColumns: '1fr auto', alignItems: 'center' }}>
                  <div><div className="feed-msg"><b>{std}</b></div><div className="feed-meta">{site}</div></div>
                  <span className="badge red"><span className="d"/> {v}%</span>
                </div>
              ))}
            </div>
          </div>
          <OSRail on={['Assess']} note={<>You're running <b style={{color:'var(--ink2)'}}>Assess</b>. The rest of the operating system — design, governance, continuous improvement — is available when you are. <a>See how it fits →</a></>}/>
        </div>
      </div>
    </Screen>
  );
}

/* ============================================================ GF3 — Client control tower (geo map) */
function GF3_MapTower() {
  return (
    <Screen summary={<AISum head="Most sites are green or amber; two reds in the Americas." act="Open Salares Norte (39%) — cyanide and tailings gaps."/>} w={1440} h={1128}
      sidebar={<Sidebar active="grid" persona="client" locked={['model','target']}/>}
      topbar={<Topbar crumbs={['Gold Fields', 'Group HSE assurance', 'Map']} byline={<>Powered by <b>Method 8</b></>} search="Search across 15 sites…"/>}>
      <header className="pg-head">
        <div className="pg-head-l">
          <div className="eyebrow"><span>Group HSE assurance</span><span className="dot"/><span className="live">Live — synced 8 min ago</span></div>
          <h1>Gap assessment · global map</h1>
          <div className="sub">15 operating sites across 4 regions. Pin colour shows average conformance; tap a site to open its 11 standards.</div>
        </div>
        <div className="pg-head-r">
          <div className="pill-tabs"><button className="pill-tab">Grid</button><button className="pill-tab active">Map</button></div>
        </div>
      </header>

      <section className="stats" style={{ gridTemplateColumns: 'repeat(4,1fr)' }}>
        <StatCard hue="sky" icon={I.map} trend="4 regions" trendDir="flat" label="Operating sites" value="15"/>
        <StatCard hue="violet" icon={I.shield} trend="+6 pts" trendDir="up" label="Group conformance" value="68" unit="%"/>
        <StatCard hue="fuchsia" icon={I.file} trend="71%" trendDir="up" label="Assessments done" value="117" unit="/ 165"/>
        <StatCard hue="orange" icon={I.target} trend="38 high" trendDir="up" label="Open actions" value="214"/>
      </section>

      <div className="card">
        <div className="card-head">
          <div className="card-head-l"><h2>Conformance by site</h2><div className="sub">Hover a pin for the per-standard breakdown</div></div>
          <div className="card-head-r" style={{ gap: 14 }}>
            <span className="legend" style={{ marginTop: 0, gap: 12 }}>
              <span className="li"><span className="sw" style={{ background: '#17b26a' }}/> ≥70%</span>
              <span className="li"><span className="sw" style={{ background: '#f79009' }}/> 50–69%</span>
              <span className="li"><span className="sw" style={{ background: '#f04438' }}/> &lt;50%</span>
            </span>
          </div>
        </div>
        <div className="card-body" style={{ padding: 16 }}>
          <div className="geomap">
            <svg viewBox="0 0 100 56" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
              {/* schematic continents — intentionally abstract */}
              <ellipse className="continent" cx="24" cy="22" rx="11" ry="9"/>
              <ellipse className="continent" cx="28" cy="40" rx="6" ry="9"/>
              <ellipse className="continent" cx="49" cy="24" rx="7" ry="7"/>
              <ellipse className="continent" cx="52" cy="40" rx="7" ry="9"/>
              <ellipse className="continent" cx="68" cy="22" rx="13" ry="9"/>
              <ellipse className="continent" cx="82" cy="40" rx="8" ry="6"/>
            </svg>
            {GF_REGIONS.map(r => (
              <div key={r.name} className="geo-region" style={{ left: `${r.x}%`, top: `${r.y - 16}%` }}>{r.name}</div>
            ))}
            {GF_REGIONS.flatMap((r, ri) => r.sites.map(([nm, p], si) => {
              const ang = (si / r.sites.length) * Math.PI * 2;
              const rad = r.sites.length > 1 ? 7 : 0;
              const x = r.x + Math.cos(ang) * rad;
              const y = r.y + Math.sin(ang) * rad * 0.8;
              return (
                <div key={nm} className="geo-pin" style={{ left: `${x}%`, top: `${y}%` }}>
                  <div className={`geo-dot ${pcTone(p)}`}>{p}</div>
                  <div className="geo-lbl">{nm}</div>
                </div>
              );
            }))}
          </div>
        </div>
      </div>

      <div style={{ marginTop: 16 }}>
        <OSRail on={['Assess']} note={<>Assessments + actions are unlocked for this engagement. <a>Talk to us about continuous monitoring →</a></>}/>
      </div>
    </Screen>
  );
}

/* ============================================================ GF4 — Rollup matrix (sites × standards) */
function GF4_Matrix() {
  // deterministic pseudo values
  const val = (si, ci) => {
    const base = GF_SITES[si].p;
    const v = Math.round(base + Math.sin((si + 1) * (ci + 2) * 1.7) * 22);
    return Math.max(20, Math.min(98, v));
  };
  return (
    <Screen summary={<AISum head="Cyanide and Contractor management are the weakest columns across the portfolio." act="Tackle the 5 red cells first."/>} w={1440} h={968}
      sidebar={<Sidebar active="file" persona="client" locked={['model','target']}/>}
      topbar={<Topbar crumbs={['Gold Fields', 'Gap assessment', 'Rollup']} byline={<>Powered by <b>Method 8</b></>} search="Search…"/>}>
      <header className="pg-head">
        <div className="pg-head-l">
          <div className="eyebrow"><span>Conformance matrix</span><span className="dot"/><span>15 sites × 11 standards</span></div>
          <h1>Where are the gaps?</h1>
          <div className="sub">Every cell is one validated gap assessment. Read down a column to compare sites on a standard; read across a row to see a site's profile.</div>
        </div>
        <div className="pg-head-r">
          <div className="pill-tabs"><button className="pill-tab">By site</button><button className="pill-tab active">By standard</button><button className="pill-tab">By phase</button></div>
        </div>
      </header>

      <div className="card">
        <div className="card-body" style={{ padding: '16px 18px' }}>
          <table className="matrix">
            <thead>
              <tr>
                <th className="rowh"> </th>
                {GF_STANDARDS.map(([ab, nm]) => <th key={ab} title={nm}>{ab}</th>)}
                <th>AVG</th>
              </tr>
            </thead>
            <tbody>
              {GF_SITES.map((s, si) => {
                const row = GF_STANDARDS.map((_, ci) => val(si, ci));
                const avg = Math.round(row.reduce((a, b) => a + b, 0) / row.length);
                return (
                  <tr key={s.n}>
                    <td className="rowh">{s.n}<span className="reg">{s.region}</span></td>
                    {row.map((v, ci) => <td key={ci}><div className={`cell ${cellClass(v)}`}>{v}</div></td>)}
                    <td><div className="cell" style={{ background: '#1f242f', color: '#fff' }}>{avg}</div></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          <div className="legend">
            <span className="li"><span className="sw cell g3" style={{height:15}}/> ≥85 conformant</span>
            <span className="li"><span className="sw cell g2" style={{height:15}}/> 70–84</span>
            <span className="li"><span className="sw cell y2" style={{height:15}}/> 55–69</span>
            <span className="li"><span className="sw cell y1" style={{height:15}}/> 40–54</span>
            <span className="li"><span className="sw cell r1" style={{height:15}}/> &lt;40 major gap</span>
          </div>
        </div>
      </div>
    </Screen>
  );
}

/* ============================================================ GF5 — Location drill-in */
function GF5_Site() {
  const stds = [
    ['Safety', 88, 'g3', 10, 10], ['Environment', 81, 'g2', 8, 8], ['Contractor mgmt', 64, 'y2', 9, 12],
    ['Critical risk', 79, 'g2', 7, 9], ['Tailings & dams', 92, 'g3', 7, 7], ['Emergency prep', 71, 'g2', 5, 6],
    ['Health & hygiene', 83, 'g2', 7, 8], ['Energy & climate', 58, 'y2', 3, 5], ['Water stewardship', 76, 'g2', 6, 7],
    ['Community & land', 69, 'y2', 6, 9], ['Cyanide mgmt', 90, 'g3', 6, 6],
  ];
  return (
    <Screen summary={<AISum head="St Ives is at 77%, above the group. 9 of 11 standards reviewed; Energy and Contractor still open." act="Chase 2 evidence items before the Apr 2 readout."/>} w={1440} h={1278}
      sidebar={<Sidebar active="grid" persona="client" locked={['model','target']}/>}
      topbar={<Topbar crumbs={['Gold Fields', 'Sites', 'St Ives']} byline={<>Powered by <b>Method 8</b></>} search="Search St Ives…"/>}>
      <header className="pg-head">
        <div className="pg-head-l">
          <div className="eyebrow"><span>Australia</span><span className="dot"/><span>Site owner · Adetola Okafor</span><span className="dot"/><span className="live">Validated 3 days ago</span></div>
          <h1>St Ives · gap assessment</h1>
          <div className="sub">All <b>11 group standards</b> assessed against <b>30 gap assessments</b>. 9 of 11 reviewed; 2 awaiting evidence.</div>
        </div>
        <div className="pg-head-r">
          <button className="btn btn-ai"><Ico d={I.spark} sw={2}/> Summarise for site GM</button>
          <button className="btn btn-pri"><Ico d={I.ext} sw={2}/> Site report</button>
        </div>
      </header>

      <section className="stats">
        <StatCard hue="violet" icon={I.shield} trend="+5 pts" trendDir="up" label="Site conformance" value="77" unit="%" foot={<><b>Above</b> group avg (68%)</>}/>
        <StatCard hue="fuchsia" icon={I.file} trend="27 / 30" trendDir="up" label="Assessments complete" value="90" unit="%" foot={<><b>9 / 11</b> standards validated</>}/>
        <StatCard hue="orange" icon={I.target} trend="4 closed" trendDir="up" label="Open actions" value="13" foot={<><b>2 high</b><span className="pip"/>8 med<span className="pip"/>3 low</>}/>
        <StatCard hue="sky" icon={I.users} trend="" trendDir="flat" label="Contributors" value="11" foot={<>HSE, ops, contractors</>}/>
      </section>

      <div className="grid-2">
        <div className="card">
          <div className="card-head"><div className="card-head-l"><h2>Standards profile</h2><div className="sub">Conformance against each group standard</div></div>
            <div className="card-head-r"><span className="card-link">Open matrix <Ico d={I.arrowR} sw={2}/></span></div>
          </div>
          <div className="card-body" style={{ paddingTop: 8 }}>
            {stds.map(([nm, v, , done, total], i) => (
              <div key={nm} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '10px 0', borderBottom: i < stds.length - 1 ? '1px solid var(--line2)' : 'none' }}>
                <Gauge value={v} size={40} sw={4}/>
                <div style={{ flex: 1 }}>
                  <div style={{ font: '600 14px/18px Inter' }}>{nm}</div>
                  <div style={{ font: '400 12px/16px Inter', color: 'var(--ink4)' }}>{done}/{total} criteria conformant</div>
                </div>
                <div style={{ width: 140 }}>
                  <div style={{ height: 6, background: 'var(--wash2)', borderRadius: 3, overflow: 'hidden' }}>
                    <div style={{ width: `${v}%`, height: '100%', background: v >= 70 ? '#17b26a' : v >= 55 ? '#f79009' : '#f04438' }}/>
                  </div>
                </div>
                <span className={`badge ${v >= 70 ? 'green' : v >= 55 ? 'amber' : 'red'}`} style={{ width: 64, justifyContent: 'center' }}>{v >= 70 ? 'Conformant' : v >= 55 ? 'Partial' : 'Gap'}</span>
              </div>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="card">
            <div className="card-head"><div className="card-head-l"><h2>Recent activity</h2></div></div>
            <div className="card-body" style={{ paddingTop: 6 }}>
              <div className="feed-item"><div className="feed-ic ai"><Ico d={I.spark} sw={2.2}/></div><div><div className="feed-msg"><b>AI</b> drafted 4 closure actions for <b>Contractor mgmt</b> gaps</div><div className="feed-meta"><span className="tag ai">AI draft</span> 2h ago</div></div></div>
              <div className="feed-item"><div className="feed-ic ok"><Ico d={I.check} sw={2.4}/></div><div><div className="feed-msg">Delivery team validated <b>Tailings & dams</b> — 92%</div><div className="feed-meta">Yesterday · M. Chen</div></div></div>
              <div className="feed-item"><div className="feed-ic warn"><Ico d={I.file} sw={2}/></div><div><div className="feed-msg">Evidence requested · <b>Energy & climate</b></div><div className="feed-meta">2 days ago</div></div></div>
            </div>
          </div>
          <OSRail on={['Assess']} note={<>This site sees <b style={{color:'var(--ink2)'}}>Assess</b> only. Its results are ready to seed a continuous-improvement program. <a>Explore →</a></>}/>
        </div>
      </div>
    </Screen>
  );
}

/* ============================================================ GF6 — Gap assessment runtime */
function GF6_Runtime() {
  const rail = [
    ['Scope & applicability', 'done'], ['Leadership & accountability', 'done'],
    ['Risk & controls', 'on'], ['Contractor competency', ''], ['Monitoring & assurance', ''], ['Records & evidence', ''],
  ];
  const qs = [
    ['3.1', 'Are critical controls for contractor high-risk work documented and verified in the field?', 'partial', true,
      'Field verification records exist for 6 of 9 critical controls. No evidence for isolation, working-at-height, or confined-space verification in the last quarter.'],
    ['3.2', 'Is there a documented risk assessment process applied before contractor mobilisation?', 'yes', false, null],
    ['3.3', 'Are contractor risk assessments reviewed and signed off by a Gold Fields representative?', 'no', true,
      'Sign-off is informal. Suggested action: add a mandatory GF approval gate in the mobilisation workflow before site access is granted.'],
  ];
  return (
    <Screen summary={<AISum head="Contractor management is at 64% — 9 of 12 criteria answered, 3 gaps found." act="Add sign-off evidence for 3.3, then submit for review."/>} w={1440} h={992}
      sidebar={<Sidebar active="file" persona="client" locked={['model','target']}/>}
      topbar={<Topbar crumbs={['Gold Fields', 'St Ives', 'Contractor mgmt']} byline={<>Powered by <b>Method 8</b></>} search="Search…"/>}>
      <header className="pg-head">
        <div className="pg-head-l">
          <div className="eyebrow"><span>Gap assessment</span><span className="dot"/><span>Standard 3 of 11</span><span className="dot"/><span>Auto-saved</span></div>
          <h1>Contractor management</h1>
          <div className="sub">Method 8 prefilled this from St Ives and your evidence. <b>Confirm each answer or change it</b> — every gap gets a drafted closure action.</div>
        </div>
        <div className="pg-head-r">
          <span className="badge amber" style={{ height: 28 }}><span className="d"/> 64% · partial</span>
          <button className="btn btn-pri">Submit for validation</button>
        </div>
      </header>

      <div className="grid-2w">
        <div>
          <div className="card" style={{ marginBottom: 0 }}>
            <div className="card-head">
              <div className="card-head-l"><h2>Section 3 · Risk & controls</h2><div className="sub">AI prefilled · confirm or change</div></div>
              <div className="card-head-r"><span className="badge gray">9 / 12 criteria done</span></div>
            </div>
            <div className="card-body">
              {qs.map(([n, q, sel, flag, note]) => (
                <div key={n} className={`asmt-q ${flag ? 'flag' : ''}`}>
                  <div className="asmt-qtop"><span className="asmt-qn">{n}</span><span className="asmt-qt">{q}</span></div>
                  <div className="asmt-opts">
                    <span className={`opt ${sel === 'yes' ? 'sel yes' : ''}`}>Conformant</span>
                    <span className={`opt ${sel === 'partial' ? 'sel partial' : ''}`}>Partial</span>
                    <span className={`opt ${sel === 'no' ? 'sel 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>Sections</h2></div></div>
            <div className="card-body" style={{ padding: 10 }}>
              <div className="arail">
                {rail.map(([nm, st], i) => (
                  <div key={nm} className={`arail-item ${st}`}>
                    <span className="rn">{st === 'done' ? <Ico d={I.check} sw={3} style={{ width: 11, height: 11 }}/> : i + 1}</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: 8 }}>
                <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)' }}>3 gaps found so far. I'll draft closure actions and route them to the St Ives site owner when you submit. Two cite the same root cause — informal contractor sign-off.</div>
              <button className="btn btn-sec btn-sm" style={{ marginTop: 11, width: '100%' }}>Preview 3 draft actions</button>
            </div>
          </div>
        </div>
      </div>
    </Screen>
  );
}

/* ============================================================ GFC — Completer home (site owner) */
function GFC_Home() {
  const stds = [
    ['Safety', 100, 'done', 0], ['Critical risk', 80, 'prog', 2], ['Contractor mgmt', 45, 'prog', 3],
    ['Tailings & dams', 0, 'todo', 1], ['Emergency prep', 0, 'todo', 1], ['Environment', 60, 'prog', 0],
    ['Cyanide mgmt', 0, 'todo', 2],
  ];
  return (
    <Screen summary={<AISum head="8 of 30 assessments done. 9 safety-critical items still need evidence." act="Start Contractor management — 3 critical items are open."/>} w={1440} h={1133}
      sidebar={<Sidebar active="file" persona="client" locked={['grid','model','target','activity']}/>}
      topbar={<Topbar crumbs={['Gold Fields', 'St Ives', 'My assessments']} byline={<>Powered by <b>Method 8</b></>} search="Search my assessments…"/>}>
      <header className="pg-head">
        <div className="pg-head-l">
          <div className="eyebrow"><span>St Ives · you are the owner</span><span className="dot"/><span>Adetola Okafor</span><span className="dot"/><span>Due Mar 31</span></div>
          <h1>My assessments</h1>
          <div className="sub">11 standards assigned to your site. Work through each one — <b style={{ color: '#b42318' }}>red items are safety-critical</b> and need evidence before you can mark them conformant.</div>
        </div>
        <div className="pg-head-r">
          <button className="btn btn-sec"><Ico d={I.users} sw={2}/> Invite collaborator</button>
          <button className="btn btn-pri">Resume where I left off</button>
        </div>
      </header>

      <section className="stats">
        <StatCard hue="fuchsia" icon={I.file} trend="3 of 11" trendDir="up" label="Standards complete" value="27" unit="%" foot={<><b>8 / 30</b> assessments done</>}/>
        <StatCard hue="orange" icon={I.shield} trend="needs evidence" trendDir="flat" label="Safety-critical open" value="9" foot={<>across 5 standards</>}/>
        <StatCard hue="sky" icon={I.users} trend="" trendDir="flat" label="My collaborators" value="2" foot={<>Ops · Contracts</>}/>
        <StatCard hue="violet" icon={I.cal} trend="11 days" trendDir="dn" label="Due" value="Mar 31" foot={<>Wave 1</>}/>
      </section>

      <div className="grid-2">
        <div className="card">
          <div className="card-head"><div className="card-head-l"><h2>Your standards</h2><div className="sub">Pick up where you left off</div></div>
            <div className="card-head-r"><div className="pill-tabs"><button className="pill-tab active">All</button><button className="pill-tab">In progress</button><button className="pill-tab">Critical open</button></div></div>
          </div>
          <div className="card-body" style={{ paddingTop: 8 }}>
            {stds.map(([nm, pct, st, crit], i) => (
              <div key={nm} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '11px 0', borderBottom: i < stds.length - 1 ? '1px solid var(--line2)' : 'none' }}>
                <span style={{ width: 26, height: 26, borderRadius: 999, border: `1.5px solid ${st === 'done' ? '#17b26a' : st === 'prog' ? '#2e90fa' : 'var(--line3)'}`, background: st === 'done' ? '#17b26a' : '#fff', color: st === 'done' ? '#fff' : st === 'prog' ? '#2e90fa' : 'var(--ink4)', display: 'grid', placeItems: 'center', font: '600 11px/1 Inter', flex: 'none' }}>{st === 'done' ? <Ico d={I.check} sw={3} size={12}/> : i + 1}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ font: '600 14px/18px Inter' }}>{nm}</div>
                  <div style={{ font: '400 11.5px/15px Inter', color: 'var(--ink4)' }}>{st === 'done' ? 'Submitted for review' : st === 'todo' ? 'Not started' : `${pct}% complete`}</div>
                </div>
                {crit > 0 && <span className="crit"><span className="d"/> {crit} critical</span>}
                <div style={{ width: 90, height: 6, background: 'var(--wash2)', borderRadius: 3, overflow: 'hidden' }}><div style={{ width: `${pct}%`, height: '100%', background: st === 'done' ? '#17b26a' : '#2e90fa' }}/></div>
                <button className="btn btn-sec btn-sm">{st === 'done' ? 'View' : st === 'todo' ? 'Start' : 'Continue'}</button>
              </div>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="card"><div className="card-head"><div className="card-head-l"><h2>Needs your evidence</h2></div><span className="crit"><span className="d"/> 9</span></div>
            <div className="card-body" style={{ paddingTop: 6 }}>
              {[['Isolation & permit-to-work', 'Critical risk'], ['Critical controls verified', 'Contractor mgmt'], ['Cyanide handling sign-off', 'Cyanide mgmt']].map(([t, s], i) => (
                <div key={i} className="feed-item critrow" style={{ border: 'none', borderBottom: i < 2 ? '1px solid var(--line2)' : 'none', borderRadius: 0 }}><div className="feed-ic warn"><Ico d={I.shield} sw={2}/></div><div style={{ flex: 1 }}><div className="feed-msg"><b>{t}</b></div><div className="feed-meta">{s}</div></div><button className="btn btn-sec btn-sm">Upload</button></div>
              ))}
            </div>
          </div>
          <div className="card"><div className="card-head"><div className="card-head-l"><h2>Your guides</h2><div className="sub">Surfaced for your open items</div></div></div>
            <div className="card-body" style={{ paddingTop: 10 }}>
              {[['Safety-critical controls explained', 'video · 5 min', '#fef3f2', '#d92d20', I.activity], ['Evidence upload guide', 'PDF', '#f4f3ff', '#6938ef', I.doc]].map(([t, m, bg, fg, ic], i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 0', borderBottom: i < 1 ? '1px solid var(--line2)' : 'none' }}><div className="guide-ic" style={{ width: 32, height: 32, background: bg, color: fg }}><Ico d={ic} sw={2}/></div><div style={{ flex: 1 }}><div style={{ font: '600 13px/16px Inter' }}>{t}</div><div style={{ font: '400 11px/14px Inter', color: 'var(--ink4)' }}>{m}</div></div></div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Screen>
  );
}

/* ============================================================ GLI — Client lead: submit & discuss */
function GLI_Intake() {
  const fileChip = (ic, nm, dark) => (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 9px', borderRadius: 7, marginTop: 8, font: '500 11px/1 Inter', background: dark ? 'rgba(255,255,255,.16)' : 'var(--wash)', border: dark ? 'none' : '1px solid var(--line)', color: dark ? '#fff' : 'var(--ink2)' }}><Ico d={ic} sw={2} size={13} style={{ color: dark ? '#fff' : '#1570ef' }}/> {nm}</span>
  );
  return (
    <Screen summary={<AISum head="7 threads open and 4 items need you. Tarkwa's contractor data is in — one gap left." act="Upload the sign-off workflow doc for Tarkwa 3.3."/>} w={1440} h={1036}
      sidebar={<Sidebar active="activity" persona="client" locked={['model','target']}/>}
      topbar={<Topbar crumbs={['Gold Fields', 'Group HSE', 'Submit & discuss']} byline={<>Powered by <b>Method 8</b></>} search="Search threads…"/>}>
      <header className="pg-head">
        <div className="pg-head-l">
          <div className="eyebrow"><span>Group HSE · client lead</span><span className="dot"/><span>Priya Iyer</span><span className="dot"/><span className="live">Delivery team online</span></div>
          <h1>Submit &amp; discuss</h1>
          <div className="sub">Drop raw data and leave comments here instead of email. Everything threads against the right standard and site — and the delivery team sees it live.</div>
        </div>
        <div className="pg-head-r"><button className="btn btn-pri"><Ico d={I.plus} sw={2}/> New thread</button></div>
      </header>

      <div className="grid-2">
        <div className="card" style={{ display: 'flex', flexDirection: 'column' }}>
          <div className="card-head"><div className="card-head-l"><h2>Contractor mgmt · Tarkwa</h2><div className="sub">Thread · 4 messages · 2 files</div></div><span className="badge amber"><span className="d"/> 1 gap open</span></div>
          <div className="card-body" style={{ paddingTop: 14 }}>
            <div className="chat">
              <div className="chat-msg me"><div className="chat-bub">Here's our updated contractor register for Tarkwa — should cover criteria 3.1–3.4.{fileChip(I.file, 'Tarkwa-contractors.xlsx', true)}</div></div>
              <div className="chat-msg"><span className="chat-av"><img src="assets/avatars/av-sarah.svg" alt=""/></span><div className="chat-bub"><b>Kath (Method 8)</b> · mapped it to 3.1, 3.2 and 3.4. Criterion 3.3 (Gold Fields sign-off) still needs your approval-workflow doc.</div></div>
              <div className="chat-msg"><span className="chat-av ai"><Ico d={I.spark} sw={2.2} size={15}/></span><div className="chat-bub">I prefilled Tarkwa · Contractor mgmt from this register — <b>3 of 4</b> criteria now conformant. One gap remains.</div></div>
              <div className="chat-msg me"><div className="chat-bub">Sign-off workflow attached — this is the current process.{fileChip(I.doc, 'GF-contractor-signoff.pdf', true)}</div></div>
            </div>
            <div className="chat-input"><Ico d={I.plus} sw={2} size={16}/> Add a comment or drop a file…</div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="card"><div className="card-head"><div className="card-head-l"><h2>Open with you</h2></div><span className="badge amber">4</span></div>
            <div className="card-body" style={{ paddingTop: 6 }}>
              {[['Evidence requested', 'Energy & climate · St Ives', 'warn'], ['Sign-off doc needed', 'Contractor · Tarkwa', 'warn'], ['Approve findings', 'Tailings · Damang', 'ok'], ['New data request', 'Cyanide · Salares Norte', 'warn']].map(([t, s, ic], i) => (
                <div key={i} className="feed-item" style={{ borderBottom: i < 3 ? '1px solid var(--line2)' : 'none' }}><div className={`feed-ic ${ic}`}><Ico d={ic === 'ok' ? I.check : I.file} sw={2.2}/></div><div style={{ flex: 1 }}><div className="feed-msg"><b>{t}</b></div><div className="feed-meta">{s}</div></div><Ico d={I.arrowR} sw={2} size={14} style={{ color: 'var(--ink4)' }}/></div>
              ))}
            </div>
          </div>
          <div className="card"><div className="card-head"><div className="card-head-l"><h2>Progress snapshot</h2></div><span className="card-link">Full board <Ico d={I.arrowR} sw={2} size={12}/></span></div>
            <div className="card-body" style={{ paddingTop: 12 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                {[['Completion', '71%'], ['Conformance', '68%'], ['Standards live', '5 / 11'], ['Threads open', '7']].map(([l, v]) => (
                  <div key={l} style={{ padding: '10px 12px', border: '1px solid var(--line)', borderRadius: 10 }}><div style={{ font: '600 22px/26px Inter' }}>{v}</div><div style={{ font: '400 12px/16px Inter', color: 'var(--ink4)' }}>{l}</div></div>
                ))}
              </div>
              <div style={{ marginTop: 12, font: '400 12px/17px Inter', color: 'var(--ink4)' }}>No emails — raw data and decisions all live here, threaded to the work.</div>
            </div>
          </div>
        </div>
      </div>
    </Screen>
  );
}

/* ============================================================ CLC — Client lead command center (consolidated) */
function CLC_Command() {
  const low = [['Cyanide mgmt', 'Salares Norte', 39], ['Tailings & dams', 'Asanko', 44], ['Contractor mgmt', 'Windfall', 41]];
  return (
    <Screen w={1440} h={1500}
      sidebar={<Sidebar active="grid" persona="client" locked={['model','target']}/>}
      topbar={<Topbar crumbs={['Gold Fields', 'Group HSE']} byline={<>Powered by <b>Method 8</b></>} search="Search across 15 sites…"/>}
      summary={<AISum head="Conformance 68% (+6 QoQ), 71% complete. Americas is the drag — Salares Norte & Windfall below 50%. 4 things need you; Tarkwa data just landed." act="Approve 2 findings, then open the Americas."/>}>
      <header className="pg-head">
        <div className="pg-head-l">
          <div className="eyebrow"><span>Group HSE · client lead</span><span className="dot"/><span>Priya Iyer</span><span className="dot"/><span className="live">Live — synced 8 min ago</span></div>
          <h1>Command center</h1>
          <div className="sub">Everything in one place — where the program stands, what needs you, and a line to the delivery team. The AI keeps it current so you don't chase it.</div>
        </div>
        <div className="pg-head-r"><button className="btn btn-ai"><Ico d={I.spark} sw={2}/> Ask Method 8</button><button className="btn btn-sec"><Ico d={I.ext} sw={2}/> Board pack</button></div>
      </header>

      <section className="stats">
        <StatCard hue="violet" icon={I.shield} trend="+6 pts" trendDir="up" label="Group conformance" value="68" unit="%" foot={<>3 sites below 50%</>}/>
        <StatCard hue="fuchsia" icon={I.file} trend="71%" trendDir="up" label="Assessments complete" value="117" unit="/ 165"/>
        <StatCard hue="orange" icon={I.target} trend="4 need you" trendDir="flat" label="Open with you" value="4" foot={<>2 approvals · 2 data</>}/>
        <StatCard hue="sky" icon={I.map} trend="" trendDir="flat" label="Sites at risk" value="3" foot={<>Americas region</>}/>
      </section>

      <div className="grid-2">
        <div className="card">
          <div className="card-head"><div className="card-head-l"><h2>Portfolio</h2><div className="sub">15 sites · 11 standards</div></div>
            <div className="card-head-r"><div className="pill-tabs"><button className="pill-tab active">Regions</button><button className="pill-tab">Map</button><button className="pill-tab">Matrix</button></div></div>
          </div>
          <div className="card-body">
            <div className="regions">
              {GF_REGIONS.map(r => {
                const avg = Math.round(r.sites.reduce((a, [, p]) => a + p, 0) / r.sites.length);
                return (
                  <div key={r.name} className="region">
                    <div className="region-h"><span>{r.name}</span><span className="badge gray">{avg}%</span></div>
                    {r.sites.map(([nm, p]) => (
                      <div key={nm} className="site-chip"><Gauge value={p} size={32} sw={4}/><span className="nm">{nm}</span><span className="pct" style={{ color: p >= 70 ? '#067647' : p >= 50 ? '#b54708' : '#b42318' }}>{p}%</span></div>
                    ))}
                  </div>
                );
              })}
            </div>
            <div style={{ marginTop: 14, padding: '10px 12px', background: '#fffbfa', border: '1px solid #fecdca', borderRadius: 10, font: '400 12.5px/18px Inter', color: 'var(--ink3)' }}>
              <b style={{ color: '#b42318' }}>AI flag:</b> Americas conformance fell 3 pts this fortnight — Cyanide & Tailings gaps at Salares Norte are the cause.
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="card"><div className="card-head"><div className="card-head-l"><h2>Needs you</h2></div><span className="badge amber">4</span></div>
            <div className="card-body" style={{ paddingTop: 6 }}>
              {[['Approve findings', 'Tailings · Damang', 'ok', 'Approve'], ['Approve findings', 'Safety · South Deep', 'ok', 'Approve'], ['Upload sign-off doc', 'Contractor · Tarkwa', 'warn', 'Upload'], ['Provide data', 'Cyanide · Salares Norte', 'warn', 'Submit']].map(([t, s, ic, cta], i) => (
                <div key={i} className="feed-item" style={{ borderBottom: i < 3 ? '1px solid var(--line2)' : 'none' }}><div className={`feed-ic ${ic}`}><Ico d={ic === 'ok' ? I.check : I.file} sw={2.2}/></div><div style={{ flex: 1 }}><div className="feed-msg"><b>{t}</b></div><div className="feed-meta">{s}</div></div><button className="btn btn-sec btn-sm">{cta}</button></div>
              ))}
            </div>
          </div>
          <div className="card"><div className="card-head"><div className="card-head-l"><h2>Submit data &amp; discuss</h2><div className="sub">No email — it threads to the work</div></div></div>
            <div className="card-body" style={{ paddingTop: 10 }}>
              <div style={{ font: '400 12.5px/18px Inter', color: 'var(--ink3)', marginBottom: 8 }}>Latest: <b style={{ color: 'var(--ink2)' }}>Kath</b> mapped your Tarkwa contractor register — 1 gap left (GF sign-off).</div>
              <div className="chat-input"><Ico d={I.plus} sw={2} size={16}/> Drop a file or leave a comment…</div>
            </div>
          </div>
          <div className="card"><div className="card-head"><div className="card-head-l"><h2>Lowest conformance</h2></div></div>
            <div className="card-body" style={{ paddingTop: 6 }}>
              {low.map(([std, site, v], i) => (
                <div key={i} className="feed-item" style={{ gridTemplateColumns: '1fr auto', alignItems: 'center', borderBottom: i < 2 ? '1px solid var(--line2)' : 'none' }}><div><div className="feed-msg"><b>{std}</b></div><div className="feed-meta">{site}</div></div><span className="badge red"><span className="d"/> {v}%</span></div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Screen>
  );
}

window.GF = {
  title: 'Gold Fields',
  subtitle: 'Multi-site gap-assessment rollout · 15 locations × 11 standards (wide & shallow)',
  screens: [
    { id: 'gf1', label: 'Admin · program builder', w: 1440, h: 1108, render: () => <GF1_Builder/> },
    { id: 'clc', label: 'Client lead · command center', w: 1440, h: 1500, render: () => <CLC_Command/> },
    { id: 'gf2', label: 'Client · control tower (region grid)', w: 1440, h: 1076, render: () => <GF2_GridTower/> },
    { id: 'gf3', label: 'Client · control tower (geo map)', w: 1440, h: 1128, render: () => <GF3_MapTower/> },
    { id: 'gf4', label: 'Client · conformance matrix', w: 1440, h: 968, render: () => <GF4_Matrix/> },
    { id: 'gf5', label: 'Client · site drill-in (St Ives)', w: 1440, h: 1278, render: () => <GF5_Site/> },
    { id: 'gli', label: 'Client lead · submit & discuss', w: 1440, h: 1036, render: () => <GLI_Intake/> },
    { id: 'gfc', label: 'Completer · my assessments (home)', w: 1440, h: 1133, render: () => <GFC_Home/> },
    { id: 'gf6', label: 'Completer · gap assessment runtime', w: 1440, h: 992, render: () => <GF6_Runtime/> },
  ],
};
