/* global React */
// MomOps Framework: interactive insight layers. One per chapter where it aids the argument.

function InsightPanel({ label, hint, children }) {
  return (
    <div className="fw-insight">
      <div className="fw-insight-bar">
        <span className="dot"></span>
        <b>Interactive</b>
        <small>{label}</small>
      </div>
      <div className="fw-insight-body">
        {hint ? <p className="iv-hint">{hint}</p> : null}
        {children}
      </div>
    </div>
  );
}

/* 1. Executive Summary: what orgs see vs what sustains them */
const DASH = [
  { k: 'Productivity', v: '94%', care: 'Calendar repair when childcare falls through' },
  { k: 'Output', v: '+12%', care: 'Emotional labour absorbing team conflict' },
  { k: 'Engagement', v: '71', care: 'Memory work: who needs what, and when' },
  { k: 'AI adoption', v: '88%', care: 'Crisis response at 2am, off the clock' },
  { k: 'Efficiency', v: '+17%', care: 'Invisible coordination across families' },
];
function InsightDashboard() {
  const [show, setShow] = React.useState(false);
  return (
    <InsightPanel label="The measurement paradox" hint="Organisations instrument what a server reports about itself. The work that actually sustains output stays unmeasured. Reveal the layer underneath.">
      <div className="iv-layer-label">What organisations see</div>
      <div className="iv-metric-grid">
        {DASH.map((m) => (
          <div className="iv-metric" key={m.k}><div className="v">{m.v}</div><div className="k">{m.k}</div></div>
        ))}
      </div>
      <div className="iv-care-wrap" style={show ? null : null} {...(show ? { className: 'iv-care-wrap show' } : { className: 'iv-care-wrap' })}>
        <div className="iv-care-inner">
          <div className="iv-connector"><i data-lucide="corner-left-down"></i></div>
          <div className="iv-layer-label">What actually sustains it</div>
          <div className="iv-care-grid">
            {DASH.map((m) => (<div className="iv-care" key={m.k}><div className="k">{m.care}</div></div>))}
          </div>
        </div>
      </div>
      <div style={{ marginTop: 20 }}>
        <button className="fw-btn fw-btn--solid" aria-pressed={show} onClick={() => setShow(!show)}>
          <i className="ic" data-lucide={show ? 'eye-off' : 'eye'}></i>
          {show ? 'Hide the invisible layer' : 'Reveal what sustains it'}
        </button>
      </div>
    </InsightPanel>
  );
}

/* 2. Who this serves: scale / Dunbar slider */
const GREEN = [
  'Mission-driven, under 500 people',
  'Collective success orientation',
  'Leadership willing to share power',
  'Engagement above 50%, 18-24 month runway',
];
const RED = [
  'Pure profit maximisation, shareholder-only metrics',
  'Zero-sum individual competition',
  'Bureaucratic hierarchies over 500 people',
  "Leadership unwilling to examine 'ideal worker' assumptions",
];
function InsightFit() {
  const [n, setN] = React.useState(120);
  let verdict, vColor, vBg, line;
  if (n <= 150) { verdict = 'In scope'; vColor = 'var(--momops-cream-text)'; vBg = 'var(--momops-teal-deep)'; line = "Within Dunbar's number. People can know each other personally, which is what care consciousness requires."; }
  else if (n <= 500) { verdict = 'Bounded'; vColor = 'var(--momops-ink-deep)'; vBg = 'var(--momops-gold)'; line = 'Workable, but relationships now need deliberate structure. Care consciousness must be designed, not assumed.'; }
  else { verdict = 'Out of scope'; vColor = 'var(--momops-cream-text)'; vBg = 'var(--momops-coral)'; line = 'Beyond 500 people, MomOps does not apply. Organisations this size require fundamentally different approaches the framework does not address.'; }
  const pct = Math.min(100, (n / 600) * 100);
  return (
    <InsightPanel label="The scale reality" hint="The 500-person limit is not a bug, it is a feature. Drag to test your organisation against the boundary.">
      <div className="iv-scale">
        <div className="iv-scale-head">
          <span className="count">{n}{n >= 600 ? '+' : ''} <span style={{ fontSize: '0.8rem', fontFamily: 'var(--font-body)', fontWeight: 700, color: 'var(--momops-ink-soft)' }}>people</span></span>
          <span className="verdict" style={{ color: vColor, background: vBg }}>{verdict}</span>
        </div>
        <input type="range" min="10" max="600" step="10" value={n} onChange={(e) => setN(+e.target.value)} />
        <div className="iv-scale-track"><div className="iv-scale-fill" style={{ width: pct + '%', background: vBg }}></div></div>
        <div className="iv-scale-marks"><span>10</span><span>150 · relationships possible</span><span>500 · ceiling</span></div>
        <p className="iv-verdict-line">{line}</p>
      </div>
      <div className="iv-fitcols">
        <div className="iv-fitcol green"><h5><span className="pip"></span>Green light</h5><ul>{GREEN.map((x, i) => <li key={i}>{x}</li>)}</ul></div>
        <div className="iv-fitcol red"><h5><span className="pip"></span>Red light</h5><ul>{RED.map((x, i) => <li key={i}>{x}</li>)}</ul></div>
      </div>
    </InsightPanel>
  );
}

