/**
 * STABLE FORM ARCHITECTURE FOR ERP
 * ─────────────────────────────────────────────────────────────────────────
 * Zero layout shift guarantee for all entry forms.
 * 
 * Core principles:
 * 1. Fixed column widths determined at render time
 * 2. Reserved space for all dynamic content BEFORE render
 * 3. Height-locked rows (no expansion from content)
 * 4. Validation messages below fields in fixed containers
 * 5. Conversion info in reserved collapsed areas
 * 6. Calculations never resize containers
 * 7. Auto-fill only changes values, never layout
 * 
 * Usage:
 *   <StableFormGrid columns={[...specs]}>
 *     <StableCalculationRow>
 *       <StableAmountCell value={amount} />
 *     </StableCalculationRow>
 *   </StableFormGrid>
 */

const { useState: stSt, useMemo: stMemo, useEffect: stEf } = React;

/**
 * ─────────────────────────────────────────────────────────────────────────
 * STABLE FORM GRID
 * ─────────────────────────────────────────────────────────────────────────
 * Container that establishes fixed column layout.
 * Never changes dimensions based on content.
 * 
 * Props:
 *   - columns: Array of {key, label, width, type, editable, ...}
 *   - children: Rows (StableCalculationRow)
 *   - gap: Spacing between cells (default 8)
 *   - rowHeight: Fixed row height in px (default 34)
 */
function StableFormGrid({ columns, children, gap = 8, rowHeight = 34, style = {} }) {
  // Calculate total grid width once
  const gridColsStr = stMemo(() => {
    return columns.map(c => {
      if (c.width) return typeof c.width === 'number' ? `${c.width}px` : c.width;
      // Default: remaining space divided equally
      return '1fr';
    }).join(` ${gap}px `);
  }, [columns, gap]);

  const totalWidth = stMemo(() => {
    return columns.reduce((sum, c) => {
      if (c.width && typeof c.width === 'number') return sum + c.width;
      return sum;
    }, 0) + (columns.length - 1) * gap;
  }, [columns, gap]);

  return (
    <div
      style={{
        display: 'grid',
        gridTemplateColumns: gridColsStr,
        gap: `${gap}px`,
        width: totalWidth ? `${totalWidth}px` : '100%',
        ...style
      }}
      data-stable-grid="true"
    >
      {children}
    </div>
  );
}

/**
 * ─────────────────────────────────────────────────────────────────────────
 * STABLE CALCULATION ROW
 * ─────────────────────────────────────────────────────────────────────────
 * Row with fixed height. All children expand to fill row vertically.
 * No vertical growth from content.
 * 
 * Props:
 *   - children: StableCell components
 *   - rowHeight: Fixed height (default 34)
 *   - validationHeight: Space reserved below row for validation (default 18)
 *   - expanded: If true, show conversion/detail area (default false)
 *   - conversionHeight: Height of conversion area when expanded (default 24)
 */
function StableCalculationRow({
  children,
  rowHeight = 34,
  validationHeight = 18,
  expanded = false,
  conversionHeight = 24,
  style = {}
}) {
  // Wrapper ensures row never grows past rowHeight
  return (
    <div style={{ display: 'contents' }}>
      <div
        style={{
          gridColumn: '1 / -1',
          display: 'grid',
          gridTemplateColumns: 'inherit',
          gap: 'inherit',
          height: `${rowHeight}px`,
          alignItems: 'stretch',
          ...style
        }}
        data-stable-row="true"
      >
        {children}
      </div>

      {/* Validation area: reserved space below row, always present */}
      <div
        style={{
          gridColumn: '1 / -1',
          height: `${validationHeight}px`,
          display: 'flex',
          alignItems: 'center',
          fontSize: '10.5px',
          color: 'var(--err)',
          overflow: 'hidden',
          paddingTop: '2px'
        }}
        data-stable-validation="true"
      >
        {/* Validation message renders here */}
      </div>

      {/* Conversion area: reserved space, hidden when not needed */}
      {conversionHeight > 0 && (
        <div
          style={{
            gridColumn: '1 / -1',
            height: expanded ? `${conversionHeight}px` : '0px',
            overflow: 'hidden',
            transition: 'height 0.15s ease',
            display: expanded ? 'flex' : 'none',
            alignItems: 'center',
            fontSize: '11px',
            color: 'var(--txt2)',
            background: '#F9FAFB',
            paddingLeft: '8px',
            borderLeft: '2px solid var(--bdr)',
            gap: '8px'
          }}
          data-stable-conversion="true"
        >
          {/* Conversion info renders here */}
        </div>
      )}
    </div>
  );
}

