unit frm_PesadoMain;

{ Pantalla principal (táctil) del control de pesado de lotes.
  - Lista de lotes con ge_stock_envasado.finalizado = 0 ordenados por ge_lotes.codigo_antiguo.
  - Lectura continua de la báscula por COM (hilo secundario).
  - Semáforo: VERDE = peso correcto (se graba automáticamente y descuenta pendientes),
              ROJO  = peso inferior al teórico en más del % de tolerancia (alarma + desechar).
  - Botón de finalización de lote (actualiza cantidad_producida con las pesadas correctas).
  - Configuración de báscula protegida por contraseña.
  Formulario construido íntegramente por código (sin DFM). }

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, System.Math, System.UITypes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
  Vcl.Grids, Vcl.DBGrids, Data.DB,
  uPesadoConfig, uBasculaSerial, uPesadoDB;

const
  WM_AFTER_SHOW = WM_APP + 100;

type
  TEstadoSemaforo = (esEspera, esVerde, esRojo, esAviso);

  TfrmPesadoMain = class(TForm)
  private
    FConfig: TPesadoConfig;
    FDB: TPesadoDB;
    FBascula: TBasculaSerial;
    FDataSource: TDataSource;
    FPrimerShow: Boolean;

    // Estado del lote activo
    FRefrescandoLotes: Boolean;
    FLoteActivo: Boolean;
    FIdStock, FIdLote, FIdArticulo: Integer;
    FCodigoLote, FArticulo, FFormato: string;
    FPesoTeoricoKg: Double;
    FPesoArticuloRaw: Double;  // Valor tal cual de ge_articulos.peso
    FUnidadesTeoricas: Integer;
    FPesadasOK, FRechazos: Integer;

    // Estado del ciclo de pesada
    FArmado: Boolean;          // El plato se ha vaciado desde la última pesada
    FAlarmaActiva: Boolean;
    FUltimoPesoNetoKg: Double;
    FWavOk: TBytes;
    FWavAlarma: TBytes;
    FSortField: string;
    FSortDesc: Boolean;

    // Controles
    pnlTop, pnlLeft, pnlRight, pnlInfo, pnlInfoFila1, pnlCentro, pnlSemaforo, pnlPesoDisplay, pnlEstado,
    pnlContadores, pnlSim, pnlAlarma, pnlStatus, pnlGridArea, pnlScrollLotes: TPanel;
    lblTitulo, lblArticulo, lblLote, lblNominal, lblPeso, lblBruto, lblEstable, lblEstado,
    lblEstadoDetalle, lblAlarma, lblStatusCom, lblStatusDB, lblUltima: TLabel;
    lblTeoricas, lblCorrectas, lblRechazadas, lblPendientes: TLabel;
    shpRojo, shpAmbar, shpVerde: TShape;
    grdLotes: TDBGrid;
    sbLotes: TScrollBar;
    btnScrollUp, btnScrollDown: TButton;
    btnMenuLotes, btnRefrescar, btnFinalizar, btnConfig, btnSalir, btnAlarmaOk: TButton;
    edtSimPeso: TEdit;
    tmrAlarma: TTimer;

    procedure ConstruirInterfaz;
    function CrearPanel(AParent: TWinControl; AAlign: TAlign; ASize: Integer; AColor: TColor): TPanel;
    function CrearLabel(AParent: TWinControl; const ACaption: string; AAlign: TAlign; ASize: Integer;
      AFontSize: Integer; AColor: TColor; ABold: Boolean = True): TLabel;
    function CrearBoton(AParent: TWinControl; const ACaption: string; AAlign: TAlign; ASize: Integer;
      AOnClick: TNotifyEvent): TButton;
    function CrearContador(AParent: TWinControl; const ATitulo: string; AColor: TColor): TLabel;
    procedure ConfigurarGrid;
    procedure AjustarColumnasGrid;
    procedure ActualizarScrollLotes;
    procedure MostrarPanelLotes(AMostrar: Boolean);

    procedure ConectarBD;
    procedure RefrescarLotes(AMantenerSeleccion: Boolean = False);
    procedure CargarLoteSeleccionado;
    procedure LimpiarLote;
    procedure MostrarInfoLote;
    procedure ActualizarContadores;
    procedure ActualizarDisposicionEstado;
    procedure SetSemaforo(AEstado: TEstadoSemaforo; const ATexto, ADetalle: string);
    procedure IniciarBascula;
    procedure EvaluarPesada(APesoNetoKg, APesoBrutoKg: Double);
    procedure ActivarAlarma(const AMensaje: string);
    procedure DetenerAlarma;
    procedure InicializarSonidos;
    procedure Sonar(AOk: Boolean);
    function PesoArticuloKg(AValor: Double): Double;

    // Eventos
    procedure WMAfterShow(var Msg: TMessage); message WM_AFTER_SHOW;
    procedure FormShowHandler(Sender: TObject);
    procedure FormResizeHandler(Sender: TObject);
    procedure FormCloseQueryHandler(Sender: TObject; var CanClose: Boolean);
    procedure BasculaPeso(Sender: TObject; APesoKg: Double; AEstable: Boolean; const ATrama: string);
    procedure BasculaEstado(Sender: TObject; AConectada: Boolean; const AMensaje: string);
    procedure DataSourceDataChange(Sender: TObject; Field: TField);
    procedure btnScrollUpClick(Sender: TObject);
    procedure btnScrollDownClick(Sender: TObject);
    procedure sbLotesScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
    procedure btnMenuLotesClick(Sender: TObject);
    procedure grdLotesCellClick(Column: TColumn);
    procedure grdLotesDblClick(Sender: TObject);
    procedure grdLotesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure grdLotesTitleClick(Column: TColumn);
    procedure btnRefrescarClick(Sender: TObject);
    procedure btnFinalizarClick(Sender: TObject);
    procedure btnConfigClick(Sender: TObject);
    procedure btnSalirClick(Sender: TObject);
    procedure btnAlarmaOkClick(Sender: TObject);
    procedure btnSimClick(Sender: TObject);
    procedure tmrAlarmaTimer(Sender: TObject);
  protected
    procedure CreateParams(var Params: TCreateParams); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  end;

var
  frmPesadoMain: TfrmPesadoMain;

implementation

uses
  Winapi.MMSystem, frm_ConfigBascula;

type
  TDBGridAccess = class(TDBGrid);

const
  CLR_FONDO = $00221810;
  CLR_PANEL = $0036281C;
  CLR_VERDE = $0050B000;
  CLR_VERDE_OFF = $00203A10;
  CLR_ROJO = $002020E0;
  CLR_ROJO_OFF = $00101040;
  CLR_AMBAR = $0000B0F0;
  CLR_AMBAR_OFF = $00103040;
  CLR_GRIS = $00606060;

  TAG_SIM_PONER = 1;
  TAG_SIM_TEORICO = 2;
  TAG_SIM_BAJO = 3;
  TAG_SIM_RETIRAR = 4;

{ TfrmPesadoMain }

procedure TfrmPesadoMain.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  Params.ExStyle := (Params.ExStyle or WS_EX_APPWINDOW) and (not WS_EX_TOOLWINDOW);
  Params.WndParent := 0;
end;

constructor TfrmPesadoMain.Create(AOwner: TComponent);
begin
  inherited CreateNew(AOwner);
  FPrimerShow := True;
  FConfig := TPesadoConfig.Cargar;
  FDB := TPesadoDB.Create(FConfig);
  FDataSource := TDataSource.Create(Self);
  FDataSource.DataSet := FDB.QryLotes;
  FDataSource.OnDataChange := DataSourceDataChange;
  FBascula := TBasculaSerial.Create;
  FBascula.OnPeso := BasculaPeso;
  FBascula.OnEstado := BasculaEstado;
  FArmado := True;

  Caption := 'Control de Pesado de Lotes';
  if not Application.Icon.Empty then
    Icon.Assign(Application.Icon);
  Color := CLR_FONDO;
  Font.Name := 'Segoe UI';
  Font.Size := 11;
  Position := poScreenCenter;
  Width := 1366;
  Height := 768;
  WindowState := wsMaximized;
  KeyPreview := True;
  OnShow := FormShowHandler;
  OnResize := FormResizeHandler;
  OnCloseQuery := FormCloseQueryHandler;

  tmrAlarma := TTimer.Create(Self);
  tmrAlarma.Enabled := False;
  tmrAlarma.Interval := 450;
  tmrAlarma.OnTimer := tmrAlarmaTimer;

  InicializarSonidos;
  ConstruirInterfaz;
  LimpiarLote;
end;

destructor TfrmPesadoMain.Destroy;
begin
  PlaySound(nil, 0, 0);
  // Detener primero el hilo de la báscula para que no lleguen lecturas a controles liberados
  FreeAndNil(FBascula);
  FDataSource.DataSet := nil;
  FreeAndNil(FDB);
  inherited;
end;

{ ---------------------------------------------------------------------------
  Construcción de la interfaz
  --------------------------------------------------------------------------- }

function TfrmPesadoMain.CrearPanel(AParent: TWinControl; AAlign: TAlign; ASize: Integer; AColor: TColor): TPanel;
begin
  Result := TPanel.Create(Self);
  Result.Parent := AParent;
  Result.Align := AAlign;
  Result.BevelOuter := bvNone;
  Result.ParentBackground := False;
  Result.Color := AColor;
  Result.Caption := '';
  if AAlign in [alTop, alBottom] then
    Result.Height := ASize
  else if AAlign in [alLeft, alRight] then
    Result.Width := ASize;
end;

function TfrmPesadoMain.CrearLabel(AParent: TWinControl; const ACaption: string; AAlign: TAlign;
  ASize: Integer; AFontSize: Integer; AColor: TColor; ABold: Boolean): TLabel;
