/* FORGE — ScreenMotorSizing · pick motor for a duty point
   Babel-standalone in-browser React. NO ES imports / exports.
   Globals: React, PumpPhysics, PUMP_TENANT, navigate, registerPumpRoute. */

(function () {
  'use strict';

  var R = (typeof React !== 'undefined') ? React : null;
  if (!R) return;
  var uSMS = R.useState;
  var uMMS = R.useMemo;

  // Paper palette (matches act1-2 / head-curve)
  var PAPER_BG     = 'oklch(0.985 0.004 85)';
  var PAPER_BG_2   = 'oklch(0.93 0.005 85)';
  var PAPER_BG_3   = 'oklch(0.965 0.005 85)';
  var PAPER_INK    = 'oklch(0.16 0.01 85)';
  var PAPER_INK_2  = 'oklch(0.30 0.01 85)';
  var PAPER_INK_3  = 'oklch(0.46 0.01 85)';
  var PAPER_INK_4  = 'oklch(0.60 0.01 85)';
  var PAPER_LINE   = 'oklch(0.84 0.006 85)';
  var PAPER_LINE_S = 'oklch(0.90 0.005 85)';
  var ACCENT       = 'oklch(0.78 0.16 75)';
  var GREEN        = 'oklch(0.66 0.13 145)';
  var RED          = 'oklch(0.58 0.18 28)';
  var AMBER        = 'oklch(0.78 0.13 70)';
  var BLUE         = 'oklch(0.62 0.10 235)';

  var FONT_UI    = 'var(--font-ui)';
  var FONT_MONO  = 'var(--font-mono)';
  var FONT_SERIF = 'var(--font-serif)';

  function root() {
    return {
      background: PAPER_BG, color: PAPER_INK,
      minHeight: '100vh', overflowY: 'auto',
      fontFamily: FONT_UI, fontSize: 14, lineHeight: 1.5,
      width: '100%', position: 'absolute', inset: 0,
      WebkitFontSmoothing: 'antialiased'
    };
  }
  function container() { return { maxWidth: 1280, margin: '0 auto', padding: '32px 40px', width: '100%' }; }
  function mono() {
    return { fontFamily: FONT_MONO, fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase', color: PAPER_INK_3 };
  }
  function Card(props) {
    var s = Object.assign({ background: PAPER_BG_3, border: '1px solid ' + PAPER_LINE, borderRadius: 10, padding: 20 }, props.style || {});
    return R.createElement('div', { style: s }, props.children);
  }
  function Pill(props) {
    var tones = {
      default: { bg: PAPER_BG_3, fg: PAPER_INK_2, bd: PAPER_LINE },
      accent:  { bg: PAPER_BG_3, fg: ACCENT,      bd: ACCENT      },
      green:   { bg: PAPER_BG_3, fg: GREEN,       bd: GREEN       },
      red:     { bg: PAPER_BG_3, fg: RED,         bd: RED         },
      amber:   { bg: PAPER_BG_3, fg: AMBER,       bd: AMBER       },
      blue:    { bg: PAPER_BG_3, fg: BLUE,        bd: BLUE        }
    };
    var p = tones[props.tone || 'default'];
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        height: 22, padding: '0 10px', borderRadius: 999,
        fontFamily: FONT_MONO, fontSize: 12,
        letterSpacing: '0.08em', textTransform: 'uppercase',
        border: '1px solid ' + p.bd, color: p.fg, background: p.bg
      }}>{props.children}</span>
    );
  }
  function Header(props) {
    return (
      <div style={{ marginBottom: 28 }}>
        <div style={Object.assign({}, mono(), { marginBottom: 8 })}>{props.eyebrow}</div>
        <h1 style={{ fontFamily: FONT_SERIF, fontSize: 34, fontWeight: 600, letterSpacing: '-0.015em', margin: 0, color: PAPER_INK }}>{props.title}</h1>
        {props.subtitle && <div style={{ marginTop: 8, color: PAPER_INK_3, fontSize: 14 }}>{props.subtitle}</div>}
      </div>
    );
  }
  function nav(p) { if (typeof navigate === 'function') navigate(p); }

  // Map a duty kW to candidate motor parts from PUMP_TENANT.parts.
  // Motor sub-assemblies live under p='10.00' but per-SKU stator/winding
  // selects HP class — we surface stator + winding lines as the "motor".
  function getMotorCandidatesFromParts() {
    var T = (typeof window !== 'undefined') ? window.PUMP_TENANT : null;
    if (!T || !T.parts) return [];
    // Heuristic: stator stack (10.06*) + winding (10.12*) parts are HP-rated motor SKUs.
    var stators = T.parts.filter(function (p) {
      return /^10\.06/.test(p.num);
    });
    var windings = T.parts.filter(function (p) {
      return /^10\.12/.test(p.num);
    });
    // Pair stator + winding by HP class (suffix heuristic):
    //   10.06   = 120SL = 1.0HP        → 10.12 (1.0HP)
    //   10.06b  = 100SL = 0.75HP       → 10.12b (0.75HP)
    //   10.06c  = 180SL = 5.0HP        → 10.12c (5HP)
    var matrix = [
      { suffix: '',  hp_class: 1.0,  label: '120SL · 1.0HP' },
      { suffix: 'b', hp_class: 0.75, label: '100SL · 0.75HP' },
      { suffix: 'c', hp_class: 5.0,  label: '180SL · 5.0HP' }
    ];
    return matrix.map(function (m) {
      var stator = stators.find(function (s) { return s.num === '10.06' + m.suffix; });
      var winding = windings.find(function (w) { return w.num === '10.12' + m.suffix; });
      return {
        hp_class: m.hp_class,
        label: m.label,
        stator_pn: stator ? stator.num : null,
        stator_name: stator ? stator.name : null,
        stator_cost: stator ? stator.cost_inr : 0,
        winding_pn: winding ? winding.num : null,
        winding_name: winding ? winding.name : null,
        winding_cost: winding ? winding.cost_inr : 0,
        combined_cost: (stator ? stator.cost_inr : 0) + (winding ? winding.cost_inr : 0)
      };
    });
  }

  // ════════════════════════════════════════════════════════════════════
  function ScreenMotorSizing() {
    var PP = (typeof window !== 'undefined') ? window.PumpPhysics : null;
    var candidates = getMotorCandidatesFromParts();

    var dutyState = uSMS(0.75);      // kW
    var duty = dutyState[0]; var setDuty = dutyState[1];
    var sfState   = uSMS(1.15);
    var sf = sfState[0]; var setSf = sfState[1];
    var hpClassState = uSMS(1.0);
    var hpClass = hpClassState[0]; var setHpClass = hpClassState[1];

    var sized = uMMS(function () {
      if (!PP) return { required_kw: 0, recommended_kw: 0, frame_size: '—' };
      return PP.motorSize({ duty_kw: duty, sf: sf, hp_class: hpClass });
    }, [duty, sf, hpClass]);

    // For each candidate motor part, flag undersize (its rated kW < required)
    var KW_PER_HP = 0.7457;
    var enriched = candidates.map(function (c) {
      var rated_kw = c.hp_class * KW_PER_HP;
      var headroom_kw = rated_kw - sized.required_kw;
      var undersize = headroom_kw < 0;
      return Object.assign({}, c, {
        rated_kw: Math.round(rated_kw * 100) / 100,
        headroom_kw: Math.round(headroom_kw * 100) / 100,
        undersize: undersize,
        match_hp: Math.abs(c.hp_class - hpClass) < 0.05
      });
    });

    function field(label, valueElt) {
      return (
        <div style={{ marginBottom: 12 }}>
          <div style={Object.assign({}, mono(), { fontSize: 11, marginBottom: 4 })}>{label}</div>
          {valueElt}
        </div>
      );
    }

    function num(id, label, value, onChange, unit, step) {
      return field(label, (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <input
            type="number"
            id={id}
            name={id}
            aria-label={label + (unit ? ' (' + unit + ')' : '')}
            value={value}
            step={step || 0.1}
            onChange={function (e) { onChange(Number(e.target.value)); }}
            style={{
              flex: 1, height: 36, padding: '0 10px',
              fontFamily: FONT_UI, fontSize: 14, color: PAPER_INK,
              background: PAPER_BG, border: '1px solid ' + PAPER_LINE, borderRadius: 6, outline: 'none'
            }}
          />
          <span style={{ fontFamily: FONT_MONO, fontSize: 11, color: PAPER_INK_3 }}>{unit}</span>
        </div>
      ));
    }

    var th = {
      textAlign: 'left', padding: '10px 12px',
      fontFamily: FONT_MONO, fontSize: 12,
      letterSpacing: '0.08em', textTransform: 'uppercase',
      color: PAPER_INK_3
    };
    var td = { padding: '10px 12px', fontFamily: FONT_MONO, color: PAPER_INK };

    return (
      <div style={root()}>
        <div style={container()}>
          <Header
            eyebrow="Forge · MOTOR SIZING"
            title="Motor sizing for duty"
            subtitle="Required kW = duty × SF. Recommend next standard IEC step. Flag undersize candidates in red."
          />

          <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr', gap: 24 }}>
            {/* Inputs */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <Card>
                <div style={Object.assign({}, mono(), { marginBottom: 14 })}>Duty inputs</div>
                {num('motor-duty-kw', 'Duty (shaft) kW', duty, setDuty, 'kW', 0.05)}
                {num('motor-service-factor', 'Service factor', sf, setSf, '×', 0.05)}
                {num('motor-hp-class', 'Target HP class', hpClass, setHpClass, 'HP', 0.25)}
              </Card>

              <Card style={{ background: PAPER_BG_2 }}>
                <div style={Object.assign({}, mono(), { marginBottom: 10 })}>Sized recommendation</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 13 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: PAPER_INK_3 }}>Required kW</span>
                    <span style={{ fontFamily: FONT_MONO }}>{sized.required_kw} kW</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: PAPER_INK_3 }}>Recommended kW</span>
                    <span style={{ fontFamily: FONT_MONO, fontWeight: 600, color: GREEN }}>{sized.recommended_kw} kW</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: PAPER_INK_3 }}>Frame</span>
                    <span style={{ fontFamily: FONT_MONO }}>{sized.frame_size}</span>
                  </div>
                </div>
                <div style={{ marginTop: 12, fontSize: 12, color: PAPER_INK_3, lineHeight: 1.5 }}>
                  IEC step-up sequence: 0.37, 0.55, 0.75, 1.1, 1.5, 2.2, 3.0, 4.0, 5.5, 7.5 kW.
                  Service factor 1.15 = standard pumpset margin (IS:9079).
                </div>
              </Card>
            </div>

            {/* Catalog */}
            <Card>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                <div style={mono()}>Motor candidates · from PUMP_TENANT.parts</div>
                <Pill tone="accent">{enriched.length} candidates</Pill>
              </div>
              <div style={{ overflow: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                  <thead>
                    <tr style={{ background: PAPER_BG_2, borderBottom: '1px solid ' + PAPER_LINE }}>
                      <th style={th}>HP class</th>
                      <th style={th}>Stator</th>
                      <th style={th}>Winding</th>
                      <th style={th}>Rated kW</th>
                      <th style={th}>Headroom</th>
                      <th style={th}>RMC</th>
                      <th style={th}>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {enriched.map(function (c) {
                      var isMatch = c.match_hp;
                      var bg = c.undersize ? 'oklch(0.97 0.04 28)' : (isMatch ? 'oklch(0.96 0.04 95)' : 'transparent');
                      var statusEl;
                      if (c.undersize) statusEl = <Pill tone="red">UNDERSIZE</Pill>;
                      else if (isMatch) statusEl = <Pill tone="green">MATCH</Pill>;
                      else statusEl = <Pill>OK</Pill>;
                      return (
                        <tr key={c.label} style={{ borderBottom: '1px solid ' + PAPER_LINE_S, background: bg }}>
                          <td style={Object.assign({}, td, { fontWeight: isMatch ? 600 : 400 })}>{c.hp_class} HP · {c.label}</td>
                          <td style={td}>{c.stator_pn || '—'}</td>
                          <td style={td}>{c.winding_pn || '—'}</td>
                          <td style={td}>{c.rated_kw}</td>
                          <td style={Object.assign({}, td, { color: c.undersize ? RED : (c.headroom_kw < 0.2 ? AMBER : GREEN) })}>
                            {c.headroom_kw >= 0 ? '+' : ''}{c.headroom_kw} kW
                          </td>
                          <td style={td}>₹{(c.combined_cost || 0).toLocaleString('en-IN')}</td>
                          <td style={Object.assign({}, td, { fontFamily: FONT_UI })}>{statusEl}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              <div style={{ marginTop: 16, padding: 12, background: PAPER_BG_2, borderRadius: 8, fontSize: 12, color: PAPER_INK_3, lineHeight: 1.5 }}>
                <span style={{ fontFamily: FONT_MONO, color: PAPER_INK_2 }}>Note · </span>
                Rated kW = HP class × 0.7457. Headroom = rated kW − required kW. An
                undersize motor will draw above its FLC under sustained load and trip
                or burn the winding — IS:9079 requires a positive margin.
              </div>
            </Card>
          </div>
        </div>
      </div>
    );
  }

  if (typeof window !== 'undefined') {
    window.ScreenMotorSizing = ScreenMotorSizing;
    if (typeof window.registerPumpRoute === 'function') {
      window.registerPumpRoute({
        path: '/forge/motor-sizing', mode: 'forge', title: 'Motor sizing',
        renderer: function () { return R.createElement(ScreenMotorSizing); }
      });
    }
  }
})();