/* 3. Why now: automation removes repeatable, relational remains */
const TASKS = [
  { name: 'Data entry & reconciliation', rep: true },
  { name: 'Report generation', rep: true },
  { name: 'Routing & ticket triage', rep: true },
  { name: 'Scheduling logistics', rep: true },
  { name: 'Mentoring a struggling colleague', rep: false },
  { name: 'Absorbing conflict on a tense team', rep: false },
  { name: 'Judgement under ambiguity', rep: false },
  { name: 'Coordinating care when systems fail', rep: false },
];
function InsightAutomation() {
  const [run, setRun] = React.useState(false);
  const removed = TASKS.filter((t) => t.rep).length;
  const remain = TASKS.length - removed;
  return (
    <InsightPanel label="The post-automation paradox" hint="Automation removes repeatable tasks. What remains is relational work: judgement, emotional intelligence, coordination and care. Most organisations have no method to value it.">
      <div className="iv-tasklist">
        {TASKS.map((t, i) => (
          <div key={i} className={'iv-task' + (run && t.rep ? ' removed' : '') + (run && !t.rep ? ' remain' : '')}>
            <span className="tag">{t.rep ? 'Repeatable' : 'Relational'}</span>
            <span className="name">{t.name}</span>
          </div>
        ))}
      </div>
      <div className="iv-auto-readout">
        <div><div className="stat">{run ? removed : 0}</div><div className="lbl">Tasks automated away</div></div>
        <div><div className="stat remain">{run ? remain : TASKS.length}</div><div className="lbl">Work that remains human</div></div>
      </div>
      <div style={{ marginTop: 18, display: 'flex', gap: 10 }}>
        <button className="fw-btn fw-btn--solid" onClick={() => setRun(true)} disabled={run}><i className="ic" data-lucide="cpu"></i>Run automation</button>
        {run ? <button className="fw-btn" onClick={() => setRun(false)}><i className="ic" data-lucide="rotate-ccw"></i>Reset</button> : null}
      </div>
    </InsightPanel>
  );
}

/* 4. Maternal intelligence as technical architecture */
const CAPS = [
  { name: 'Resource allocation', ent: 'Optimises budgets across systems in real time', mat: 'Manages time, money, attention and emotional bandwidth across competing stakeholders' },
  { name: 'Load balancing', ent: 'Redistributes traffic when a node fails', mat: 'Redistributes responsibilities the instant someone gets sick, finding backup on the fly' },
  { name: 'Monitoring & alerting', ent: 'Tracks CPU, latency, error rates', mat: 'Tracks sleep, mood, milestones and grades, held in memory with instant recall' },
  { name: 'Incident response', ent: '24/7 on-call for outages', mat: 'Middle-of-the-night emergencies and cascading failures when childcare collapses' },
];
function InsightArchitecture() {
  const [sel, setSel] = React.useState(0);
  return (
    <InsightPanel label="The enterprise software analogy" hint="Build software that did this and it would be worth millions. When mothers do the exact work, it is invisible and unpaid. Select a capability to compare.">
      <div className="iv-arch">
        <div className="iv-arch-col ent">
          <h5>Enterprise software</h5>
          {CAPS.map((c, i) => (
            <div key={i} className={'iv-arch-row' + (sel === i ? ' on' : '')} onClick={() => setSel(i)}>
              <div className="cap-name">{c.name}</div>
              {sel === i ? <div className="cap-desc">{c.ent}</div> : null}
            </div>
          ))}
        </div>
        <div className="iv-arch-col mat">
          <h5>Maternal systems intelligence</h5>
          {CAPS.map((c, i) => (
            <div key={i} className={'iv-arch-row' + (sel === i ? ' on' : '')} onClick={() => setSel(i)}>
              <div className="cap-name">{c.name}</div>
              {sel === i ? <div className="cap-desc">{c.mat}</div> : null}
            </div>
          ))}
        </div>
      </div>
      <div className="iv-arch-worth">
        <span className="ent">Valued at: millions</span>
        <span className="mat">Valued at: "she's just staying home"</span>
      </div>
    </InsightPanel>
  );
}