begin
  Result := TLabel.Create(Self);
  Result.Parent := AParent;
  Result.AutoSize := False;
  Result.Align := AAlign;
  if AAlign in [alTop, alBottom] then
    Result.Height := ASize;
  Result.Caption := ACaption;
  Result.Font.Name := 'Segoe UI';
  Result.Font.Size := AFontSize;
  Result.Font.Color := AColor;
  if ABold then
    Result.Font.Style := [fsBold];
  Result.Layout := tlCenter;
  Result.Transparent := True;
  Result.AlignWithMargins := True;
  Result.Margins.Left := 12;
  Result.Margins.Right := 12;
  Result.Margins.Top := 0;
  Result.Margins.Bottom := 0;
end;

function TfrmPesadoMain.CrearBoton(AParent: TWinControl; const ACaption: string; AAlign: TAlign;
  ASize: Integer; AOnClick: TNotifyEvent): TButton;
begin
  Result := TButton.Create(Self);
  Result.Parent := AParent;
  Result.Align := AAlign;
  if AAlign in [alTop, alBottom] then
    Result.Height := ASize
  else
    Result.Width := ASize;
  Result.Caption := ACaption;
  Result.Font.Name := 'Segoe UI';
  Result.Font.Size := 14;
  Result.Font.Style := [fsBold];
  Result.AlignWithMargins := True;
  Result.Margins.SetBounds(6, 6, 6, 6);
  Result.OnClick := AOnClick;
end;

function TfrmPesadoMain.CrearContador(AParent: TWinControl; const ATitulo: string; AColor: TColor): TLabel;
var
  LPnl: TPanel;
begin
  LPnl := CrearPanel(AParent, alLeft, 200, $002E2116);
  LPnl.AlignWithMargins := True;
  LPnl.Margins.SetBounds(4, 3, 4, 3);
  CrearLabel(LPnl, ATitulo, alTop, 26, 12, $00F0E8E0).Alignment := taCenter;
  Result := CrearLabel(LPnl, '0', alClient, 0, 82, AColor);
  Result.Alignment := taCenter;
end;

procedure TfrmPesadoMain.ConstruirInterfaz;
var
  LPnl, LPnlBotones, LPnlLuces: TPanel;
  LBtn: TButton;
begin
  // ---------- Cabecera compacta ----------
  pnlTop := CrearPanel(Self, alTop, 48, $001A130D);
  btnMenuLotes := CrearBoton(pnlTop, '☰  LOTES', alLeft, 165, btnMenuLotesClick);
  btnMenuLotes.Font.Size := 12;
  btnMenuLotes.Margins.SetBounds(6, 4, 6, 4);
  btnSalir := CrearBoton(pnlTop, 'SALIR', alRight, 120, btnSalirClick);
  btnSalir.Font.Size := 12;
  btnSalir.Margins.SetBounds(4, 4, 6, 4);
  btnConfig := CrearBoton(pnlTop, 'CONFIG. BÁSCULA', alRight, 200, btnConfigClick);
  btnConfig.Font.Size := 12;
  btnConfig.Margins.SetBounds(4, 4, 4, 4);
  lblTitulo := CrearLabel(pnlTop, 'CONTROL DE PESADO DE LOTES', alClient, 0, 17, clWhite);

  // ---------- Barra de estado inferior compacta ----------
  pnlStatus := CrearPanel(Self, alBottom, 24, $00201C18);
  lblStatusDB := CrearLabel(pnlStatus, 'BD: desconectada', alRight, 0, 9, clSilver, False);
  lblStatusDB.Width := 420;
  lblStatusDB.Alignment := taRightJustify;
  lblStatusCom := CrearLabel(pnlStatus, 'Báscula: detenida', alClient, 0, 9, clSilver, False);

  // ---------- Panel izquierdo desplegable: lotes (oculto por defecto) ----------
  pnlLeft := CrearPanel(Self, alLeft, 700, $0028221E);
  pnlLeft.AlignWithMargins := True;
  pnlLeft.Margins.SetBounds(6, 6, 4, 6);
  pnlLeft.Visible := False;
  CrearLabel(pnlLeft, 'SELECCIONE UN LOTE PENDIENTE DE PESADO', alTop, 38, 14, CLR_AMBAR);

  LPnlBotones := CrearPanel(pnlLeft, alBottom, 56, $0028221E);
  btnRefrescar := CrearBoton(LPnlBotones, 'REFRESCAR LISTA DE LOTES', alClient, 0, btnRefrescarClick);
  btnRefrescar.Font.Size := 13;

  pnlGridArea := CrearPanel(pnlLeft, alClient, 0, $0028221E);
  pnlGridArea.BevelOuter := bvNone;

  // Panel lateral con scroll táctil ampliado y botones grandes
  pnlScrollLotes := CrearPanel(pnlGridArea, alRight, 54, $0028221E);
  pnlScrollLotes.BevelOuter := bvNone;
  pnlScrollLotes.AlignWithMargins := True;
  pnlScrollLotes.Margins.SetBounds(2, 4, 4, 4);

  btnScrollUp := CrearBoton(pnlScrollLotes, '▲', alTop, 75, btnScrollUpClick);
  btnScrollUp.Font.Size := 22;
  btnScrollUp.Font.Style := [fsBold];

  btnScrollDown := CrearBoton(pnlScrollLotes, '▼', alBottom, 75, btnScrollDownClick);
  btnScrollDown.Font.Size := 22;
  btnScrollDown.Font.Style := [fsBold];

  sbLotes := TScrollBar.Create(Self);
  sbLotes.Parent := pnlScrollLotes;
  sbLotes.Kind := sbVertical;
  sbLotes.Align := alClient;
  sbLotes.Width := 54;
  sbLotes.OnScroll := sbLotesScroll;

  grdLotes := TDBGrid.Create(Self);
  grdLotes.Parent := pnlGridArea;
  grdLotes.Align := alClient;
  grdLotes.AlignWithMargins := True;
  grdLotes.Margins.SetBounds(6, 4, 2, 4);
  grdLotes.DataSource := FDataSource;
  grdLotes.ReadOnly := True;
  grdLotes.Options := [dgTitles, dgTitleClick, dgColumnResize, dgColLines, dgRowLines, dgRowSelect, dgAlwaysShowSelection, dgCancelOnExit];
  grdLotes.Font.Size := 13;
  grdLotes.TitleFont.Size := 12;
  grdLotes.TitleFont.Style := [fsBold];
  grdLotes.OnCellClick := grdLotesCellClick;
  grdLotes.OnDblClick := grdLotesDblClick;
  grdLotes.OnKeyDown := grdLotesKeyDown;
  grdLotes.OnTitleClick := grdLotesTitleClick;
  TDBGridAccess(grdLotes).DefaultRowHeight := 44;
  ConfigurarGrid;

  // ---------- Panel derecho: zona de pesaje (ocupa toda la pantalla cuando pnlLeft está oculto) ----------
  pnlRight := CrearPanel(Self, alClient, 0, CLR_FONDO);
  pnlRight.AlignWithMargins := True;
  pnlRight.Margins.SetBounds(6, 6, 6, 6);

  pnlInfo := CrearPanel(pnlRight, alTop, 90, CLR_PANEL);
  pnlInfoFila1 := CrearPanel(pnlInfo, alTop, 58, CLR_PANEL);
  pnlInfoFila1.BevelOuter := bvNone;
  pnlInfoFila1.Margins.SetBounds(0, 0, 0, 0);

  lblArticulo := CrearLabel(pnlInfoFila1, '', alLeft, 0, 15, clWhite);
  lblArticulo.AutoSize := True;
  lblArticulo.Layout := tlCenter;
  lblArticulo.Left := 0;

  lblLote := CrearLabel(pnlInfoFila1, '', alLeft, 0, 30, clWhite);
  lblLote.AutoSize := True;
  lblLote.Layout := tlCenter;
  lblLote.Margins.Left := 24;
  lblLote.Left := 5000;

  lblNominal := CrearLabel(pnlInfo, '', alTop, 28, 11, CLR_AMBAR, False);
  lblNominal.Layout := tlCenter;

  // Panel de contadores de unidades debajo de la información del lote
  pnlContadores := CrearPanel(pnlRight, alTop, 170, CLR_FONDO);
  pnlContadores.Top := pnlInfo.Top + pnlInfo.Height + 1;
  lblTeoricas := CrearContador(pnlContadores, 'UDS. FABRICADAS', clWhite);
  lblCorrectas := CrearContador(pnlContadores, 'PESADAS CORRECTAS', CLR_VERDE);
  lblRechazadas := CrearContador(pnlContadores, 'RECHAZADAS', CLR_ROJO);
  lblPendientes := CrearContador(pnlContadores, 'PENDIENTES', CLR_AMBAR);
  lblPendientes.Parent.Align := alClient;

  // Botón de finalizar lote destacado en la parte inferior de la zona de pesado
  btnFinalizar := CrearBoton(pnlRight, 'FINALIZAR LOTE', alBottom, 56, btnFinalizarClick);
  btnFinalizar.Font.Size := 16;
  btnFinalizar.Margins.SetBounds(4, 4, 4, 4);

  // Panel de simulación (sólo visible en modo simulado)
  pnlSim := CrearPanel(pnlRight, alBottom, 46, $00504020);
  CrearLabel(pnlSim, 'SIMULADOR  peso (kg):', alLeft, 0, 11, clYellow).Width := 200;
  edtSimPeso := TEdit.Create(Self);
  edtSimPeso.Parent := pnlSim;
  edtSimPeso.Align := alLeft;
  edtSimPeso.Width := 110;
  edtSimPeso.AlignWithMargins := True;
  edtSimPeso.Margins.SetBounds(4, 6, 4, 6);
  edtSimPeso.Font.Size := 13;
  edtSimPeso.Text := '1.000';
  LBtn := CrearBoton(pnlSim, 'PONER', alLeft, 110, btnSimClick);
  LBtn.Tag := TAG_SIM_PONER;
  LBtn.Font.Size := 12;
  LBtn.Margins.SetBounds(4, 4, 4, 4);
  LBtn := CrearBoton(pnlSim, 'TEÓRICO', alLeft, 120, btnSimClick);
  LBtn.Tag := TAG_SIM_TEORICO;
  LBtn.Font.Size := 12;
  LBtn.Margins.SetBounds(4, 4, 4, 4);
  LBtn := CrearBoton(pnlSim, '-5 %', alLeft, 100, btnSimClick);
  LBtn.Tag := TAG_SIM_BAJO;
  LBtn.Font.Size := 12;
  LBtn.Margins.SetBounds(4, 4, 4, 4);
  LBtn := CrearBoton(pnlSim, 'RETIRAR', alLeft, 120, btnSimClick);
  LBtn.Tag := TAG_SIM_RETIRAR;
  LBtn.Font.Size := 12;
  LBtn.Margins.SetBounds(4, 4, 4, 4);
  pnlSim.Visible := False;

  // Zona central principal: semáforo + visor gigante de peso
  pnlCentro := CrearPanel(pnlRight, alClient, 0, CLR_FONDO);

  pnlSemaforo := CrearPanel(pnlCentro, alLeft, 160, $00151210);
  pnlSemaforo.AlignWithMargins := True;
  pnlSemaforo.Margins.SetBounds(0, 4, 6, 4);
  LPnlLuces := pnlSemaforo;
  shpRojo := TShape.Create(Self);
  shpRojo.Parent := LPnlLuces;
  shpRojo.Shape := stCircle;
  shpRojo.Pen.Color := clBlack;
  shpRojo.Pen.Width := 3;
  shpAmbar := TShape.Create(Self);
  shpAmbar.Parent := LPnlLuces;
  shpAmbar.Shape := stCircle;
  shpAmbar.Pen.Color := clBlack;
  shpAmbar.Pen.Width := 3;
  shpVerde := TShape.Create(Self);
  shpVerde.Parent := LPnlLuces;
  shpVerde.Shape := stCircle;
  shpVerde.Pen.Color := clBlack;
  shpVerde.Pen.Width := 3;

  LPnl := CrearPanel(pnlCentro, alClient, 0, CLR_FONDO);
  LPnl.AlignWithMargins := True;
  LPnl.Margins.SetBounds(0, 4, 0, 4);

  // Panel de estado compacto debajo del visor de peso
  pnlEstado := CrearPanel(LPnl, alBottom, 74, CLR_GRIS);
  pnlEstado.AlignWithMargins := True;
  pnlEstado.Margins.SetBounds(0, 6, 0, 0);
  lblUltima := CrearLabel(pnlEstado, '', alBottom, 18, 10, clWhite, False);
  lblUltima.Alignment := taCenter;
  lblEstadoDetalle := CrearLabel(pnlEstado, '', alBottom, 22, 13, clWhite);
  lblEstadoDetalle.Alignment := taCenter;
  lblEstado := CrearLabel(pnlEstado, '', alClient, 0, 20, clWhite);
  lblEstado.Alignment := taCenter;
  lblEstado.WordWrap := True;

  // Panel PRINCIPAL: visor de peso capturado de la báscula (ocupa todo el espacio central disponible)
  pnlPesoDisplay := CrearPanel(LPnl, alClient, 0, clBlack);
  lblPeso := CrearLabel(pnlPesoDisplay, '0.000 kg', alClient, 0, 84, $0000FF40);
  lblPeso.Font.Name := 'Consolas';
  lblPeso.Alignment := taCenter;
  lblEstable := CrearLabel(pnlPesoDisplay, '', alBottom, 26, 13, clSilver);
  lblEstable.Alignment := taCenter;
  lblBruto := CrearLabel(pnlPesoDisplay, '', alTop, 20, 10, clGray, False);
  lblBruto.Alignment := taRightJustify;

  // Alarma de rechazo a PANTALLA COMPLETA (cubre toda la ventana de la aplicación)
  pnlAlarma := CrearPanel(Self, alNone, 0, CLR_ROJO);
  pnlAlarma.Visible := False;
  CrearLabel(pnlAlarma, '¡ALARMA DE PESO INSUFICIENTE!', alTop, 96, 36, clYellow).Alignment := taCenter;
  btnAlarmaOk := CrearBoton(pnlAlarma, 'ARTÍCULO RETIRADO Y DESECHADO  (ACEPTAR)', alBottom, 120, btnAlarmaOkClick);
  btnAlarmaOk.Font.Size := 24;
  btnAlarmaOk.Margins.SetBounds(80, 16, 80, 32);
  lblAlarma := CrearLabel(pnlAlarma, '', alClient, 0, 44, clWhite);
  lblAlarma.Alignment := taCenter;
  lblAlarma.WordWrap := True;

  FormResizeHandler(nil);
