// Unit Converter Engine — OM Group ERP
// Globals:  cvtFactor · cvtBaseUnit · cvtSecUnit · cvtInfo
// Components: ConversionBadge · ConversionFactorsSection

const { useState: cvSt, useEffect: cvEf } = React;

// ── Core utilities (available globally) ──────────────────────────
(function(w) {
  'use strict';
  function getMat(mid) { return w.Store ? w.Store.byId('materials', mid) : null; }

  w.cvtFactor   = function(mid) { const m=getMat(mid); return (m&&m.conversionFactor) ? parseFloat(m.conversionFactor) : null; };
  w.cvtBaseUnit = function(mid) { const m=getMat(mid); return (m&&m.baseUnit)  || 'MT'; };
  w.cvtSecUnit  = function(mid) { const m=getMat(mid); return (m&&m.secondaryUnit) || 'm³'; };

  // Returns full info object or null when no factor is defined
  w.cvtInfo = function(mid, qty, rate, fromUnit) {
    const f = w.cvtFactor(mid);
    if (!f) return null;
    const bu = w.cvtBaseUnit(mid);
    const su = w.cvtSecUnit(mid);
    const q  = parseFloat(qty)  || 0;
    const r  = parseFloat(rate) || 0;
    const fu = fromUnit || bu;
    const tu = fu === bu ? su : bu;
    const convQty  = fu===bu ? +(q*f).toFixed(3) : +(q/f).toFixed(3);
    const convRate = r>0 ? (fu===bu ? +(r/f).toFixed(2) : +(r*f).toFixed(2)) : null;
    return { factor:f, baseUnit:bu, secondaryUnit:su, fromUnit:fu, toUnit:tu, origQty:q, origRate:r, convQty, convRate };
  };
})(window);