/* 5. The three pillars map */
const PILLARS = [
  { n: 'Pillar 1', t: 'Care Work Visibility', blurb: 'Make the invisible infrastructure visible through documentation and recognition.',
    groups: [['Assessment methodology', ['Comprehensive care work audits', 'Ethnographic observation & interviews', 'Systems analysis of enabling work']],
             ['Documentation systems', ['Job descriptions naming care', 'Evaluation criteria that count it', 'Resource allocation that accounts for it']]] },
  { n: 'Pillar 2', t: 'Intersectional Analysis', blurb: 'Ensure care consciousness addresses interconnected systems of oppression.',
    groups: [['Identity mapping', ['Distribution across race, gender, class, age, ability', 'Assignment, recognition, compensation patterns', "Naming 'privileged irresponsibility'"]],
             ['Alliance building', ["Women's, racial justice & LGBTQ+ partnerships", 'Cross-identity collaboration', 'Integration with existing justice work']]] },
  { n: 'Pillar 3', t: 'Participatory Design', blurb: 'Turn employees from passive recipients into active co-creators of culture.',
    groups: [['Co-research methodology', ['Employees trained as co-researchers', 'Shared data collection & analysis', 'Genuine decision-making power']],
             ['Democratic decision-making', ['Representation in care policy', 'Shared power over distribution', 'Continuous feedback systems']]] },
];
function InsightPillars() {
  const [sel, setSel] = React.useState(0);
  const p = PILLARS[sel];
  return (
    <InsightPanel label="Systematic transformation" hint="Three pillars working together. Select one to see its methods.">
      <div className="iv-pillars">
        {PILLARS.map((pl, i) => (
          <div key={i} className={'iv-pillar' + (sel === i ? ' on' : '')} onClick={() => setSel(i)}>
            <div className="n">{pl.n}</div><h5>{pl.t}</h5><p>{pl.blurb}</p>
          </div>
        ))}
      </div>
      <div className="iv-pillar-detail">
        {p.groups.map((g, gi) => (
          <div key={gi}>
            <h6>{g[0]}</h6>
            <ul>{g[1].map((x, xi) => <li key={xi}>{x}</li>)}</ul>
          </div>
        ))}
      </div>
    </InsightPanel>
  );
}

/* ── 6 · Implementation: 18-month timeline ──────────────────────────────── */
const PHASES = [
  { mo: 'Months 1-6', t: 'Foundation Assessment', sub: 'Readiness', acts: ['Executive education on care ethics & business case', 'Honest assessment of power-redistribution willingness', 'Care work audit & baseline measurement', 'Co-researcher training & pilot selection'] },
  { mo: 'Months 7-12', t: 'Pilot Implementation', sub: 'Testing & refinement', acts: ['Employee-led pilots in selected areas', 'Manager training on care recognition', 'Policy integration into performance & pay', 'Real-time monitoring & rapid refinement'] },
  { mo: 'Months 13-18', t: 'Organizational Integration', sub: 'Scaled change', acts: ['Organisation-wide rollout of refined practice', 'Cultural integration via storytelling', 'Continuous improvement systems', 'Impact measurement across indicators'] },
];
function InsightTimeline() {
  const [sel, setSel] = React.useState(0);
  return (
    <InsightPanel label="Research-validated roadmap" hint="Eighteen months, three phases. Select a phase to see its activities.">
      <div className="iv-tl-ruler">{Array.from({ length: 18 }).map((_, i) => <span key={i}></span>)}</div>
      <div className="iv-phases">
        {PHASES.map((p, i) => (
          <div key={i} className={'iv-phase' + (sel === i ? ' on' : '')} onClick={() => setSel(i)}>
            <div className="mo">{p.mo}</div><h5>{p.t}</h5><div className="sub">{p.sub}</div>
          </div>
        ))}
      </div>
      <div className="iv-phase-detail">
        <ul>{PHASES[sel].acts.map((a, i) => <li key={i}>{a}</li>)}</ul>
      </div>
    </InsightPanel>
  );
}