/**
 * ─────────────────────────────────────────────────────────────────────────
 * STABLE CELL
 * ─────────────────────────────────────────────────────────────────────────
 * Fixed-size input cell. Never expands or contracts.
 * 
 * Props:
 *   - type: 'input' | 'select' | 'readonly' | 'calculated'
 *   - value: Current value
 *   - onChange: (value) => void
 *   - placeholder: string
 *   - children: For readonly/calculated display
 *   - width: Optional override of column width
 *   - error: Validation error message
 *   - style: Additional styles
 */
function StableCell({
  type = 'input',
  value = '',
  onChange = () => {},
  placeholder = '',
  children = null,
  width = 'auto',
  error = null,
  style = {},
  ...props
}) {
  const baseStyle = {
    border: error ? '1px solid var(--err)' : '1px solid var(--bdr)',
    borderRadius: 'var(--r)',
    padding: '5px 8px',
    fontSize: '12px',
    fontFamily: 'var(--font)',
    outline: 'none',
    height: '100%',
    width: '100%',
    background: type === 'readonly' || type === 'calculated' ? '#F9FAFB' : '#fff',
    color: type === 'readonly' || type === 'calculated' ? 'var(--txt2)' : 'var(--txt)',
    transition: 'border 0.1s',
    ...style
  };

  if (type === 'readonly' || type === 'calculated') {
    return (
      <div
        style={{
          ...baseStyle,
          display: 'flex',
          alignItems: 'center',
          paddingRight: '8px',
          fontWeight: type === 'calculated' ? 600 : 400
        }}
      >
        {children || value || '—'}
      </div>
    );
  }

  if (type === 'select') {
    return (
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{
          ...baseStyle,
          appearance: 'none',
          paddingRight: '22px',
          backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%236B7280' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E")`,
          backgroundRepeat: 'no-repeat',
          backgroundPosition: 'right 6px center',
          cursor: 'pointer'
        }}
        {...props}
      >
        {children}
      </select>
    );
  }

  // type === 'input' (default)
  return (
    <input
      type="text"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      style={baseStyle}
      {...props}
    />
  );
}

/**
 * ─────────────────────────────────────────────────────────────────────────
 * STABLE AMOUNT CELL
 * ─────────────────────────────────────────────────────────────────────────
 * Specialized read-only cell for calculated amounts.
 * Guarantees fixed width via right-alignment and monospace font.
 * Large numbers never resize the column.
 * 
 * Props:
 *   - value: Number to display
 *   - currency: If true, prepend currency symbol (default false)
 *   - decimals: Decimal places (default 2)
 *   - width: Fixed width (default '100px')
 */
function StableAmountCell({ value = 0, currency = false, decimals = 2, width = '100px' }) {
  const formatted = stMemo(() => {
    const num = parseFloat(value) || 0;
    return currency
      ? '₹ ' + num.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      : num.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  }, [value, currency, decimals]);

  return (
    <div
      style={{
        width,
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'flex-end',
        paddingRight: '8px',
        fontFamily: 'var(--font)',
        fontSize: '12px',
        fontWeight: 600,
        color: 'var(--txt)',
        background: '#F9FAFB',
        border: '1px solid var(--bdr)',
        borderRadius: 'var(--r)',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap',
        flex: '0 0 auto'
      }}
      title={formatted}
    >
      {formatted}
    </div>
  );
}

/**
 * ─────────────────────────────────────────────────────────────────────────
 * STABLE VALIDATION AREA
 * ─────────────────────────────────────────────────────────────────────────
 * Display validation message in reserved space (never expands row).
 * 
 * Props:
 *   - message: Error/validation message
 *   - type: 'error' | 'warning' | 'info'
 */
function StableValidationMessage({ message, type = 'error' }) {
  if (!message) return null;

  const colors = {
    error: { bg: 'var(--err)', text: '#fff' },
    warning: { bg: 'var(--warn)', text: '#fff' },
    info: { bg: 'var(--info)', text: '#fff' }
  };

  const color = colors[type] || colors.error;

  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: '4px',
        padding: '2px 6px',
        borderRadius: '3px',
        background: color.bg,
        color: color.text,
        fontSize: '10px',
        fontWeight: 600,
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis'
      }}
      title={message}
    >
      {type === 'error' && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{display:'inline',verticalAlign:'-1px',flexShrink:0,marginRight:4}}><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>}
      {message}
    </span>
  );
}