end;

procedure TfrmPesadoMain.ConfigurarGrid;

  procedure AddCol(const AField, ATitle: string; AWidth: Integer; AAlign: TAlignment = taLeftJustify);
  var
    LCol: TColumn;
  begin
    LCol := grdLotes.Columns.Add;
    LCol.FieldName := AField;
    LCol.Title.Caption := ATitle;
    LCol.Width := AWidth;
    LCol.Alignment := AAlign;
  end;

begin
  grdLotes.Columns.Clear;
  AddCol('articulo', 'Artículo', 320);
  AddCol('codigo_antiguo', 'Lote', 125);
  AddCol('fecha_lote', 'Fecha', 105, taCenter);
  AddCol('cantidad_producida', 'Uds.', 65, taRightJustify);
  AddCol('pesadas_ok', 'Pes.', 60, taRightJustify);
  AddCol('peso_teorico', 'Peso', 70, taRightJustify);
  AddCol('formato', 'Formato', 110);
end;

procedure TfrmPesadoMain.AjustarColumnasGrid;
var
  I, LColW, LTotalFijo, LAnchoDisp, LAnchoNecesarioLeft, LIdxArticulo: Integer;
  LCol: TColumn;
  LField: TField;
  LBM: TBookmark;
  LTexto: string;
  LAnchos: array of Integer;
begin
  if not Assigned(grdLotes) or (grdLotes.Columns.Count = 0) then
    Exit;

  SetLength(LAnchos, grdLotes.Columns.Count);
  LIdxArticulo := -1;

  // 1. Medir ancho de títulos
  grdLotes.Canvas.Font.Assign(grdLotes.TitleFont);
  for I := 0 to grdLotes.Columns.Count - 1 do
  begin
    LCol := grdLotes.Columns[I];
    LAnchos[I] := grdLotes.Canvas.TextWidth(LCol.Title.Caption) + 20;
    if SameText(LCol.FieldName, 'articulo') then
      LIdxArticulo := I;
  end;

  // 2. Medir ancho real de todas las celdas del dataset
  if Assigned(FDB) and FDB.QryLotes.Active and (not FDB.QryLotes.IsEmpty) then
  begin
    grdLotes.Canvas.Font.Assign(grdLotes.Font);
    FDB.QryLotes.DisableControls;
    try
      LBM := FDB.QryLotes.GetBookmark;
      try
        FDB.QryLotes.First;
        while not FDB.QryLotes.Eof do
        begin
          for I := 0 to grdLotes.Columns.Count - 1 do
          begin
            LField := FDB.QryLotes.FindField(grdLotes.Columns[I].FieldName);
            if Assigned(LField) then
            begin
              LTexto := LField.DisplayText;
              LColW := grdLotes.Canvas.TextWidth(LTexto) + 20;
              if LColW > LAnchos[I] then
                LAnchos[I] := LColW;
            end;
          end;
          FDB.QryLotes.Next;
        end;
        if FDB.QryLotes.BookmarkValid(LBM) then
          FDB.QryLotes.GotoBookmark(LBM);
      finally
        FDB.QryLotes.FreeBookmark(LBM);
      end;
    finally
      FDB.QryLotes.EnableControls;
    end;
  end
  else
  begin
    for I := 0 to grdLotes.Columns.Count - 1 do
      if SameText(grdLotes.Columns[I].FieldName, 'articulo') then
        LAnchos[I] := 300
      else if SameText(grdLotes.Columns[I].FieldName, 'codigo_antiguo') then
        LAnchos[I] := 125
      else if SameText(grdLotes.Columns[I].FieldName, 'fecha_lote') then
        LAnchos[I] := 105
      else if SameText(grdLotes.Columns[I].FieldName, 'formato') then
        LAnchos[I] := 105
      else
        LAnchos[I] := 65;
  end;

  // 3. Ajustar ancho del panel izquierdo para que todas las columnas quepan completas
  LTotalFijo := 0;
  for I := 0 to High(LAnchos) do
    if I <> LIdxArticulo then
      Inc(LTotalFijo, LAnchos[I]);

  if Assigned(pnlLeft) and (ClientWidth > 0) then
  begin
    LAnchoNecesarioLeft := LTotalFijo + LAnchos[Max(0, LIdxArticulo)] + 54 + GetSystemMetrics(SM_CXVSCROLL) + 40;
    pnlLeft.Width := EnsureRange(LAnchoNecesarioLeft, Round(ClientWidth * 0.50), Round(ClientWidth * 0.68));
  end;

  // 4. Asignar anchos y expandir la columna Artículo para cubrir todo el ancho del DBGrid
  LAnchoDisp := grdLotes.ClientWidth - GetSystemMetrics(SM_CXVSCROLL) - (grdLotes.Columns.Count + 2);
  for I := 0 to High(LAnchos) do
    if I <> LIdxArticulo then
      grdLotes.Columns[I].Width := LAnchos[I];

  if LIdxArticulo >= 0 then
    grdLotes.Columns[LIdxArticulo].Width := Max(200, LAnchoDisp - LTotalFijo);

  ActualizarScrollLotes;
end;

