// ============================================================
// WATER MANAGEMENT PLATFORM — case study support components.
// Copy source of truth: rio-tinto-brief.md — wording verbatim.
// Reuses CountUp / DecPair / Mockup / ScreenPlaceholder globals
// declared in imprint-case.jsx / imprint-screens.jsx / rio-tinto-screens.jsx.
// ============================================================
const { useState: useStateRT } = React;

// ---- "at a glance" stat strip (hero) ----
function AtAGlance() {
  const stats = [
    { before: '50s', after: '80s', label: 'SUS score' },
    { before: '40', after: '200+', label: 'Active users' },
    { value: 70, suffix: '%', label: 'Fewer duplicate support tickets' },
    { before: 'Weeks', after: 'Real-time', label: 'Downtime detection' },
  ];
  return (
    <div className="rt-glance reveal">
      {stats.map((s, i) => (
        <div key={i} className="rt-glance-cell">
          <div className="rt-glance-v">
            {s.value !== undefined
              ? <CountUp to={s.value} suffix={s.suffix} />
              : <React.Fragment>{s.before}<span className="arrow">→</span>{s.after}</React.Fragment>}
          </div>
          <div className="rt-glance-l">{s.label}</div>
        </div>
      ))}
    </div>
  );
}

// ---- discovery / design & validation split-bar ----
function ProcessRhythm() {
  return (
    <div className="rt-rhythm reveal">
      <div className="rt-rhythm-bar">
        <div className="rt-rhythm-half a">Discovery & research</div>
        <div className="rt-rhythm-cut"></div>
        <div className="rt-rhythm-half b">Design & validation</div>
      </div>
      <div className="rt-rhythm-caption">
        <span>First half of the PI</span>
        <span>Second half of the PI</span>
      </div>
    </div>
  );
}

// ---- three work-phase columns ----
function WorkPhases() {
  const cols = [
    {
      k: 'First half', t: 'Discovery and research',
      items: [
        'Facilitated discovery workshops with engineers, hydrogeologists, supervisors, and product stakeholders',
        'Ran stakeholder interviews to understand workflows and reporting pain points',
        'Captured business requirements and operational constraints',
        'Synthesised findings in Miro using affinity mapping',
        'Prioritised opportunities with Product Owners and engineering',
      ],
    },
    {
      k: 'Second half', t: 'Design and validation',
      items: [
        'Built user flows, information architecture, wireframes, and high-fidelity designs in Figma',
        'Ran design critiques with designers, engineers, and stakeholders',
        'Built interactive prototypes for complex reporting workflows',
        'Conducted moderated usability testing in Maze',
        'Synthesised findings and iterated',
        'Used Figma Make to rapidly prototype alternative interaction patterns for complex chart behaviour',
      ],
    },
    {
      k: 'Following PI', t: 'Implementation',
      items: [
        'Partnered closely with developers during the build',
        'Used embedded Figma prototypes to clarify interaction details',
        'Supported QA and edge-case validation',
        'Gathered production feedback to inform the next discovery cycle',
      ],
    },
  ];
  return (
    <div className="rt-phases">
      {cols.map((c, i) => (
        <div key={i} className="rt-phase-col reveal" style={{ transitionDelay: (i * 0.08) + 's' }}>
          <div className="ph-k">{c.k}</div>
          <div className="ph-t">{c.t}</div>
          <ul>{c.items.map((it, j) => <li key={j}>{it}</li>)}</ul>
        </div>
      ))}
    </div>
  );
}

// ---- Downtimes module: Ongoing / Completed / Trends ----
function DowntimesShowcase() {
  const views = {
    ongoing: { label: 'Ongoing', desc: 'Active downtime events requiring attention right now.', Screen: DowntimesLiveScreen },
    completed: { label: 'Completed', desc: 'Historical downtime records, for investigation and pattern-spotting.', Screen: DowntimesCompletedScreen },
    trends: { label: 'Trends', desc: 'Aggregated reporting across sites, locations, and operational areas.', Screen: DowntimesTrendsScreen },
  };
  const [tab, setTab] = useStateRT('ongoing');
  const Screen = views[tab].Screen;
  return (
    <div className="reveal">
      <div className="rt-dt-meta">
        <div className="cs-toggle">
          {Object.keys(views).map(k => (
            <button key={k} className={tab === k ? 'on' : ''} onClick={() => setTab(k)}>{views[k].label}</button>
          ))}
        </div>
        <span className="rt-dt-desc">{views[tab].desc}</span>
      </div>
      <Mockup url={'platform.riotinto.internal/downtimes/' + tab} canvasWidth={1440} canvasHeight={900}>
        <Screen />
      </Mockup>
    </div>
  );
}

