import { View } from 'react-native';
import { encodeCode128B } from '../utils/code128';

/**
 * Renders a proper Code 128B barcode using View bars.
 * Compatible with react-native-view-shot (no Canvas/SVG).
 */
export function BarcodeComponent({ value = '00794210392730860225', height = 60 }) {
  // Sanitise: Code 128B supports ASCII 32-127
  const cleanValue = String(value || '')
    .replace(/[^\x20-\x7E]/g, '')
    .substring(0, 40) || 'BARCODE';

  const pattern = encodeCode128B(cleanValue);
  const totalWidth = 550;
  const totalUnits = pattern.reduce((a, b) => a + b, 0);

  const barElements = [];
  let x = 0;

  for (let i = 0; i < pattern.length; i++) {
    const units = pattern[i];
    const w = (units / totalUnits) * totalWidth;
    const isBar = i % 2 === 0; // even indices = bars, odd = spaces
    if (isBar) {
      barElements.push(
        <View
          key={i}
          style={{
            position: 'absolute',
            left: x,
            width: Math.max(w, 1),
            height,
            backgroundColor: '#000',
          }}
        />
      );
    }
    x += w;
  }

  return (
    <View style={{ width: totalWidth, height, backgroundColor: '#fff' }}>
      {barElements}
    </View>
  );
}