procedure TfrmPesadoMain.MostrarPanelLotes(AMostrar: Boolean);
begin
  if not Assigned(pnlLeft) then
    Exit;
  pnlLeft.Visible := AMostrar;
  if AMostrar then
  begin
    btnMenuLotes.Caption := '✕  OCULTAR LOTES';
    AjustarColumnasGrid;
    if grdLotes.CanFocus then
      grdLotes.SetFocus;
  end
  else
    btnMenuLotes.Caption := '☰  LOTES';
  FormResizeHandler(nil);
end;

procedure TfrmPesadoMain.ActualizarDisposicionEstado;
var
  LAltoUtil, LAltoCentro, LAltoDispPeso, LFontContador, LFontPeso, LMaxArtWidth: Integer;
begin
  if not Assigned(pnlPesoDisplay) or not Assigned(pnlEstado) then
    Exit;

  LAltoUtil := Max(480, ClientHeight);

  // Compactar pnlInfo (Fila 1: Descripción + Lote el doble de grande; Fila 2: Formato y Peso Nominal)
  if Assigned(pnlInfo) and Assigned(pnlInfoFila1) and Assigned(lblArticulo) and Assigned(lblLote) and Assigned(lblNominal) then
  begin
    lblNominal.Visible := lblNominal.Caption <> '';
    if lblNominal.Visible then
    begin
      pnlInfo.Height := EnsureRange(Round(LAltoUtil * 0.14), 86, 110);
      pnlInfoFila1.Height := Round(pnlInfo.ClientHeight * 0.65);
      lblNominal.Height := pnlInfo.ClientHeight - pnlInfoFila1.Height;
      lblNominal.Font.Size := EnsureRange(Round(lblNominal.Height * 0.44), 10, 13);
    end
    else
    begin
      pnlInfo.Height := EnsureRange(Round(LAltoUtil * 0.10), 60, 80);
      pnlInfoFila1.Height := pnlInfo.ClientHeight;
    end;

    // Altura y tamaño de fuentes: El lote debe aparecer el doble de grande que la descripción del artículo
    lblArticulo.Font.Size := EnsureRange(Round(pnlInfoFila1.Height * 0.30), 13, 25);
    lblLote.Font.Size := lblArticulo.Font.Size * 2; // EXACTAMENTE EL DOBLE DE GRANDE
    lblLote.Font.Color := clWhite;
    lblArticulo.Left := 0;
    lblLote.Left := 5000;

    // Evitar desbordamiento horizontal si la descripción del artículo es excepcionalmente larga
    if (pnlInfoFila1.ClientWidth > 0) and (lblLote.Caption <> '') then
    begin
      LMaxArtWidth := pnlInfoFila1.ClientWidth - lblLote.Width - lblLote.Margins.Left - 32;
      if (LMaxArtWidth > 150) and (lblArticulo.Width > LMaxArtWidth) then
      begin
        lblArticulo.AutoSize := False;
        lblArticulo.Width := LMaxArtWidth;
      end
      else
        lblArticulo.AutoSize := True;
    end
    else
      lblArticulo.AutoSize := True;

    if Assigned(pnlContadores) then
      pnlContadores.Top := pnlInfo.Top + pnlInfo.Height + 1;
  end;

  // Mostrar/ocultar etiquetas secundarias vacías para que no roben altura al texto principal
  if Assigned(lblBruto) then
    lblBruto.Visible := lblBruto.Caption <> '';
  if Assigned(lblEstadoDetalle) then
    lblEstadoDetalle.Visible := lblEstadoDetalle.Caption <> '';
  if Assigned(lblUltima) then
    lblUltima.Visible := lblUltima.Caption <> '';

  // El panel PRINCIPAL es pnlPesoDisplay (alClient, ~75% de la zona central);
  // pnlEstado (alBottom) queda como franja compacta (~25% de la zona central)
  if Assigned(pnlEstado.Parent) and (pnlEstado.Parent.ClientHeight > 60) then
  begin
    LAltoCentro := pnlEstado.Parent.ClientHeight - 6;
    if (Assigned(lblEstadoDetalle) and lblEstadoDetalle.Visible) or
       (Assigned(lblUltima) and lblUltima.Visible) then
      pnlEstado.Height := EnsureRange(Round(LAltoCentro * 0.27), 58, 92)
    else
      pnlEstado.Height := EnsureRange(Round(LAltoCentro * 0.21), 44, 72);
  end;

  // Escalar fuentes y alturas internas del visor principal de peso según su altura real
  if pnlPesoDisplay.ClientHeight > 0 then
  begin
    if Assigned(lblBruto) and lblBruto.Visible then
    begin
      lblBruto.Height := EnsureRange(Round(pnlPesoDisplay.ClientHeight * 0.12), 16, 22);
      lblBruto.Font.Size := EnsureRange(Round(lblBruto.Height * 0.45), 8, 11);
    end;
    if Assigned(lblEstable) then
    begin
      lblEstable.Height := EnsureRange(Round(pnlPesoDisplay.ClientHeight * 0.15), 20, 30);
      lblEstable.Font.Size := EnsureRange(Round(lblEstable.Height * 0.48), 10, 14);
    end;
    if Assigned(lblPeso) then
    begin
      LAltoDispPeso := pnlPesoDisplay.ClientHeight - lblEstable.Height;
      if Assigned(lblBruto) and lblBruto.Visible then
        Dec(LAltoDispPeso, lblBruto.Height);
      LFontPeso := EnsureRange(
        Min(Round(LAltoDispPeso * 0.56), Round(Max(300, pnlPesoDisplay.ClientWidth) * 0.13)),
        36, 108);
      lblPeso.Font.Size := LFontPeso;
    end;
  end;

  // Escalar fuentes y alturas internas del panel compacto de estado del semáforo
  if pnlEstado.ClientHeight > 0 then
  begin
    if Assigned(lblUltima) and lblUltima.Visible then
    begin
      lblUltima.Height := EnsureRange(Round(pnlEstado.ClientHeight * 0.24), 15, 22);
      lblUltima.Font.Size := EnsureRange(Round(lblUltima.Height * 0.46), 8, 10);
      lblUltima.Top := pnlEstado.ClientHeight;
    end;
    if Assigned(lblEstadoDetalle) and lblEstadoDetalle.Visible then
    begin
      lblEstadoDetalle.Height := EnsureRange(Round(pnlEstado.ClientHeight * 0.30), 18, 28);
      lblEstadoDetalle.Font.Size := EnsureRange(Round(lblEstadoDetalle.Height * 0.46), 10, 13);
      lblEstadoDetalle.Top := 0;
    end;
    if Assigned(lblEstado) then
    begin
      if (Assigned(lblEstadoDetalle) and lblEstadoDetalle.Visible) or
         (Assigned(lblUltima) and lblUltima.Visible) then
        lblEstado.Font.Size := EnsureRange(Round(pnlEstado.ClientHeight * 0.23), 12, 22)
      else
        lblEstado.Font.Size := EnsureRange(Round(pnlEstado.ClientHeight * 0.34), 14, 24);
    end;
  end;

  // Escalar cifras de los contadores según el alto de pnlContadores (reducido un 25 %)
  if Assigned(pnlContadores) and Assigned(lblTeoricas) and (pnlContadores.ClientHeight > 30) then
  begin
    LFontContador := EnsureRange(Round((pnlContadores.ClientHeight - 30) * 0.54), 54, 102);
    lblTeoricas.Font.Size := LFontContador;
    lblCorrectas.Font.Size := LFontContador;
    lblRechazadas.Font.Size := LFontContador;
    lblPendientes.Font.Size := LFontContador + 3;
  end;
end;

procedure TfrmPesadoMain.FormResizeHandler(Sender: TObject);
var
  LDiam, LTop, LHueco, LAltoUtil: Integer;
begin
  LAltoUtil := Max(480, ClientHeight);

  // 1. Paneles superiores e inferiores compactos para dar el máximo protagonismo al visor de peso
  if Assigned(pnlTop) then
  begin
    pnlTop.Height := EnsureRange(Round(LAltoUtil * 0.068), 42, 54);
    if Assigned(lblTitulo) then
      lblTitulo.Font.Size := EnsureRange(Round(pnlTop.Height * 0.33), 14, 18);
  end;

  if Assigned(pnlStatus) then
    pnlStatus.Height := EnsureRange(Round(LAltoUtil * 0.032), 20, 26);

  if Assigned(pnlContadores) then
    pnlContadores.Height := EnsureRange(Round(LAltoUtil * 0.25), 150, 210);

  if Assigned(btnFinalizar) then
  begin
    btnFinalizar.Height := EnsureRange(Round(LAltoUtil * 0.080), 48, 64);
    btnFinalizar.Font.Size := EnsureRange(Round(btnFinalizar.Height * 0.32), 14, 18);
  end;

  if Assigned(pnlSim) then
    pnlSim.Height := EnsureRange(Round(LAltoUtil * 0.065), 38, 48);

  if Assigned(pnlLeft) and pnlLeft.Visible then
    AjustarColumnasGrid;

  if Assigned(pnlContadores) and Assigned(lblTeoricas) then
  begin
    lblTeoricas.Parent.Width := Max(140, pnlContadores.Width div 4 - 8);
    lblCorrectas.Parent.Width := lblTeoricas.Parent.Width;
    lblRechazadas.Parent.Width := lblTeoricas.Parent.Width;
  end;

  ActualizarDisposicionEstado;

  if Assigned(pnlSemaforo) and Assigned(shpRojo) then
  begin
    if Assigned(pnlCentro) and (pnlCentro.ClientHeight > 60) then
      pnlSemaforo.Width := EnsureRange(Round(pnlCentro.ClientHeight * 0.44), 100, 175);
    LDiam := Min(pnlSemaforo.Width - 20, (pnlSemaforo.Height - 24) div 3);
    LDiam := Max(LDiam, 26);
    LHueco := Max(4, (pnlSemaforo.Height - 3 * LDiam) div 4);
    LTop := LHueco;
    shpRojo.SetBounds((pnlSemaforo.Width - LDiam) div 2, LTop, LDiam, LDiam);
    Inc(LTop, LDiam + LHueco);
    shpAmbar.SetBounds((pnlSemaforo.Width - LDiam) div 2, LTop, LDiam, LDiam);
    Inc(LTop, LDiam + LHueco);
    shpVerde.SetBounds((pnlSemaforo.Width - LDiam) div 2, LTop, LDiam, LDiam);
  end;

  if Assigned(pnlAlarma) then
    pnlAlarma.SetBounds(0, 0, ClientWidth, ClientHeight);
