// Method 8 — demo · Culture survey: compose → send → results.
// "Send" is the live moment: dispatch animation, then responses stream into
// an animated results view (dimension scores, site heatmap, AI insight).

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

function useCountUp(target, run, dur = 1500) {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    if (!run) { setN(0); return; }
    const steps = 30, stepDur = dur / steps;
    let i = 0;
    const id = setInterval(() => {
      i++;
      const p = i / steps;
      setN(Math.round(target * (1 - Math.pow(1 - p, 3))));
      if (i >= steps) { setN(target); clearInterval(id); }
    }, stepDur);
    return () => clearInterval(id);
  }, [target, run, dur]);
  return n;
}

const SV_QS = [
  'I can stop a job if I believe it is unsafe, without fear of blame.',
  'When I report a hazard or near-miss, something is done about it.',
  'My supervisor talks about safety as much as production.',
  'I have the time and resources to do my work safely.',
  'People here look out for each other\'s safety.',
];
const SV_CHANNELS = [
  ['phone', '#ecfdf3', '#067647', 'SMS link', '1,240 mobiles · anonymous one-tap'],
  ['qr', '#eff8ff', '#175cd3', 'QR posters', 'Crib rooms & muster points · 15 sites'],
  ['mail', '#f4f3ff', '#5925dc', 'Email', 'Salaried & supervisory staff'],
];
const SV_DIMS = [
  ['Reporting culture', 'When I speak up, it matters', 74, '#17b26a'],
  ['Psychological safety', 'Safe to raise concerns', 68, '#66c61c'],
  ['Leadership visibility', 'Leaders walk the talk', 63, '#fdb022'],
  ['Stop-work confidence', 'I can stop an unsafe job', 59, '#f79009'],
  ['Fatigue & workload', 'Time & resource to be safe', 55, '#f04438'],
];
const SV_SITES = ['St Ives', 'Agnew', 'Gruyere', 'Tarkwa', 'Damang', 'South Deep'];
const heatTone = (v) => v >= 75 ? 'g3' : v >= 65 ? 'g2' : v >= 55 ? 'y2' : v >= 45 ? 'y1' : 'r1';
const heatVal = (si, di) => { const base = SV_DIMS[di][2]; const v = Math.round(base + Math.sin((si + 1) * (di + 3) * 1.3) * 13); return Math.max(38, Math.min(92, v)); };

const VERBATIM = [
  ['Supervisors back us when we call a stop now — big change this year.', 'St Ives · day shift', 'pos'],
  ['I can raise a concern, but I\'m not always sure it actually goes anywhere.', 'Tarkwa · processing', 'neu'],
  ['Night shift is stretched too thin to do the checks properly.', 'Damang · night shift', 'neg'],
];