// ---- shipped-first timeline (Ongoing shipped before Completed/Trends) ----
function ShipTimeline() {
  const nodes = [
    { tag: 'PI · shipped first', t: 'Ongoing', d: 'The single most urgent pain point, downtime events sitting undetected for weeks, scoped, tested, and shipped first.', first: true },
    { tag: 'Later PI', t: 'Completed', d: 'Sequenced in once the core real-time detection loop was validated in production.' },
    { tag: 'Later PI', t: 'Trends', d: 'Shipped alongside Completed, once the real-time visibility was already in users’ hands.' },
  ];
  return (
    <div className="rt-ship reveal">
      {nodes.map((n, i) => (
        <React.Fragment key={i}>
          <div className={'rt-ship-node' + (n.first ? ' first' : '')}>
            <div className="sp-tag">{n.tag}</div>
            <div className="sp-t">{n.t}</div>
            <div className="sp-d">{n.d}</div>
          </div>
          {i < nodes.length - 1 && <div className="rt-ship-arrow">→</div>}
        </React.Fragment>
      ))}
    </div>
  );
}

// ---- chart-type snippets (line / bar / treemap) ----
function ChartRow() {
  return (
    <div className="reveal">
      <Mockup url="platform.riotinto.internal/charts" canvasWidth={1440} canvasHeight={900}>
        <ChartSnippetsScreen />
      </Mockup>
    </div>
  );
}

// ---- richer operational data chip row ----
function DataChips() {
  const items = ['Asset information', 'Engine temperature & equipment health', 'Geographic context', 'Historical performance', 'Live downtime events'];
  return (
    <div className="rt-datachips reveal">
      {items.map((t, i) => <span key={i} className="rt-datachip">{t}</span>)}
    </div>
  );
}

// ---- outcome two-column cards ----
function OutcomeColumns() {
  const users = [
    'SUS score lifted from the 50s into the 80s',
    'Real-time visibility of downtime events across all seven mine sites',
    'Next-day reporting delays eliminated through real-time field capture',
    'Increased trust in the platform as the genuine single source of truth for water operations',
  ];
  const business = [
    'Adoption grew from 40 to over 200 active users, direct return on the time invested in the redesign, not just a usability win',
    'Reduced reliance on Excel and Power BI meant less duplicated maintenance effort across seven sites’ worth of parallel reporting tools',
    'Standardised reporting structure across every site, cutting the reconciliation work that used to happen every time data needed to be compared across sites',
    '70% reduction in duplicate support tickets, direct time back for the support and engineering teams',
    'Downtime events that used to surface weeks late now surface in real time, materially reducing the window of unmanaged operational risk',
  ];
  return (
    <div className="rt-outgrid">
      <div className="rt-outcard reveal">
        <h4>For users</h4>
        <ul>{users.map((u, i) => <li key={i}>{u}</li>)}</ul>
      </div>
      <div className="rt-outcard reveal" style={{ transitionDelay: '0.08s' }}>
        <h4>For the business</h4>
        <ul>{business.map((b, i) => <li key={i}>{b}</li>)}</ul>
      </div>
    </div>
  );
}

// ---- crops a mobile screen out of its shared 1440x900 canvas and scales
// it up to a legible, genuinely phone-sized frame — used for the field
// capture screen, which was previously shown shrunk inside the desktop
// browser-chrome Mockup, making a phone screenshot look like it was
// sitting inside a website and rendering it too small to read ----
function RTPhoneCrop({ children, maxWidth = 380, maxScaleUp = 1.7 }) {
  const contentRef = React.useRef(null);
  const [box, setBox] = useStateRT(null);

  React.useLayoutEffect(() => {
    const content = contentRef.current;
    if (!content) return;
    const measure = () => {
      const canvas = content.firstElementChild;
      const phone = canvas && canvas.firstElementChild;
      if (!phone) return;
      // offsetLeft/Top/Width/Height are relative to the nearest positioned
      // ancestor (content, which is position:absolute) and, unlike
      // getBoundingClientRect, are unaffected by the CSS scale transform
      // applied to content itself. Using getBoundingClientRect here would
      // read the already-scaled size back in, and each re-measure would
      // shrink the crop a little further, converging on a too-small result.
      setBox({ left: phone.offsetLeft, top: phone.offsetTop, w: phone.offsetWidth, h: phone.offsetHeight });
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(content);
    return () => ro.disconnect();
  }, []);

  const scale = box ? Math.min(maxScaleUp, maxWidth / box.w) : 1;
  const outerW = box ? box.w * scale : maxWidth;
  const outerH = box ? box.h * scale : 640;

  return (
    <div style={{ width: outerW, height: outerH, overflow: 'hidden', position: 'relative', margin: '0 auto', borderRadius: 26, boxShadow: '0 30px 60px -28px rgba(20,20,20,.35)' }}>
      <div
        ref={contentRef}
        style={{
          position: 'absolute',
          left: box ? -box.left * scale : 0,
          top: box ? -box.top * scale : 0,
          transform: `scale(${scale})`,
          transformOrigin: 'top left',
        }}
      >
        {children}
      </div>
    </div>
  );
}

Object.assign(window, {
  AtAGlance, ProcessRhythm, WorkPhases, DowntimesShowcase, ShipTimeline, ChartRow, DataChips, OutcomeColumns, RTPhoneCrop,
});