/**
 * ─────────────────────────────────────────────────────────────────────────
 * STABLE CONVERSION DISPLAY
 * ─────────────────────────────────────────────────────────────────────────
 * Display unit conversion info in reserved collapsed area.
 * Never affects row height when hidden.
 * 
 * Props:
 *   - fromUOM: Source unit (e.g., 'KG')
 *   - toUOM: Target unit (e.g., 'MT')
 *   - factor: Conversion factor
 *   - quantity: Base quantity
 */
function StableConversionInfo({ fromUOM, toUOM, factor, quantity }) {
  if (!fromUOM || !toUOM || !factor) return null;

  const converted = stMemo(() => {
    const q = parseFloat(quantity) || 0;
    return (q * factor).toFixed(4);
  }, [quantity, factor]);

  return (
    <span style={{ display: 'flex', alignItems: 'center', gap: '12px', fontSize: '11px' }}>
      <span style={{ color: 'var(--txt2)' }}>
        {quantity} {fromUOM} = {converted} {toUOM}
      </span>
      <span style={{ color: 'var(--or)', fontWeight: 600 }}>{factor}x</span>
    </span>
  );
}

/**
 * ─────────────────────────────────────────────────────────────────────────
 * STABLE TOTALS PANEL
 * ─────────────────────────────────────────────────────────────────────────
 * Fixed-position summary panel. Never moves or resizes.
 * 
 * Props:
 *   - subtotal: number
 *   - gst: number
 *   - total: number
 *   - currency: If true, format as currency
 */
function StableTotalsPanel({ subtotal = 0, gst = 0, total = 0, currency = true }) {
  const fmt = (num) => {
    return currency
      ? '₹ ' + num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      : num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  };

  return (
    <div
      style={{
        display: 'grid',
        gridTemplateColumns: '1fr 1fr',
        gap: '12px',
        padding: '12px',
        background: '#F9FAFB',
        border: '1px solid var(--bdr)',
        borderRadius: 'var(--r)',
        borderTop: '2px solid var(--or)'
      }}
      data-stable-totals="true"
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: '11.5px', fontWeight: 600, color: 'var(--txt2)' }}>Subtotal:</span>
        <span style={{ fontFamily: 'var(--font)', fontSize: '12px', fontWeight: 700, color: 'var(--txt)' }}>
          {fmt(subtotal)}
        </span>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: '11.5px', fontWeight: 600, color: 'var(--txt2)' }}>GST:</span>
        <span style={{ fontFamily: 'var(--font)', fontSize: '12px', fontWeight: 700, color: 'var(--txt)' }}>
          {fmt(gst)}
        </span>
      </div>

      <div style={{ gridColumn: '1 / -1', display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: '6px', borderTop: '1px solid var(--bdr)' }}>
        <span style={{ fontSize: '12px', fontWeight: 700, color: 'var(--txt)' }}>Grand Total:</span>
        <span style={{ fontFamily: 'var(--font)', fontSize: '14px', fontWeight: 700, color: 'var(--or)' }}>
          {fmt(total)}
        </span>
      </div>
    </div>
  );
}

/**
 * ─────────────────────────────────────────────────────────────────────────
 * LAYOUT STABILITY AUDIT HELPER
 * ─────────────────────────────────────────────────────────────────────────
 * Runtime check to detect layout shifts (for development/testing).
 * Logs warnings if dimensions change during render cycles.
 */
function useLayoutStabilityCheck(ref, componentName = 'Component') {
  const [initialDims, setInitialDims] = stSt(null);

  stEf(() => {
    if (!ref.current) return;

    const el = ref.current;
    const current = {
      width: el.offsetWidth,
      height: el.offsetHeight,
      cols: el.style.gridTemplateColumns
    };

    if (!initialDims) {
      setInitialDims(current);
    } else if (
      current.width !== initialDims.width ||
      current.height !== initialDims.height ||
      current.cols !== initialDims.cols
    ) {
      console.warn(`[LAYOUT SHIFT] ${componentName}:`, {
        was: initialDims,
        now: current
      });
    }
  }, [initialDims, ref]);
}

// Expose to window for cross-script access
Object.assign(window, {
  StableFormGrid,
  StableCalculationRow,
  StableCell,
  StableAmountCell,
  StableValidationMessage,
  StableConversionInfo,
  StableTotalsPanel,
  useLayoutStabilityCheck,
});