end;

{ ---------------------------------------------------------------------------
  Arranque, base de datos y báscula
  --------------------------------------------------------------------------- }

procedure TfrmPesadoMain.FormShowHandler(Sender: TObject);
begin
  if not FPrimerShow then
    Exit;
  FPrimerShow := False;
  FormResizeHandler(nil);
  // Diferir la conexión a BD y báscula hasta que VCL termine CMShowingChanged
  // (ShowWindow + registro del botón en la barra de tareas de Windows).
  PostMessage(Handle, WM_AFTER_SHOW, 0, 0);
end;

procedure TfrmPesadoMain.WMAfterShow(var Msg: TMessage);
begin
  Update;
  IniciarBascula;
  ConectarBD;
end;

procedure TfrmPesadoMain.ConectarBD;
begin
  Screen.Cursor := crHourGlass;
  try
    try
      FDB.Conectar;
      FDB.AsegurarEsquema;
      lblStatusDB.Caption := Format('BD: %s @ %s', [FDB.Conexion.Params.Values['Database'],
        FDB.Conexion.Params.Values['Server']]);
      lblStatusDB.Font.Color := CLR_VERDE;
      RefrescarLotes;
    except
      on E: Exception do
      begin
        lblStatusDB.Caption := 'BD: ERROR DE CONEXIÓN';
        lblStatusDB.Font.Color := CLR_ROJO;
        Screen.Cursor := crDefault;
        MessageDlg('No se pudo conectar con la base de datos:' + sLineBreak + E.Message + sLineBreak + sLineBreak +
          'Revise la configuración de conexión en CONFIG. BÁSCULA y pulse REFRESCAR para reintentar.', mtError, [mbOK], 0);
      end;
    end;
  finally
    Screen.Cursor := crDefault;
  end;
end;

procedure TfrmPesadoMain.RefrescarLotes(AMantenerSeleccion: Boolean);
var
  LIdActual: Integer;
  LField: TField;
begin
  if not FDB.Conexion.Connected then
  begin
    ConectarBD;
    Exit;
  end;
  LIdActual := 0;
  if AMantenerSeleccion and FLoteActivo then
    LIdActual := FIdStock
  else if AMantenerSeleccion and FDB.QryLotes.Active and not FDB.QryLotes.IsEmpty then
    LIdActual := FDB.QryLotes.FieldByName('id_stock_envasado').AsInteger;

  FRefrescandoLotes := True;
  try
    FDB.RefrescarLotes;

    LField := FDB.QryLotes.FindField('fecha_lote');
    if LField is TDateTimeField then
      TDateTimeField(LField).DisplayFormat := 'dd/mm/yyyy';
    LField := FDB.QryLotes.FindField('peso_teorico');
    if LField is TNumericField then
      TNumericField(LField).DisplayFormat := '0.000';
    LField := FDB.QryLotes.FindField('cantidad_producida');
    if LField is TNumericField then
      TNumericField(LField).DisplayFormat := '0';

    if FSortField <> '' then
    begin
      if FSortDesc then
        FDB.QryLotes.IndexFieldNames := FSortField + ':D'
      else
        FDB.QryLotes.IndexFieldNames := FSortField;
    end;

    if pnlLeft.Visible then
      AjustarColumnasGrid;

    if LIdActual > 0 then
      FDB.QryLotes.Locate('id_stock_envasado', LIdActual, []);
  finally
    FRefrescandoLotes := False;
  end;

  if FDB.QryLotes.IsEmpty then
    LimpiarLote;
end;

procedure TfrmPesadoMain.IniciarBascula;
begin
  pnlSim.Visible := FConfig.Simulado;
  FArmado := True;
  FBascula.Iniciar(FConfig);
end;

function TfrmPesadoMain.PesoArticuloKg(AValor: Double): Double;
begin
  if FConfig.UnidadArticulo = upGramos then
    Result := AValor / 1000
  else
    Result := AValor;
end;

{ ---------------------------------------------------------------------------
  Gestión del lote y navegación táctil de lista
  --------------------------------------------------------------------------- }

procedure TfrmPesadoMain.ActualizarScrollLotes;
begin
  if Assigned(sbLotes) and Assigned(FDB) and FDB.QryLotes.Active then
  begin
    sbLotes.Min := 1;
    sbLotes.Max := Max(1, FDB.QryLotes.RecordCount);
    if FDB.QryLotes.RecNo >= 1 then
      sbLotes.Position := FDB.QryLotes.RecNo;
  end;
end;

procedure TfrmPesadoMain.DataSourceDataChange(Sender: TObject; Field: TField);
begin
  if not FRefrescandoLotes then
    ActualizarScrollLotes;
end;

procedure TfrmPesadoMain.btnScrollUpClick(Sender: TObject);
begin
  if Assigned(FDB) and FDB.QryLotes.Active and not FDB.QryLotes.Bof then
  begin
    FDB.QryLotes.MoveBy(-5);
    ActualizarScrollLotes;
  end;
end;

procedure TfrmPesadoMain.btnScrollDownClick(Sender: TObject);
begin
  if Assigned(FDB) and FDB.QryLotes.Active and not FDB.QryLotes.Eof then
  begin
    FDB.QryLotes.MoveBy(5);
    ActualizarScrollLotes;
  end;
end;

procedure TfrmPesadoMain.sbLotesScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
begin
  if Assigned(FDB) and FDB.QryLotes.Active and (FDB.QryLotes.RecordCount > 0) then
  begin
    if (ScrollPos >= 1) and (ScrollPos <= FDB.QryLotes.RecordCount) then
    begin
      FDB.QryLotes.RecNo := ScrollPos;
      if Assigned(grdLotes) and grdLotes.CanFocus then
        grdLotes.SetFocus;
    end;
  end;
end;

procedure TfrmPesadoMain.LimpiarLote;
begin
  FLoteActivo := False;
  FIdStock := 0;
  FIdLote := 0;
  FIdArticulo := 0;
  FCodigoLote := '';
  FArticulo := '';
  FFormato := '';
  FPesoTeoricoKg := 0;
  FUnidadesTeoricas := 0;
  FPesadasOK := 0;
  FRechazos := 0;
  lblArticulo.Caption := 'NINGÚN LOTE SELECCIONADO';
  lblLote.Caption := '';
  lblLote.Font.Color := clWhite;
  lblNominal.Caption := 'Pulse el botón "☰ LOTES" arriba a la izquierda para desplegar y elegir un lote';
  lblUltima.Caption := '';
  btnFinalizar.Enabled := False;
  ActualizarContadores;
  SetSemaforo(esEspera, 'PULSE "☰ LOTES" PARA SELECCIONAR LOTE', '');
end;

procedure TfrmPesadoMain.btnMenuLotesClick(Sender: TObject);
begin
  if FAlarmaActiva then
    Exit;
  if not pnlLeft.Visible then
  begin
    if FDB.Conexion.Connected then
      RefrescarLotes(True);
    MostrarPanelLotes(True);
  end
  else
    MostrarPanelLotes(False);
end;

procedure TfrmPesadoMain.grdLotesCellClick(Column: TColumn);
begin
  if FRefrescandoLotes or FAlarmaActiva then
    Exit;
  CargarLoteSeleccionado;
  if FLoteActivo then
    MostrarPanelLotes(False);
end;

procedure TfrmPesadoMain.grdLotesDblClick(Sender: TObject);
begin
  if FRefrescandoLotes or FAlarmaActiva then
    Exit;
  CargarLoteSeleccionado;
  if FLoteActivo then
    MostrarPanelLotes(False);
end;

procedure TfrmPesadoMain.grdLotesTitleClick(Column: TColumn);
var
  LField, LTitle: string;
  I: Integer;
begin
  if (Column = nil) or (Column.FieldName = '') then
    Exit;
  if not Assigned(FDataSource) or not Assigned(FDataSource.DataSet) or not FDataSource.DataSet.Active then
    Exit;

  LField := Column.FieldName;
  if SameText(FSortField, LField) then
    FSortDesc := not FSortDesc
  else
  begin
    FSortField := LField;
    FSortDesc := False;
  end;

  if Assigned(FDB) and FDB.QryLotes.Active then
  begin
    if FSortDesc then
      FDB.QryLotes.IndexFieldNames := LField + ':D'
    else
      FDB.QryLotes.IndexFieldNames := LField;
  end;

  for I := 0 to grdLotes.Columns.Count - 1 do
  begin
    LTitle := grdLotes.Columns[I].Title.Caption;
    LTitle := StringReplace(LTitle, ' ▲', '', [rfReplaceAll]);
    LTitle := StringReplace(LTitle, ' ▼', '', [rfReplaceAll]);
    if SameText(grdLotes.Columns[I].FieldName, FSortField) then
    begin
      if FSortDesc then
        LTitle := LTitle + ' ▼'
      else
        LTitle := LTitle + ' ▲';
    end;
    grdLotes.Columns[I].Title.Caption := LTitle;
  end;
end;

procedure TfrmPesadoMain.grdLotesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if (Key = VK_RETURN) and (not FRefrescandoLotes) and (not FAlarmaActiva) then
  begin
    CargarLoteSeleccionado;
    if FLoteActivo then
      MostrarPanelLotes(False);
    Key := 0;
  end
  else if Key = VK_ESCAPE then
  begin
    MostrarPanelLotes(False);
    Key := 0;
  end;