/* ── 7 · ROI: useful measurement vs dangerous surveillance ──────────────── */
function InsightROI() {
  const [mode, setMode] = React.useState('useful');
  const useful = mode === 'useful';
  return (
    <InsightPanel label="Measurement without surveillance" hint="The same intent splits two ways. Measure impact and you support care. Measure activity and you commodify it.">
      <div className="iv-seg" role="tablist">
        <button className={useful ? 'on' : ''} onClick={() => setMode('useful')}>Useful measurement</button>
        <button className={!useful ? 'on' : ''} onClick={() => setMode('surveil')}>Dangerous surveillance</button>
      </div>
      {useful ? (
        <>
          <div className="iv-roi-panel useful" style={{ marginTop: 16 }}>
            <h5>Impact outcomes</h5>
            <p>Recognise care work through outcomes, not activity tracking. Measure whether people are supported, retained and able to do their best work.</p>
          </div>
          <div className="iv-roi-stats">
            <div className="iv-roi-stat useful"><div className="v">4:1</div><div className="k">ROI on wellbeing programs (WHO, 2022)</div></div>
            <div className="iv-roi-stat useful"><div className="v">30%</div><div className="k">Better retention with care support</div></div>
            <div className="iv-roi-stat useful"><div className="v">41%</div><div className="k">Lower absenteeism</div></div>
            <div className="iv-roi-stat useful"><div className="v">17%</div><div className="k">Productivity gain</div></div>
          </div>
        </>
      ) : (
        <div className="iv-roi-panel surveil" style={{ marginTop: 16 }}>
          <h5>Activity tracking</h5>
          <p>Counting care acts turns care into performance. Surveillance erodes the relational authenticity that made the work valuable in the first place. The metric quietly becomes the target, and the target replaces the care.</p>
        </div>
      )}
    </InsightPanel>
  );
}

/* 8. Critical questions: reflective */
const QS = [
  { k: 'On measurement', q: 'How do we measure care work without surveilling it?', body: 'Creating metrics risks commodifying care, potentially undermining the relational authenticity that makes it valuable.' },
  { k: 'On scaling', q: 'Can the framework keep its participatory essence as it grows?', body: 'How do we prevent care consciousness from becoming another checkbox initiative?' },
  { k: 'On culture', q: 'How does maternal intelligence translate across cultures?', body: 'Different family structures, care traditions and work patterns. What is universal versus culturally specific?' },
  { k: 'On power', q: 'How do we meet resistance from those who benefit?', body: 'Particularly at leadership levels that benefit from current care work exploitation.' },
];
function InsightQuestions() {
  const [open, setOpen] = React.useState(null);
  return (
    <InsightPanel label="Sit with the unresolved" hint="These questions are open on purpose. Intellectual honesty means holding them, not closing them. Select one to sit with it.">
      <div className="iv-questions">
        {QS.map((item, i) => (
          <div key={i} className={'iv-q' + (open === i ? ' on' : '')} onClick={() => setOpen(open === i ? null : i)}>
            <div className="qh"><span className="qk">{item.k}</span><span className="qt">{item.q}</span></div>
            <div className="iv-q-body"><div><p>{item.body}</p><div className="iv-q-rest">Left open. This is a question we carry, not one we have answered.</div></div></div>
          </div>
        ))}
      </div>
    </InsightPanel>
  );
}

/* 10. Conclusion: the four whys */
const WHYS = [
  { q: 'Why now?', a: 'Post-automation organisations need systematic approaches to irreplaceable human capabilities.' },
  { q: 'Why care?', a: 'Care work is invisible infrastructure determining organisational resilience and effectiveness.' },
  { q: 'Why maternal intelligence?', a: "Mothers already do systems thinking under constraint. We are scaling their epistemology." },
  { q: 'Why this framework?', a: 'The first comprehensive methodology making care consciousness measurable and implementable for compatible contexts.' },
];
function InsightWhys() {
  const [open, setOpen] = React.useState({});
  return (
    <InsightPanel label="The four strategic whys" hint="Select each to turn it over.">
      <div className="iv-whys">
        {WHYS.map((w, i) => (
          <div key={i} className={'iv-why' + (open[i] ? ' on' : '')} onClick={() => setOpen({ ...open, [i]: !open[i] })}>
            <div className="q">{w.q}</div><div className="a">{w.a}</div>
          </div>
        ))}
      </div>
    </InsightPanel>
  );
}

window.INTERACTIVES = {
  dashboard: InsightDashboard,
  fit: InsightFit,
  automation: InsightAutomation,
  architecture: InsightArchitecture,
  pillars: InsightPillars,
  timeline: InsightTimeline,
  roi: InsightROI,
  questions: InsightQuestions,
  whys: InsightWhys,
};