function SurveyView() {
  const [step, setStep] = React.useState('setup');   // setup | sending | results
  const [prog, setProg] = React.useState(0);
  const sendTimer = React.useRef(null);

  const RECIPIENTS = 1240;
  const sentCount = useCountUp(RECIPIENTS, step === 'sending');
  const respCount = useCountUp(758, step === 'results', 1800);  // 61% of 1240
  const overall = useCountUp(64, step === 'results', 1600);
  const [mounted, setMounted] = React.useState(false);

  React.useEffect(() => () => clearInterval(sendTimer.current), []);

  const send = () => {
    setStep('sending'); setProg(0);
    clearInterval(sendTimer.current);
    let p = 0;
    sendTimer.current = setInterval(() => {
      p += 0.04; setProg(Math.min(1, p));
      if (p >= 1) { clearInterval(sendTimer.current); setTimeout(() => { setStep('results'); setTimeout(() => setMounted(true), 80); }, 500); }
    }, 70);
  };
  const restart = () => { setStep('setup'); setMounted(false); setProg(0); };

  const r = 38, c = 2 * Math.PI * r;

  // measured track width for the dimension bars (pixel-sized, see workshop)
  const dimRef = React.useRef(null);
  const [dtw, setDtw] = React.useState(0);
  React.useLayoutEffect(() => {
    const el = dimRef.current; if (!el) return;
    const ro = new ResizeObserver(() => setDtw(el.clientWidth));
    ro.observe(el); setDtw(el.clientWidth);
    return () => ro.disconnect();
  }, [step]);

  return (
    <>
      {step === 'results'
        ? <AISum head={<>Overall culture index <b>64/100</b> (+5 vs last pulse) from <b>61%</b> response. <b>Stop-work confidence</b> (59) and <b>fatigue</b> (55) are the soft spots — concentrated on night shift at St&nbsp;Ives and Damang. Reporting culture is your strength.</>} act="Drill into night-shift fatigue, then route a finding to the improvement plan."/>
        : <AISum head={<>A safety-culture pulse to <b>1,240 frontline workers</b> across 15 sites — anonymous, one-tap, 5 questions. Method 8 will theme the free-text and map results to your standards automatically.</>} act={step === 'setup' ? 'Review the 5 statements and channels, then send.' : 'Dispatching…'}/>}

      <PageHead
        eyebrow={<><span>Sense · culture survey</span><span className="dot"/><span>Safety Culture Pulse · Q2</span><span className="dot"/>{step === 'results' ? <span className="live">Collecting — synced live</span> : <span>Draft</span>}</>}
        title="Safety Culture Pulse"
        sub={<>Frontline perception across all 15 sites. The hard gap assessment tells you the <b>system</b> is in place; this tells you whether people <b>feel</b> it on the floor.</>}
        actions={<>
          <div className="sv-steps">
            {[['setup', 'Compose'], ['sending', 'Send'], ['results', 'Results']].map(([k, lab], i) => {
              const order = ['setup', 'sending', 'results'];
              const cur = order.indexOf(step), me = order.indexOf(k);
              return <button key={k} className={`sv-step ${step === k ? 'active' : ''} ${me < cur ? 'done' : ''}`}><span className="sx">{me < cur ? <Ico d={I.check} sw={3} size={10}/> : i + 1}</span>{lab}</button>;
            })}
          </div>
        </>}/>

      {step === 'setup' && (
        <div className="grid-2">
          <div className="card">
            <div className="card-head"><div className="card-head-l"><h2>The 5 statements</h2><div className="sub">Rated 1–5 · agree ↔ disagree · ~90 seconds</div></div><span className="badge violet"><Ico d={I.spark} sw={2} size={12}/> AI-tuned</span></div>
            <div className="card-body" style={{ paddingTop: 14 }}>
              {SV_QS.map((q, i) => (
                <div key={i} className="q-likert">
                  <div className="qt">{i + 1}. {q}</div>
                  <div className="likert-row">{['Disagree', '', '', '', 'Agree'].map((l, j) => <div key={j} className="likert-dot">{l ? l : '•'}</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>Audience</h2></div></div>
              <div className="card-body" style={{ paddingTop: 12, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                <div className="aud-chip"><div><div className="ac-n">1,240</div><div className="ac-l">frontline workers</div></div></div>
                <div className="aud-chip"><div><div className="ac-n">15</div><div className="ac-l">operating sites</div></div></div>
                <div className="aud-chip"><div><div className="ac-n">100%</div><div className="ac-l">anonymous</div></div></div>
              </div>
            </div>
            <div className="card">
              <div className="card-head"><div className="card-head-l"><h2>How it reaches them</h2></div></div>
              <div className="card-body" style={{ paddingTop: 12 }}>
                {SV_CHANNELS.map(([ic, bg, fg, n, d]) => (
                  <div key={n} className="chan"><div className="ci" style={{ background: bg, color: fg }}><Ico d={I[ic]} sw={2}/></div><div><div className="cn">{n}</div><div className="cd">{d}</div></div></div>
                ))}
                <button className="btn btn-pri" style={{ width: '100%', height: 42, marginTop: 6, fontSize: 14 }} onClick={send}><Ico d={I.send} sw={2}/> Send to 1,240 workers</button>
              </div>
            </div>
          </div>
        </div>
      )}

      {step === 'sending' && (
        <div className="card"><div className="card-body sending">
          <div className="send-ring">
            <svg viewBox="0 0 84 84"><circle className="rt" cx="42" cy="42" r={r}/><circle className="ra" cx="42" cy="42" r={r} strokeDasharray={c} strokeDashoffset={c * (1 - prog)}/></svg>
            <div className="sc"><Ico d={I.send} sw={2}/></div>
          </div>
          <div className="send-count">{sentCount.toLocaleString()}</div>
          <div className="send-stat">Dispatching the pulse…</div>
          <div className="send-sub">SMS links sent · QR posters live at 15 sites · responses are anonymous</div>
        </div></div>
      )}

      {step === 'results' && (
        <>
          <section className="stats" style={{ marginBottom: 20 }}>
            <div className="stat"><div className="stat-top"><div className="stat-icon teal"><Ico d={I.activity}/></div><span className="stat-trend up"><Ico d={I.up} sw={2.4}/> +5</span></div><div className="stat-lbl">Culture index</div><div className="stat-val">{overall}<small>/100</small></div><div className="stat-foot"><b>Above</b> industry median</div></div>
            <div className="stat"><div className="stat-top"><div className="stat-icon sky"><Ico d={I.users}/></div><span className="resp-live"><span className="pulse-dot"/></span></div><div className="stat-lbl">Responses</div><div className="stat-val">{respCount.toLocaleString()}</div><div className="stat-foot"><b>61%</b> response · climbing</div></div>
            <div className="stat"><div className="stat-top"><div className="stat-icon orange"><Ico d={I.shield}/></div></div><div className="stat-lbl">Lowest dimension</div><div className="stat-val">55</div><div className="stat-foot">Fatigue &amp; workload</div></div>
            <div className="stat"><div className="stat-top"><div className="stat-icon violet"><Ico d={I.map}/></div></div><div className="stat-lbl">Sites at risk</div><div className="stat-val">2</div><div className="stat-foot">St Ives &amp; Damang · night shift</div></div>
          </section>

          <div className="grid-2">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div className="card">
                <div className="card-head"><div className="card-head-l"><h2>Culture dimensions</h2><div className="sub">Index 0–100 · weakest at the bottom</div></div></div>
                <div className="card-body" style={{ paddingTop: 10 }}>
                  {SV_DIMS.map(([n, sub, v, col], di) => (
                    <div key={n} className="dim-row">
                      <div className="dn">{n}<small>{sub}</small></div>
                      <div className="dim-track" ref={di === 0 ? dimRef : null}><div className="dim-seg" style={{ width: mounted ? v / 100 * dtw : 0, background: col }}/></div>
                      <div className="dv" style={{ color: col }}>{v}</div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="card">
                <div className="card-head"><div className="card-head-l"><h2>By site &amp; dimension</h2><div className="sub">Where culture and conformance diverge</div></div></div>
                <div className="card-body" style={{ padding: '14px 18px' }}>
                  <table className="matrix">
                    <thead><tr><th className="rowh"> </th>{SV_DIMS.map(([n]) => <th key={n} title={n}>{n.split(' ')[0].slice(0, 4)}</th>)}</tr></thead>
                    <tbody>
                      {SV_SITES.map((s, si) => (
                        <tr key={s}><td className="rowh">{s}</td>{SV_DIMS.map((_, di) => { const v = heatVal(si, di); return <td key={di}><div className={`cell ${heatTone(v)}`}>{v}</div></td>; })}</tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div className="card">
                <div className="card-head"><div className="card-head-l"><h2>What people said</h2><div className="sub">Free-text, themed by AI</div></div><span className="badge violet"><Ico d={I.spark} sw={2} size={12}/> 412 comments</span></div>
                <div className="card-body" style={{ paddingTop: 12 }}>
                  {VERBATIM.map(([t, m, s], i) => (
                    <div key={i} className="verbatim"><div className="vt">“{t}”</div><div className="vm"><span className={`sent-tag ${s}`}>{s === 'pos' ? 'Positive' : s === 'neg' ? 'Negative' : 'Mixed'}</span>{m}</div></div>
                  ))}
                  <div style={{ font: '400 12px/17px Inter', color: 'var(--ink4)', marginTop: 4 }}>Top themes: <b style={{ color: 'var(--ink2)' }}>night-shift fatigue</b>, <b style={{ color: 'var(--ink2)' }}>stop-work follow-through</b>, <b style={{ color: 'var(--ink2)' }}>supervisor visibility</b>.</div>
                </div>
              </div>
              <div className="card">
                <div className="card-body" style={{ padding: 16 }}>
                  <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' }}>What Method 8 recommends</div></div>
                  <div style={{ font: '400 12.5px/18px Inter', color: 'var(--ink3)' }}>Perception (59) lags the conformance score on stop-work — the system exists but isn't felt. This mirrors today's <b>field-verification</b> workshop result. I've drafted a finding linking both for the St Ives improvement plan.</div>
                  <button className="btn btn-sec btn-sm" style={{ marginTop: 12, width: '100%' }} onClick={restart}>Run another pulse</button>
                </div>
              </div>
            </div>
          </div>
        </>
      )}
    </>
  );
}

Object.assign(window, { SurveyView });