end;

procedure TfrmPesadoMain.CargarLoteSeleccionado;
var
  LQ: TDataSet;
  LPeso: Double;
begin
  LQ := FDB.QryLotes;
  if (not LQ.Active) or LQ.IsEmpty then
  begin
    LimpiarLote;
    Exit;
  end;
  if FAlarmaActiva then
    Exit;

  LPeso := PesoArticuloKg(LQ.FieldByName('peso_teorico').AsFloat);
  if LPeso <= 0 then
  begin
    FLoteActivo := False;
    FIdStock := LQ.FieldByName('id_stock_envasado').AsInteger;
    FIdLote := LQ.FieldByName('id_lote').AsInteger;
    FIdArticulo := LQ.FieldByName('id_articulo').AsInteger;
    FCodigoLote := LQ.FieldByName('codigo_antiguo').AsString;
    FArticulo := LQ.FieldByName('articulo').AsString;
    FFormato := LQ.FieldByName('formato').AsString;
    FPesoTeoricoKg := 0;
    FUnidadesTeoricas := Round(LQ.FieldByName('cantidad_producida').AsFloat);
    FPesadasOK := 0;
    FRechazos := 0;
    lblArticulo.Caption := FArticulo;
    lblLote.Caption := 'LOTE: ' + FCodigoLote;
    lblNominal.Caption := 'ATENCIÓN: Artículo sin peso asignado en su ficha (ge_articulos.peso)';
    lblUltima.Caption := '';
    btnFinalizar.Enabled := False;
    ActualizarContadores;
    SetSemaforo(esAviso, 'ARTÍCULO SIN PESO', 'Asigne el peso del artículo en GESTION antes de pesar este lote');
    Exit;
  end;

  try
    FIdStock := LQ.FieldByName('id_stock_envasado').AsInteger;
    FIdLote := LQ.FieldByName('id_lote').AsInteger;
    FIdArticulo := LQ.FieldByName('id_articulo').AsInteger;
    FCodigoLote := LQ.FieldByName('codigo_antiguo').AsString;
    FArticulo := LQ.FieldByName('articulo').AsString;
    FFormato := LQ.FieldByName('formato').AsString;
    FPesoArticuloRaw := LQ.FieldByName('peso_teorico').AsFloat;
    FPesoTeoricoKg := LPeso;
    FUnidadesTeoricas := Round(LQ.FieldByName('cantidad_producida').AsFloat);
    // Recuperar lo ya pesado (permite continuar un lote tras cerrar la aplicación)
    FPesadasOK := FDB.ContarPesadas(FIdStock, True);
    FRechazos := FDB.ContarPesadas(FIdStock, False);
    FLoteActivo := True;
  except
    on E: Exception do
    begin
      LimpiarLote;
      MessageDlg('Error al cargar el lote: ' + E.Message, mtError, [mbOK], 0);
      Exit;
    end;
  end;

  MostrarInfoLote;
  lblUltima.Caption := '';
  btnFinalizar.Enabled := True;
  FArmado := FUltimoPesoNetoKg * 1000 < FConfig.UmbralCeroGr;
  ActualizarContadores;
  if FArmado then
    SetSemaforo(esEspera, 'COLOQUE EL ARTÍCULO', 'Lote cargado. Esperando peso estable...')
  else
    SetSemaforo(esAviso, 'VACÍE EL PLATO', 'Retire el artículo de la báscula para empezar');
end;

procedure TfrmPesadoMain.MostrarInfoLote;
begin
  lblArticulo.Caption := FArticulo;
  lblLote.Caption := 'LOTE: ' + FCodigoLote;
  if FFormato <> '' then
    lblNominal.Caption := Format('FORMATO: %s      ·      PESO NOMINAL: %s kg      MÍNIMO ADMITIDO (-%s %%): %s kg',
      [FFormato, FormatFloat('0.000', FPesoTeoricoKg), FormatFloat('0.##', FConfig.ToleranciaPorc),
       FormatFloat('0.000', FPesoTeoricoKg * (1 - FConfig.ToleranciaPorc / 100))])
  else
    lblNominal.Caption := Format('PESO NOMINAL: %s kg      MÍNIMO ADMITIDO (-%s %%): %s kg',
      [FormatFloat('0.000', FPesoTeoricoKg), FormatFloat('0.##', FConfig.ToleranciaPorc),
       FormatFloat('0.000', FPesoTeoricoKg * (1 - FConfig.ToleranciaPorc / 100))]);

  if FConfig.TaraEnvaseGr > 0 then
    lblNominal.Caption := lblNominal.Caption + Format('      TARA ENVASE: %s g', [FormatFloat('0.#', FConfig.TaraEnvaseGr)]);

  ActualizarDisposicionEstado;
end;

procedure TfrmPesadoMain.ActualizarContadores;
var
  LPend: Integer;
begin
  LPend := Max(0, FUnidadesTeoricas - FPesadasOK);
  lblTeoricas.Caption := IntToStr(FUnidadesTeoricas);
  lblCorrectas.Caption := IntToStr(FPesadasOK);
  lblRechazadas.Caption := IntToStr(FRechazos);
  lblPendientes.Caption := IntToStr(LPend);
  if FLoteActivo and (LPend = 0) then
    lblPendientes.Font.Color := CLR_VERDE
  else
    lblPendientes.Font.Color := CLR_AMBAR;
end;

{ ---------------------------------------------------------------------------
  Semáforo, sonidos y alarma
  --------------------------------------------------------------------------- }

procedure TfrmPesadoMain.SetSemaforo(AEstado: TEstadoSemaforo; const ATexto, ADetalle: string);
begin
  shpRojo.Brush.Color := CLR_ROJO_OFF;
  shpAmbar.Brush.Color := CLR_AMBAR_OFF;
  shpVerde.Brush.Color := CLR_VERDE_OFF;
  case AEstado of
    esVerde:
      begin
        shpVerde.Brush.Color := $0000FF40;
        pnlEstado.Color := CLR_VERDE;
      end;
    esRojo:
      begin
        shpRojo.Brush.Color := $003030FF;
        pnlEstado.Color := CLR_ROJO;
      end;
    esAviso:
      begin
        shpAmbar.Brush.Color := CLR_AMBAR;
        pnlEstado.Color := $00007090;
      end;
  else
    pnlEstado.Color := CLR_GRIS;
  end;
  lblEstado.Caption := ATexto;
  lblEstadoDetalle.Caption := ADetalle;
  ActualizarDisposicionEstado;
end;

procedure TfrmPesadoMain.InicializarSonidos;

  function GenerarWavDosTonos(AFreq1, AFreq2: Double; ADur1Ms, ADur2Ms: Integer;
    AArmonicos: Boolean): TBytes;
  const
    SAMPLE_RATE = 22050;
  var
    LTotalSamples, LSamples1, I, LDataSize: Integer;
    LHeader: array[0..43] of Byte;
    LFreq, LPhase, LVal: Double;
    LSample: SmallInt;
    P: PByte;

    procedure WriteU32(AOffset: Integer; AVal: Cardinal);
    begin
      PCardinal(@LHeader[AOffset])^ := AVal;
    end;

    procedure WriteU16(AOffset: Integer; AVal: Word);
    begin
      PWord(@LHeader[AOffset])^ := AVal;
    end;

  begin
    LSamples1 := (SAMPLE_RATE * ADur1Ms) div 1000;
    LTotalSamples := LSamples1 + ((SAMPLE_RATE * ADur2Ms) div 1000);
    LDataSize := LTotalSamples * 2;
    SetLength(Result, 44 + LDataSize);

    FillChar(LHeader, SizeOf(LHeader), 0);
    Move(AnsiString('RIFF')[1], LHeader[0], 4);
    WriteU32(4, 36 + Cardinal(LDataSize));
    Move(AnsiString('WAVE')[1], LHeader[8], 4);
    Move(AnsiString('fmt ')[1], LHeader[12], 4);
    WriteU32(16, 16);
    WriteU16(20, 1); // PCM
    WriteU16(22, 1); // Mono
    WriteU32(24, SAMPLE_RATE);
    WriteU32(28, SAMPLE_RATE * 2);
    WriteU16(32, 2);
    WriteU16(34, 16);
    Move(AnsiString('data')[1], LHeader[36], 4);
    WriteU32(40, Cardinal(LDataSize));
    Move(LHeader[0], Result[0], 44);

    LPhase := 0;
    P := @Result[44];
    for I := 0 to LTotalSamples - 1 do
    begin
      if I < LSamples1 then
        LFreq := AFreq1
      else
        LFreq := AFreq2;
      LPhase := LPhase + (2 * Pi * LFreq) / SAMPLE_RATE;
      if AArmonicos then
        LVal := 0.65 * Sin(LPhase) + 0.25 * Sin(3 * LPhase) + 0.10 * Sin(5 * LPhase)
      else
        LVal := Sin(LPhase);
      LSample := Round(EnsureRange(LVal, -1.0, 1.0) * 28000);
      PSmallInt(P)^ := LSample;
      Inc(P, 2);
    end;
  end;

begin
  // Doble tono agradable para pesada OK (1046 Hz -> 1318 Hz)
  FWavOk := GenerarWavDosTonos(1046, 1318, 80, 110, False);
  // Sirena industrial bitonal potente para alarma de rechazo (980 Hz <-> 620 Hz)
  FWavAlarma := GenerarWavDosTonos(980, 620, 320, 320, True);
end;

procedure TfrmPesadoMain.Sonar(AOk: Boolean);
begin
  if not FConfig.SonidoActivo then
    Exit;
  if AOk then
  begin
    if Length(FWavOk) > 0 then
      PlaySound(PChar(@FWavOk[0]), 0, SND_MEMORY or SND_ASYNC or SND_NODEFAULT);
  end
  else
  begin
    if Length(FWavAlarma) > 0 then
      PlaySound(PChar(@FWavAlarma[0]), 0, SND_MEMORY or SND_ASYNC or SND_LOOP or SND_NODEFAULT);
  end;