// ── ConversionBadge ──────────────────────────────────────────────
// Stable inline/column conversion indicator for item grids.
//
// Props:
//   materialId, qty, rate, unit — data
//   twoLine — when true, renders a structured two-line column badge:
//               ≈ 7.68 m³
//               ₹625/m³
//             when false (default), renders compact single-line inline badge.
//
// All text is white-space:nowrap + overflow:hidden to guarantee that NO VALUE
// — however large — ever wraps to an extra line and pushes row height.
// Column widths are locked by table-layout:fixed in .ig; this component
// locks the HEIGHT by never allowing text to wrap.
function ConversionBadge({ materialId, qty, rate, unit, twoLine }) {
  if (!materialId || !(parseFloat(qty) > 0)) return null;
  const info = window.cvtInfo ? window.cvtInfo(materialId, qty, rate, unit) : null;
  if (!info) return null;

  const icon = (
    <svg width="7" height="7" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"
      style={{flexShrink:0, opacity:.8, display:'block'}}>
      <polyline points="17 1 21 5 17 9"/>
      <path d="M3 11V9a4 4 0 014-4h14"/>
      <polyline points="7 23 3 19 7 15"/>
      <path d="M21 13v2a4 4 0 01-4 4H3"/>
    </svg>
  );

  // ── Two-line structured display — for dedicated Conversion columns ────────
  // Fixed structure: always two visual slots (qty line + rate line).
  // Rate line is empty-but-reserved when no rate, so rows stay the same height.
  if (twoLine) {
    return (
      <div style={{overflow:'hidden', maxWidth:'100%', lineHeight:1.3}}>
        {/* Line 1 — converted quantity */}
        <div style={{
          display:'flex', alignItems:'center', gap:3,
          fontSize:10, color:'#2563EB', fontWeight:600,
          whiteSpace:'nowrap', overflow:'hidden',
        }}>
          {icon}
          <span style={{overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>
            ≈ {info.convQty} {info.toUnit}
          </span>
        </div>
        {/* Line 2 — converted rate (always renders to hold height stable) */}
        <div style={{
          fontSize:9.5, fontWeight:500,
          whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
          paddingLeft:10, lineHeight:1.4, minHeight:'1em',
          color: info.convRate != null ? 'var(--txt2)' : 'transparent',
        }}>
          {info.convRate != null
            ? `₹${window.fmtNum(info.convRate)}/${info.toUnit}`
            : '\u200B'  /* zero-width space keeps line alive for height */}
        </div>
      </div>
    );
  }

  // ── Single-line compact display — for inline use inside quantity cells ────
  // white-space:nowrap ensures long values never wrap and increase row height.
  return (
    <div style={{
      display:'flex', alignItems:'center', gap:3,
      fontSize:10, color:'#2563EB', fontWeight:500,
      whiteSpace:'nowrap', overflow:'hidden',
      marginTop:2, lineHeight:1.3, maxWidth:'100%',
    }}>
      {icon}
      <span style={{overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>
        ≈ {info.convQty} {info.toUnit}
      </span>
      {info.convRate != null && (
        <span style={{
          color:'var(--txt2)', marginLeft:1,
          overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap',
        }}>
          · ₹{window.fmtNum(info.convRate)}/{info.toUnit}
        </span>
      )}
    </div>
  );
}
window.ConversionBadge = ConversionBadge;

// ── ConversionFactorsSection ─────────────────────────────────────
// Full management table rendered at the bottom of MaterialsPage.
function ConversionFactorsSection({ companyId, session }) {
  const [materials, setMaterials] = cvSt([]);
  const [editId,    setEditId]    = cvSt(null);
  const [editForm,  setEditForm]  = cvSt({});
  const [open,      setOpen]      = cvSt(true);

  const isAdmin = ['SUPER_ADMIN','ADMIN','MANAGER'].includes(session?.userRole);

  cvEf(() => { reload(); }, [companyId]);
  function reload() { setMaterials(Store.all('materials', companyId)); }

  function openEdit(m) {
    setEditForm({
      baseUnit:         m.baseUnit         || 'MT',
      secondaryUnit:    m.secondaryUnit    || 'm³',
      conversionFactor: m.conversionFactor || '',
      allowOverride:    m.allowOverride    !== false,
    });
    setEditId(m.id);
  }
  function cancelEdit() { setEditId(null); }

  function saveEdit() {
    if (!editForm.conversionFactor) { window.toast&&window.toast('Conversion factor is required','er'); return; }
    Store.update('materials', editId, editForm);
    Store.addLog('UPDATE','Conversion Factor',
      `${Store.name('materials',editId)}: 1 ${editForm.baseUnit} = ${editForm.conversionFactor} ${editForm.secondaryUnit}`);
    setEditId(null); reload();
    window.toast&&window.toast('Conversion factor saved','ok');
  }

  const setEF = (k,v) => setEditForm(p => ({...p,[k]:v}));

  return (
    <div style={{marginTop:18}}>
      {/* Section header */}
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8,cursor:'pointer',userSelect:'none'}}
           onClick={()=>setOpen(p=>!p)}>
        <div style={{display:'flex',alignItems:'center',gap:8}}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--or)" strokeWidth="2">
            <polyline points="17 1 21 5 17 9"/>
            <path d="M3 11V9a4 4 0 014-4h14"/>
            <polyline points="7 23 3 19 7 15"/>
            <path d="M21 13v2a4 4 0 01-4 4H3"/>
          </svg>
          <h2 style={{fontSize:14,fontWeight:600,color:'var(--txt)',margin:0}}>Conversion Factors</h2>
          <span style={{fontSize:11.5,color:'var(--txt2)'}}>Unit conversion settings — used across Sales, Purchases &amp; Transfers</span>
        </div>
        <div style={{display:'flex',alignItems:'center',gap:8}}>
          {!isAdmin && <span style={{fontSize:11,color:'var(--txt3)',background:'#F3F4F6',padding:'2px 8px',borderRadius:3}}>View only</span>}
          <span style={{color:'var(--or)',fontSize:9,display:'inline-block',transition:'transform .15s',transform:open?'rotate(90deg)':'none'}}>&#9658;</span>
        </div>
      </div>

      {open && (
        <div className="card">
          <div className="tbl-w">
            <table className="tbl">
              <thead>
                <tr>
                  <th style={{width:50,textAlign:'center'}}>SR. NO.</th>
                  <th>MATERIAL</th>
                  <th>BASE UNIT</th>
                  <th>SECONDARY UNIT</th>
                  <th>CONVERSION FACTOR</th>
                  <th>FORMULA</th>
                  <th>ALLOW OVERRIDE</th>
                  {isAdmin && <th>ACTION</th>}
                </tr>
              </thead>
              <tbody>
                {materials.length === 0
                  ? <tr className="empty"><td colSpan={isAdmin?8:7} style={{textAlign:'center',padding:32,color:'var(--txt2)'}}>No materials found.</td></tr>
                  : materials.map((m, i) => (
                    <React.Fragment key={m.id}>
                      <tr>
                        <td style={{color:'var(--txt2)',textAlign:'center'}}>{i+1}</td>
                        <td><strong>{m.name}</strong></td>
                        <td style={{color:'var(--txt2)'}}>{m.baseUnit||'MT'}</td>
                        <td style={{color:'var(--txt2)'}}>{m.secondaryUnit||'m³'}</td>
                        <td style={{fontWeight:700,color:m.conversionFactor?'var(--or)':'var(--txt3)',fontFamily:'var(--font)',fontSize:12}}>
                          {m.conversionFactor||'—'}
                        </td>
                        <td style={{fontSize:11.5,color:'var(--txt2)'}}>
                          {m.conversionFactor
                            ? `1 ${m.baseUnit||'MT'} = ${m.conversionFactor} ${m.secondaryUnit||'m³'}`
                            : <em style={{color:'var(--txt3)'}}>Not configured</em>}
                        </td>
                        <td>
                          {m.allowOverride!==false
                            ? <span className="bdg bg-gn">Yes</span>
                            : <span className="bdg bg-gy">No</span>}
                        </td>
                        {isAdmin && (
                          <td>
                            <button className="btn btn-wh btn-sm" onClick={()=>editId===m.id ? cancelEdit() : openEdit(m)}>
                              {editId===m.id ? 'Cancel' : 'Edit'}
                            </button>
                          </td>
                        )}
                      </tr>

                      {/* Inline edit row */}
                      {editId === m.id && (
                        <tr key={m.id+'-edit'}>
                          <td colSpan={isAdmin?8:7} style={{padding:0,background:'#FFF9F5',borderTop:'2px solid var(--or-bdr)'}}>
                            <div style={{padding:'12px 16px'}}>
                              <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr) auto',gap:10,alignItems:'flex-end'}}>
                                <div className="fld">
                                  <label>Base Unit</label>
                                  <window.FormSelect value={editForm.baseUnit} onChange={v=>setEF('baseUnit',v)} options={[{value:'MT',label:'MT — Metric Ton'},{value:'m³',label:'m³ — Cubic Meter'},{value:'Kg',label:'Kg — Kilogram'}]}/>
                                </div>
                                <div className="fld">
                                  <label>Secondary Unit</label>
                                  <window.FormSelect value={editForm.secondaryUnit} onChange={v=>setEF('secondaryUnit',v)} options={[{value:'m³',label:'m³ — Cubic Meter'},{value:'MT',label:'MT — Metric Ton'},{value:'Kg',label:'Kg — Kilogram'}]}/>
                                </div>
                                <div className="fld">
                                  <label>Conversion Factor <span style={{color:'var(--err)'}}>*</span></label>
                                  <input className="inp" type="number" value={editForm.conversionFactor}
                                    onChange={e=>setEF('conversionFactor',e.target.value)}
                                    step="0.001" min="0.001" placeholder="e.g. 0.67"/>
                                </div>
                                <div className="fld">
                                  <label>Allow Override</label>
                                  <window.FormSelect value={editForm.allowOverride?'yes':'no'}
                                    onChange={v=>setEF('allowOverride',v==='yes')} options={[{value:'yes',label:'Yes — Allow manual override'},{value:'no',label:'No — Lock factor'}]}/>
                                </div>
                                <div style={{display:'flex',gap:5,paddingBottom:1}}>
                                  <button type="button" className="btn btn-or btn-sm" onClick={saveEdit}>Save</button>
                                  <button type="button" className="btn btn-wh btn-sm" onClick={cancelEdit}>Cancel</button>
                                </div>
                              </div>
                              {editForm.conversionFactor && (
                                <div style={{marginTop:8,fontSize:11.5,color:'var(--txt2)',background:'#F9FAFB',padding:'5px 10px',borderRadius:3,display:'inline-block'}}>
                                  1 {editForm.baseUnit} = {editForm.conversionFactor} {editForm.secondaryUnit}
                                  &nbsp;·&nbsp;
                                  1 {editForm.secondaryUnit} ≈ {+(1/parseFloat(editForm.conversionFactor||1)).toFixed(4)} {editForm.baseUnit}
                                </div>
                              )}
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
window.ConversionFactorsSection = ConversionFactorsSection;

// ── ConvQtyCell ──────────────────────────────────────────────────
// DISPLAY ONLY — does not affect any calculations.
// Shows a quantity with a hover tooltip explaining the density
// conversion that produced it from a different original UOM.
//
// qty     : displayed (already-converted) quantity in Tons
// origQty : original quantity before conversion (e.g. 20 for "20 m³")
// origUom : original UOM (e.g. 'm³', 'CUM') — if Ton/MT, no tooltip
// density : density factor used (e.g. 1.50)
function ConvQtyCell({ qty, origQty, origUom, density }) {
  const [pos, setPos] = cvSt(null);
  const refEl = React.useRef(null);

  const qtyN  = parseFloat(qty)     || 0;
  const origN = parseFloat(origQty) || 0;
  const densN = parseFloat(density) || 1.50;
  const uom   = (origUom || '').trim();

  // Only show indicator when original UOM is non-Ton AND values actually differ
  const tonLike = ['Ton','ton','MT','mt','Tons','tons'].includes(uom);
  const hasConv = !tonLike && !!uom && Math.abs(qtyN - origN) > 0.001 && qtyN > 0;

  if (!hasConv) {
    return <span style={{ fontWeight: 600 }}>{window.formatQuantity(qtyN)}</span>;
  }

  // Determine direction: m³/CUM → multiply; Ton → divide
  const isMul = ['m³','m3','M3','CUM','cum','Cubic Meter','cubic meter'].includes(uom);
  const formula = isMul
    ? `${window.formatQuantity(origN)} ${uom} × ${densN} = ${window.formatQuantity(qtyN)} Ton`
    : `${window.formatQuantity(origN)} ${uom} ÷ ${densN} = ${window.formatQuantity(qtyN)} Ton`;

  function calcPos() {
    if (!iconRef.current) return;
    var r = iconRef.current.getBoundingClientRect();
    var vw = window.innerWidth, vh = window.innerHeight;
    var TW = 262, TH = 168, gap = 10, margin = 10;
    // Default: below the icon, horizontally centred
    var top  = r.bottom + gap;
    var left = r.left + r.width / 2 - TW / 2;
    // Flip above if not enough space below
    if (top + TH > vh - margin) top = r.top - TH - gap;
    // Prevent horizontal overflow — shift left or right
    if (left + TW > vw - margin) left = vw - TW - margin;
    left = Math.max(margin, left);
    // Clamp top
    top  = Math.max(margin, top);
    setPos({ top, left });
  }

  const iconRef = React.useRef(null);

  function openTip() { calcPos(); }

  React.useEffect(function() {
    if (!pos) return;
    function reCalc() { calcPos(); }
    window.addEventListener('scroll', reCalc, true);
    window.addEventListener('resize', reCalc);
    return function() {
      window.removeEventListener('scroll', reCalc, true);
      window.removeEventListener('resize', reCalc);
    };
  }, [!!pos]);

  return (
    <span
      ref={refEl}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 3, cursor: 'help' }}
      onMouseEnter={openTip}
      onMouseLeave={() => setPos(null)}
    >
      <span style={{ fontWeight: 600 }}>{window.formatQuantity(qtyN)}</span>
      {/* Subtle ⓘ indicator */}
      <span ref={iconRef} style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: 13, height: 13, borderRadius: '50%',
        background: '#EFF6FF', border: '1px solid #93C5FD',
        color: '#2563EB', fontSize: 8, fontWeight: 700,
        flexShrink: 0, userSelect: 'none', lineHeight: '13px',
      }}>i</span>
      {pos && ReactDOM.createPortal(
        <div className="om-tip" style={{ top: pos.top, left: pos.left, width: 262, padding: '12px 14px' }}>
          <div className="om-tip-hd">Unit Conversion Applied</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div className="om-tip-row">
              <span className="om-tip-lbl">Original</span>
              <span className="om-tip-val" style={{ color: 'var(--or)' }}>{window.formatQuantity(origN)} {uom}</span>
            </div>
            <div className="om-tip-row">
              <span className="om-tip-lbl">Density factor</span>
              <span className="om-tip-val">{densN}</span>
            </div>
            <div className="om-tip-row">
              <span className="om-tip-lbl">Converted</span>
              <span className="om-tip-val" style={{ color: 'var(--ok)' }}>{window.formatQuantity(qtyN)} Ton</span>
            </div>
            <div style={{
              marginTop: 4, padding: '6px 10px',
              background: '#F8F9FB', borderRadius: 8,
              fontSize: 11, color: 'var(--txt2)',
              fontFamily: 'var(--font)', lineHeight: 1.5,
              borderLeft: '2px solid var(--info)',
            }}>
              {formula}
            </div>
          </div>
        </div>,
        document.body
      )}
    </span>
  );
}
window.ConvQtyCell = ConvQtyCell;