end;

procedure TfrmPesadoMain.ActivarAlarma(const AMensaje: string);
begin
  FAlarmaActiva := True;
  lblAlarma.Caption := AMensaje;
  pnlAlarma.SetBounds(0, 0, ClientWidth, ClientHeight);
  pnlAlarma.Color := CLR_ROJO;
  pnlAlarma.Visible := True;
  pnlAlarma.BringToFront;
  btnFinalizar.Enabled := False;
  Sonar(False);
  tmrAlarma.Tag := 0;
  tmrAlarma.Enabled := True;
  if btnAlarmaOk.CanFocus then
    btnAlarmaOk.SetFocus;
end;

procedure TfrmPesadoMain.DetenerAlarma;
begin
  tmrAlarma.Enabled := False;
  FAlarmaActiva := False;
  pnlAlarma.Visible := False;
  btnFinalizar.Enabled := FLoteActivo;
  PlaySound(nil, 0, 0);
end;

procedure TfrmPesadoMain.tmrAlarmaTimer(Sender: TObject);
begin
  tmrAlarma.Tag := tmrAlarma.Tag + 1;
  if Odd(tmrAlarma.Tag) then
    pnlAlarma.Color := $00000088
  else
  begin
    pnlAlarma.Color := CLR_ROJO;
    if FConfig.SonidoActivo then
      Winapi.Windows.Beep(950, 90);
  end;
end;

procedure TfrmPesadoMain.btnAlarmaOkClick(Sender: TObject);
begin
  DetenerAlarma;
  if FUltimoPesoNetoKg * 1000 >= FConfig.UmbralCeroGr then
    SetSemaforo(esAviso, 'VACÍE EL PLATO', 'Retire el artículo rechazado de la báscula')
  else
    SetSemaforo(esEspera, 'COLOQUE EL ARTÍCULO', 'Esperando peso estable...');
end;

{ ---------------------------------------------------------------------------
  Lecturas de báscula y evaluación
  --------------------------------------------------------------------------- }

procedure TfrmPesadoMain.BasculaEstado(Sender: TObject; AConectada: Boolean; const AMensaje: string);
begin
  lblStatusCom.Caption := 'Báscula: ' + AMensaje;
  if AConectada then
    lblStatusCom.Font.Color := CLR_VERDE
  else
    lblStatusCom.Font.Color := CLR_ROJO;
end;

procedure TfrmPesadoMain.BasculaPeso(Sender: TObject; APesoKg: Double; AEstable: Boolean; const ATrama: string);
var
  LNetoKg: Double;
begin
  LNetoKg := APesoKg - FConfig.TaraEnvaseGr / 1000;
  FUltimoPesoNetoKg := LNetoKg;

  lblPeso.Caption := FormatFloat('0.000', LNetoKg) + ' kg';
  if FConfig.TaraEnvaseGr > 0 then
    lblBruto.Caption := 'Bruto: ' + FormatFloat('0.000', APesoKg) + ' kg'
  else
    lblBruto.Caption := '';
  if lblBruto.Visible <> (lblBruto.Caption <> '') then
    ActualizarDisposicionEstado;
  if AEstable then
  begin
    lblEstable.Caption := '●  ESTABLE';
    lblEstable.Font.Color := $0000FF40;
  end
  else
  begin
    lblEstable.Caption := '○  EN MOVIMIENTO';
    lblEstable.Font.Color := CLR_AMBAR;
  end;

  // Plato vacío: rearmar el ciclo
  if LNetoKg * 1000 < FConfig.UmbralCeroGr then
  begin
    if not FArmado then
    begin
      FArmado := True;
      if FLoteActivo and not FAlarmaActiva then
        SetSemaforo(esEspera, 'COLOQUE EL ARTÍCULO', 'Esperando peso estable...');
    end;
    Exit;
  end;

  if FAlarmaActiva or (not FLoteActivo) or (not FArmado) then
    Exit;

  if AEstable and (LNetoKg * 1000 >= FConfig.PesoMinimoGr) then
  begin
    FArmado := False; // Una sola evaluación por artículo hasta que se vacíe el plato
    EvaluarPesada(LNetoKg, APesoKg);
  end;
end;

procedure TfrmPesadoMain.EvaluarPesada(APesoNetoKg, APesoBrutoKg: Double);
var
  LPesada: TPesadaRegistro;
  LMinimo: Double;
begin
  LMinimo := FPesoTeoricoKg * (1 - FConfig.ToleranciaPorc / 100);

  LPesada.IdStockEnvasado := FIdStock;
  LPesada.IdLote := FIdLote;
  LPesada.IdArticulo := FIdArticulo;
  LPesada.PesoTeoricoKg := RoundTo(FPesoTeoricoKg, -3);
  LPesada.PesoRealKg := RoundTo(APesoNetoKg, -3);
  LPesada.PesoBrutoKg := RoundTo(APesoBrutoKg, -3);
  LPesada.DesviacionPorc := RoundTo((APesoNetoKg - FPesoTeoricoKg) / FPesoTeoricoKg * 100, -2);
  LPesada.Conforme := APesoNetoKg >= LMinimo;

  try
    FDB.RegistrarPesada(LPesada);
  except
    on E: Exception do
    begin
      SetSemaforo(esAviso, 'ERROR AL GRABAR', 'No se ha guardado la pesada. Retire y repita. (' + E.Message + ')');
      Sonar(False);
      Exit;
    end;
  end;

  if LPesada.Conforme then
  begin
    Inc(FPesadasOK);
    ActualizarContadores;
    if APesoNetoKg >= FPesoTeoricoKg then
      SetSemaforo(esVerde, 'PESO CORRECTO', Format('%s kg  (%+.2f %%)', [FormatFloat('0.000', APesoNetoKg), LPesada.DesviacionPorc]))
    else
      SetSemaforo(esVerde, 'CORRECTO (EN TOLERANCIA)', Format('%s kg  (%+.2f %%)', [FormatFloat('0.000', APesoNetoKg), LPesada.DesviacionPorc]));
    if FPesadasOK = FUnidadesTeoricas then
      lblEstadoDetalle.Caption := lblEstadoDetalle.Caption + '  ·  LOTE COMPLETADO: pulse FINALIZAR LOTE'
    else if FPesadasOK > FUnidadesTeoricas then
      lblEstadoDetalle.Caption := lblEstadoDetalle.Caption + Format('  ·  %d uds. por encima de lo fabricado', [FPesadasOK - FUnidadesTeoricas]);
    lblUltima.Caption := Format('Última pesada: %s kg  CORRECTA  a las %s', [FormatFloat('0.000', APesoNetoKg), FormatDateTime('hh:nn:ss', Now)]);
    ActualizarDisposicionEstado;
    Sonar(True);
  end
  else
  begin
    Inc(FRechazos);
    ActualizarContadores;
    SetSemaforo(esRojo, 'PESO INSUFICIENTE', Format('%s kg  (%+.2f %%)', [FormatFloat('0.000', APesoNetoKg), LPesada.DesviacionPorc]));
    lblUltima.Caption := Format('Última pesada: %s kg  RECHAZADA  a las %s', [FormatFloat('0.000', APesoNetoKg), FormatDateTime('hh:nn:ss', Now)]);
    ActualizarDisposicionEstado;
    ActivarAlarma(Format('¡DESECHAR ARTÍCULO!' + sLineBreak + sLineBreak +
      '%s  (Lote: %s)' + sLineBreak +
      'Peso leído: %s kg   ·   Mínimo admitido: %s kg' + sLineBreak +
      'Déficit: %.2f %%',
      [FArticulo, FCodigoLote, FormatFloat('0.000', APesoNetoKg), FormatFloat('0.000', LMinimo), Abs(LPesada.DesviacionPorc)]));
  end;
end;

{ ---------------------------------------------------------------------------
  Botones
  --------------------------------------------------------------------------- }

procedure TfrmPesadoMain.btnRefrescarClick(Sender: TObject);
begin
  try
    RefrescarLotes(True);
  except
    on E: Exception do
      MessageDlg('Error al refrescar los lotes: ' + E.Message, mtError, [mbOK], 0);
  end;
end;

function ConfirmarFinalizacionLote(AOwner: TComponent; const ACodigoLote, AArticulo: string;
  AUnidadesTeoricas, APesadasOK, ARechazos: Integer): Boolean;
var
  LForm: TForm;
  LPnlFondo, LPnlCard, LPnlBotones: TPanel;
  LLblTitulo, LLblSub, LLblAviso: TLabel;
  LBtnConfirmar, LBtnRechazar: TButton;

  function CrearFilaDato(AParent: TWinControl; const AEtiqueta, AValor: string; AColorVal: TColor): TPanel;
  var
    LLblEtiq, LLblVal: TLabel;
  begin
    Result := TPanel.Create(LForm);
    Result.Parent := AParent;
    Result.Align := alTop;
    Result.Height := 34;
    Result.BevelOuter := bvNone;
    Result.ParentBackground := False;
    Result.Color := $00453E38;
    Result.AlignWithMargins := True;
    Result.Margins.SetBounds(16, 2, 16, 2);

    LLblEtiq := TLabel.Create(LForm);
    LLblEtiq.Parent := Result;
    LLblEtiq.Align := alLeft;
    LLblEtiq.SetBounds(12, 6, 260, 24);
    LLblEtiq.Font.Name := 'Segoe UI';
    LLblEtiq.Font.Size := 12;
    LLblEtiq.Font.Color := clSilver;
    LLblEtiq.Caption := AEtiqueta;

    LLblVal := TLabel.Create(LForm);
    LLblVal.Parent := Result;
    LLblVal.Align := alRight;
    LLblVal.SetBounds(280, 4, 180, 26);
    LLblVal.Alignment := taRightJustify;
    LLblVal.Font.Name := 'Segoe UI';
    LLblVal.Font.Size := 14;
    LLblVal.Font.Style := [fsBold];
    LLblVal.Font.Color := AColorVal;
    LLblVal.Caption := AValor;
  end;

begin
  Result := False;
  LForm := TForm.CreateNew(AOwner);
  try
    LForm.Caption := 'Confirmación de Finalización de Lote';
    LForm.BorderStyle := bsDialog;
    LForm.Position := poScreenCenter;
    LForm.ClientWidth := 560;
    LForm.ClientHeight := 440;
    LForm.Color := $00201C18;
    LForm.Font.Name := 'Segoe UI';

    LPnlFondo := TPanel.Create(LForm);
    LPnlFondo.Parent := LForm;
    LPnlFondo.Align := alClient;
    LPnlFondo.BevelOuter := bvNone;
    LPnlFondo.ParentBackground := False;
    LPnlFondo.Color := $00201C18;
    LPnlFondo.Padding.SetBounds(16, 16, 16, 16);

    // Cabecera destacada de la ventana
    LLblTitulo := TLabel.Create(LForm);
    LLblTitulo.Parent := LPnlFondo;
    LLblTitulo.Align := alTop;
    LLblTitulo.Height := 38;
    LLblTitulo.Font.Name := 'Segoe UI';
    LLblTitulo.Font.Size := 18;
    LLblTitulo.Font.Style := [fsBold];
    LLblTitulo.Font.Color := clYellow;
    LLblTitulo.Alignment := taCenter;
    LLblTitulo.Caption := '¿DESEA FINALIZAR ESTE LOTE?';

    LLblSub := TLabel.Create(LForm);
    LLblSub.Parent := LPnlFondo;
    LLblSub.Align := alTop;
    LLblSub.Height := 28;
    LLblSub.Font.Name := 'Segoe UI';
    LLblSub.Font.Size := 13;
    LLblSub.Font.Style := [fsBold];
    LLblSub.Font.Color := clWhite;
    LLblSub.Alignment := taCenter;
    LLblSub.Caption := Format('Lote %s  ·  %s', [ACodigoLote, AArticulo]);

    // Tarjeta con los datos de resumen del lote
    LPnlCard := TPanel.Create(LForm);
    LPnlCard.Parent := LPnlFondo;
    LPnlCard.Align := alClient;
    LPnlCard.BevelOuter := bvNone;
    LPnlCard.ParentBackground := False;
    LPnlCard.Color := $0036302B;
    LPnlCard.AlignWithMargins := True;
    LPnlCard.Margins.SetBounds(4, 10, 4, 10);
    LPnlCard.Padding.SetBounds(6, 8, 6, 8);

    CrearFilaDato(LPnlCard, 'Unidades previstas (teóricas):', Format('%d uds.', [AUnidadesTeoricas]), clWhite);
    CrearFilaDato(LPnlCard, 'Pesadas conformes (válidas):', Format('%d uds.', [APesadasOK]), $0050B000);
    CrearFilaDato(LPnlCard, 'Pesadas rechazadas:', Format('%d uds.', [ARechazos]), $004040FF);
    CrearFilaDato(LPnlCard, 'Nuevo stock envasado a generar:', Format('%d uds.', [APesadasOK]), $0000D0FF);

    if APesadasOK < AUnidadesTeoricas then
    begin
      LLblAviso := TLabel.Create(LForm);
      LLblAviso.Parent := LPnlCard;
      LLblAviso.Align := alTop;
      LLblAviso.Height := 30;
      LLblAviso.Alignment := taCenter;
      LLblAviso.Font.Name := 'Segoe UI';
      LLblAviso.Font.Size := 12;
      LLblAviso.Font.Style := [fsBold];
      LLblAviso.Font.Color := $0000B0FF; // Ámbar/Naranja
      LLblAviso.Caption := Format('⚠️ ATENCIÓN: Quedan %d unidades teóricas sin pesar.', [AUnidadesTeoricas - APesadasOK]);
    end;

    // Panel inferior con botones táctiles GRANDES y de alto contraste
    LPnlBotones := TPanel.Create(LForm);
    LPnlBotones.Parent := LPnlFondo;
    LPnlBotones.Align := alBottom;
    LPnlBotones.Height := 80;
    LPnlBotones.BevelOuter := bvNone;
    LPnlBotones.ParentBackground := False;
    LPnlBotones.Color := $00201C18;

    // Botón Rechazar / Cancelar (Izquierda)
    LBtnRechazar := TButton.Create(LForm);
    LBtnRechazar.Parent := LPnlBotones;
    LBtnRechazar.Align := alLeft;
    LBtnRechazar.Width := 250;
    LBtnRechazar.Caption := '❌ NO, CONTINUAR PESANDO';
    LBtnRechazar.Font.Name := 'Segoe UI';
    LBtnRechazar.Font.Size := 13;
    LBtnRechazar.Font.Style := [fsBold];
    LBtnRechazar.ModalResult := mrCancel;
    LBtnRechazar.AlignWithMargins := True;
    LBtnRechazar.Margins.SetBounds(4, 6, 6, 6);

    // Botón Confirmar Finalización (Derecha)
    LBtnConfirmar := TButton.Create(LForm);
    LBtnConfirmar.Parent := LPnlBotones;
    LBtnConfirmar.Align := alRight;
    LBtnConfirmar.Width := 250;
    LBtnConfirmar.Caption := '✔ SÍ, FINALIZAR LOTE';
    LBtnConfirmar.Font.Name := 'Segoe UI';
    LBtnConfirmar.Font.Size := 14;
    LBtnConfirmar.Font.Style := [fsBold];
    LBtnConfirmar.ModalResult := mrOk;
    LBtnConfirmar.AlignWithMargins := True;
    LBtnConfirmar.Margins.SetBounds(6, 6, 4, 6);

    LForm.ActiveControl := LBtnConfirmar;
    Result := LForm.ShowModal = mrOk;
  finally
    LForm.Free;
  end;
end;

procedure TfrmPesadoMain.btnFinalizarClick(Sender: TObject);
begin
  if not FLoteActivo then
    Exit;

  // Una única ventana de confirmación clara y con botones táctiles de gran tamaño
  if not ConfirmarFinalizacionLote(Self, FCodigoLote, FArticulo, FUnidadesTeoricas, FPesadasOK, FRechazos) then
    Exit;

  try
    if not FDB.LoteSigueAbierto(FIdStock) then
    begin
      MessageDlg('Este lote ya ha sido finalizado desde otro puesto.', mtWarning, [mbOK], 0);
      LimpiarLote;
      RefrescarLotes(False);
      MostrarPanelLotes(True);
      Exit;
    end;
    FDB.FinalizarLote(FIdStock);
  except
    on E: Exception do
    begin
      MessageDlg('Error al finalizar el lote: ' + E.Message, mtError, [mbOK], 0);
      Exit;
    end;
  end;

  // Lote finalizado con éxito: sin segundo emergente molesto. Limpiar y mostrar lista de lotes directamente
  LimpiarLote;
  RefrescarLotes(False);
  MostrarPanelLotes(True);
end;

procedure TfrmPesadoMain.btnConfigClick(Sender: TObject);
var
  LCfg: TPesadoConfig;
  LCambioBD: Boolean;
begin
  if not PedirPasswordAdmin(Self) then
    Exit;
  // Liberar el puerto para que la pantalla de configuración pueda probarlo
  FBascula.Detener;
  lblStatusCom.Caption := 'Báscula: detenida (configurando)';
  lblStatusCom.Font.Color := clSilver;
  LCfg := FConfig;
  if TfrmConfigBascula.Ejecutar(LCfg) then
  begin
    LCambioBD := (not SameText(LCfg.DBServer, FConfig.DBServer)) or
                 (LCfg.DBPort <> FConfig.DBPort) or
                 (not SameText(LCfg.DBDatabase, FConfig.DBDatabase)) or
                 (LCfg.DBUser <> FConfig.DBUser) or
                 (LCfg.DBPassword <> FConfig.DBPassword) or
                 (not FDB.Conexion.Connected);
    FConfig := LCfg;
    if LCambioBD then
    begin
      LimpiarLote;
      FDB.AplicarConfiguracion(FConfig);
      ConectarBD;
    end;
  end;
  IniciarBascula;
  if FLoteActivo then
  begin
    // Recalcular con la posible nueva unidad / tolerancia / tara
    FPesoTeoricoKg := PesoArticuloKg(FPesoArticuloRaw);
    MostrarInfoLote;
  end;
end;

procedure TfrmPesadoMain.btnSalirClick(Sender: TObject);
begin
  Close;
end;

procedure TfrmPesadoMain.FormCloseQueryHandler(Sender: TObject; var CanClose: Boolean);
begin
  CanClose := True;
end;

procedure TfrmPesadoMain.btnSimClick(Sender: TObject);
var
  LValor: Double;
begin
  LValor := StrToFloatDef(StringReplace(edtSimPeso.Text, ',', '.', []), 0, TFormatSettings.Invariant);
  case (Sender as TComponent).Tag of
    TAG_SIM_PONER:
      FBascula.SetPesoSimulado(LValor);
    TAG_SIM_TEORICO:
      begin
        LValor := FPesoTeoricoKg + FConfig.TaraEnvaseGr / 1000 + 0.002;
        edtSimPeso.Text := FormatFloat('0.000', LValor, TFormatSettings.Invariant);
        FBascula.SetPesoSimulado(LValor);
      end;
    TAG_SIM_BAJO:
      begin
        LValor := FPesoTeoricoKg * 0.95 + FConfig.TaraEnvaseGr / 1000;
        edtSimPeso.Text := FormatFloat('0.000', LValor, TFormatSettings.Invariant);
        FBascula.SetPesoSimulado(LValor);
      end;
    TAG_SIM_RETIRAR:
      FBascula.SetPesoSimulado(0);
  end;
end;

end.
