unit frm_PlanificacionMasasProduccion;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
  Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, Vcl.Menus, Data.DB, FireDAC.Comp.Client,
  FireDAC.Comp.DataSet, FireDAC.Stan.Param, FireDAC.Stan.Intf, FireDAC.Stan.Option,
  FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, System.Math, System.Generics.Collections,
  System.Generics.Defaults, System.IOUtils,
  System.UITypes, System.DateUtils, System.StrUtils, uAppTheme, dmg_Main,
  frm_InformePlanificacionProduccion, frm_OrdenesFabricacion, frm_OrdenesProduccion;

type
  TSaborRepartoItem = class
  public
    RecetaId: Integer;
    RecetaDesc: string;
    PrefijoLote: string;
    ArticuloId: Integer;
    ArticuloDesc: string;
    Porcentaje: Double;
    UnidadesBase: Double;
    UnidadesCalculadas: Integer;
    UnidadesXL: Integer;
    UnidadesL: Integer;
    LoteCodigo: string;
    constructor Create;
  end;

  TProductoFinalItem = class
  public
    ArticuloId: Integer;
    ArticuloDesc: string;
    RecetaId: Integer;
    RecetaDesc: string;
    PrefijoLote: string;
    UnidadesBase: Double;
  end;

  TMasaBaseItem = class
  public
    NumeroMasa: Integer;
    NombreMasa: string;
    LoteCodigo: string;
    Lote1erEmpasteCodigo: string;
    Multiplicador: Double;
    EsExistente: Boolean;
    Sabores: TObjectList<TSaborRepartoItem>;
    constructor Create(ANumero: Integer);
    destructor Destroy; override;
    function TotalPorcentaje: Double;
  end;

  TPlanFabricacion = class
  public
    Fecha: TDateTime;
    AlmacenId: Integer;
    AlmacenNombre: string;
    ObradorId: Integer;
    ObradorNombre: string;
    RecetaPrincipalId: Integer;
    RecetaPrincipalDesc: string;
    PrefijoPrincipal: string;
    EsMasaBase: Boolean;
    EsMasaMadre: Boolean;
    CantidadMasasPrincipal: Integer;

    MasasBaseManana: Integer;
    Requiere1erEmpaste: Boolean;
    Receta1erEmpasteId: Integer;
    RequiereMasaMadre: Boolean;
    RecetaMasaMadreId: Integer;
    LoteMasaMadreCodigo: string;
    Lote1erEmpasteCodigo: string;
    MasaMadrePorMasaKg: Double;
    MasaMadreExtraKg: Double;
    MasaMadreHoyKg: Double;
    MasaMadreTotalKg: Double;

    Masas: TObjectList<TMasaBaseItem>;
    constructor Create;
    destructor Destroy; override;
    procedure Limpiar;
    procedure RecalcularTotales;
  end;

  TfrmPlanificacionMasasProduccion = class;

  TMasaRepartoRow = class
  public
    OwnerForm: TfrmPlanificacionMasasProduccion;
    RowPanel: TPanel;
    lblMasa: TLabel;
    cbbPorc: TComboBox;
    cbbArticulo: TComboBox;
    edtUnidades: TEdit;
    edtAcumulado: TEdit;
    edtLote: TEdit;
    btnEliminar: TSpeedButton;

    MasaItem: TMasaBaseItem;
    SaborItem: TSaborRepartoItem;

    constructor Create(AOwner: TfrmPlanificacionMasasProduccion; AMasa: TMasaBaseItem; ASabor: TSaborRepartoItem; AIndexInMasa: Integer);
    destructor Destroy; override;

    procedure OnMasaLabelClick(Sender: TObject);
    procedure OnPorcExit(Sender: TObject);
    procedure OnPorcKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure OnPorcCloseUp(Sender: TObject);
    procedure OnArticuloChange(Sender: TObject);
    procedure OnUnidadesExit(Sender: TObject);
    procedure OnUnidadesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure OnLoteChange(Sender: TObject);
    procedure OnEliminarClick(Sender: TObject);
  end;

  TfrmPlanificacionMasasProduccion = class(TForm)
    pnlTop: TPanel;
    lblTitle: TLabel;
    lblSubtitle: TLabel;
    pnlKpis: TPanel;
    pnlKpiRecetas: TPanel;
    lblKpiRecetasVal: TLabel;
    lblKpiRecetasLbl: TLabel;
    pnlKpiMasas: TPanel;
    lblKpiMasasVal: TLabel;
    lblKpiMasasLbl: TLabel;
    pnlKpiUnidades: TPanel;
    lblKpiUnidadesVal: TLabel;
    lblKpiUnidadesLbl: TLabel;

    pnlOptions: TPanel;
    lblFechaLote: TLabel;
    dtpFechaLote: TDateTimePicker;
    lblAlmacen: TLabel;
    cbbAlmacen: TComboBox;
    lblObrador: TLabel;
    cbbObrador: TComboBox;
    chkSoloConDeficit: TCheckBox;
    btnRecalcular: TBitBtn;
    btnDuplicarPlan: TBitBtn;

    pnlBody: TPanel;
    pcModo: TPageControl;

    // Tab 1: Plan Manual
    tsPlanManual: TTabSheet;
    pnlPlanLeft: TPanel;
    pnlSelReceta: TPanel;
    lblRecetaPlan: TLabel;
    cbbRecetaPlan: TComboBox;
    lblCantidadMasas: TLabel;
    edtCantidadMasas: TEdit;
    cbbPorcionMasa: TComboBox;
    btnAplicarMasas: TBitBtn;
    btnAnadirMasas: TBitBtn;

    pnlMasaMadreParams: TPanel;
    lblMasaMadreTitle: TLabel;
    lblSubrecetasInfo: TLabel;
    lblPesoMasaMadreKg: TLabel;
    edtPesoMasaMadreKg: TEdit;
    lblMasaMadreManana: TLabel;
    edtMasasBaseManana: TEdit;
    lblMasaMadreExtra: TLabel;
    edtMasaMadreExtraKg: TEdit;

    pnlRepartoSabores: TPanel;
    pnlRepartoHeader: TPanel;
    lblRepartoTitle: TLabel;
    pnlTemplateButtons: TPanel;
    btnTpl100: TBitBtn;
    btnTpl5050: TBitBtn;
    btnTpl7525: TBitBtn;
    btnTpl4x25: TBitBtn;
    pnlGridHeader: TPanel;
    lblHdrMasa: TLabel;
    lblHdrPorc: TLabel;
    lblHdrArt: TLabel;
    lblHdrUds: TLabel;
    lblHdrAcum: TLabel;
    lblHdrLote: TLabel;
    sbxLineasMasa: TScrollBox;
    pnlRepartoFooter: TPanel;
    lblSumaPorc: TLabel;
    btnGuardarMasaReparto: TBitBtn;

    splManual: TSplitter;
    pnlPlanRight: TPanel;
    pnlTreeHeader: TPanel;
    lblTreeTitle: TLabel;
    btnModificarLote: TBitBtn;
    tvProduccion: TTreeView;
    pnlTreeFooter: TPanel;
    lblKpiTreeMasas: TLabel;
    lblKpiTreeMM: TLabel;
    lblKpiTreeUds: TLabel;
    pmTreeProduccion: TPopupMenu;
    miModificarLote: TMenuItem;

    // Tab 2: Pedidos / Déficit
    tsCalculoPedidos: TTabSheet;
    splRecetas: TSplitter;
    pnlRecetas: TPanel;
    pnlRecetasHeader: TPanel;
    lblRecetasTitle: TLabel;
    dbgRecetas: TDBGrid;

    pnlArticulos: TPanel;
    pnlArticulosHeader: TPanel;
    lblArticulosTitle: TLabel;
    dbgArticulos: TDBGrid;

    // Footer
    pnlFooter: TPanel;
    btnGuardarPlan: TBitBtn;
    btnVerInforme: TBitBtn;
    btnVerOrdenesFabricacion: TBitBtn;
    btnDuplicarPlanFooter: TBitBtn;
    btnGenerarLoteReceta: TBitBtn;
    btnGenerarTodosLotes: TBitBtn;
    btnExportar: TBitBtn;
    btnCerrar: TBitBtn;

    dsRecetas: TDataSource;
    dsArticulos: TDataSource;
    mtRecetas: TFDMemTable;
    mtArticulos: TFDMemTable;
    qAlmacenes: TFDQuery;
    qObradores: TFDQuery;
    qCargaPlan: TFDQuery;
    qExec: TFDQuery;
    saveDlgExport: TSaveDialog;

    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure dtpFechaLoteChange(Sender: TObject);
    procedure cbbAlmacenChange(Sender: TObject);
    procedure cbbObradorChange(Sender: TObject);
    procedure pcModoChange(Sender: TObject);

    // Eventos Plan Manual
    procedure cbbRecetaPlanChange(Sender: TObject);
    procedure btnAplicarMasasClick(Sender: TObject);
    procedure btnAnadirMasasClick(Sender: TObject);
    procedure edtCantidadMasasKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure edtCantidadMasasExit(Sender: TObject);
    procedure edtCantidadMasasChange(Sender: TObject);
    procedure edtPesoMasaMadreKgChange(Sender: TObject);
    procedure edtMasasBaseMananaChange(Sender: TObject);
    procedure edtMasaMadreExtraKgChange(Sender: TObject);
    procedure btnTpl100Click(Sender: TObject);
    procedure btnTpl5050Click(Sender: TObject);
    procedure btnTpl7525Click(Sender: TObject);
    procedure btnTpl4x25Click(Sender: TObject);
    procedure btnGuardarMasaRepartoClick(Sender: TObject);
    procedure btnGuardarPlanClick(Sender: TObject);
    procedure btnDuplicarPlanClick(Sender: TObject);
    procedure btnVerInformeClick(Sender: TObject);
    procedure btnVerOrdenesFabricacionClick(Sender: TObject);
    procedure btnModificarLoteClick(Sender: TObject);
    procedure tvProduccionDblClick(Sender: TObject);
    procedure tvProduccionKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);

    // Eventos Pedidos / Déficit
    procedure chkSoloConDeficitClick(Sender: TObject);
    procedure btnRecalcularClick(Sender: TObject);
    procedure btnGenerarLoteRecetaClick(Sender: TObject);
    procedure btnGenerarTodosLotesClick(Sender: TObject);
    procedure btnExportarClick(Sender: TObject);
    procedure btnCerrarClick(Sender: TObject);
    procedure mtRecetasAfterScroll(DataSet: TDataSet);
    procedure dbgRecetasDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure dbgArticulosDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);

  private
    FPlan: TPlanFabricacion;
    FProductosFinales: TObjectList<TProductoFinalItem>;
    FRepartoRows: TObjectList<TMasaRepartoRow>;
    FUpdatingControls: Boolean;
    FMaxArticuloDroppedWidth: Integer;
    FEmpresaId: Integer;
    FFechaEntregaVal: Integer;
    FEstadoIndex: Integer;
    FFiltrarFecha: Boolean;
    FFechaDesde: TDateTime;
    FFechaHasta: TDateTime;
    FSearch: string;
    FTabCalendario: TTabSheet;
    FCalYear: Word;
    FCalMonth: Word;
    FCalSelectedDate: TDateTime;
    FCalGrid: TDrawGrid;
    FLblCalMes: TLabel;
    FLblCalCap: TLabel;
    FMemoCalDetalle: TMemo;

    procedure InicializarPestanaCalendario;
    procedure CalPrevMonthClick(Sender: TObject);
    procedure CalNextMonthClick(Sender: TObject);
    procedure CalTodayClick(Sender: TObject);
    procedure CalGridResize(Sender: TObject);
    procedure CalGridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure CalGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    function GetCalCellDate(ACol, ARow: Integer): TDateTime;
    procedure ActualizarDetalleDiaCalendario(ADate: TDateTime);
    procedure RefrescarCalendarioVisual;

    procedure ConfigurarEstructuraTablas;
    procedure SetupGrids;
    procedure CargarAlmacenes;
    procedure CargarObradores;
    procedure CargarDatosPlanificacion;
    procedure ActualizarKPIs;
    procedure ActualizarArbolProduccion;
    procedure ReconstruirFilasReparto;
    procedure PostReconstruirFilasReparto;
    procedure SincronizarValoresFilas;
    procedure ActualizarTotalesAcumulados;
    procedure AgregarLineaRestanteMasa(AMasa: TMasaBaseItem; APrevSabor: TSaborRepartoItem; ARestantePorc: Double);
    function BuscarSiguienteFormato(ACurrentArtId, ARecetaId: Integer): TProductoFinalItem;
    procedure ValidarSumaPorcentajesSlots;
    procedure ModificarLoteNodoSeleccionado;
    function FormatearCodigoLoteSabor(const APrefijo: string; AFecha: TDateTime; ANumeroMasa: Integer; const ALoteBase: string = ''; ASubIndex: Integer = 0): string;
    procedure CargarPlanDesdeFecha(AFecha: TDateTime);
    procedure AsegurarColumnaArticuloReparto;
    procedure RegistrarMateriasPrimasTeoricasElaboracion(AElabId, ARecetaId: Integer;
      AMultiplicador: Double; AUserId: Integer; AIncluirMasaMadreKg: Double = 0.0);
    procedure RegistrarMateriasPrimasInclusionesElaboracion(AElabId, ARecetaId: Integer;
      AMultiplicador: Double; AIdLoteMB: Integer; const ALoteMBCodigo: string; AUserId: Integer);
    function SolicitarFechaDestino(const ACaption, APrompt: string; var AFecha: TDateTime): Boolean;
    function ObtenerSemillaMasaMadreKg(ARecetaId: Integer): Double;
    function GetPorcionMultiplicador: Double;

    function AjustarMasasACuartos(AMasas: Double): Double;
    function FormatearMasasCuartos(AMasas: Double): string;
    function GenerarLotesParaReceta(ARecetaId: Integer; const ARecetaNombre: string;
      AMasasAjustadas: Double; out ATotalLotesCreados: Integer): Boolean;
    function ObtenerAlmacenDeObrador(AObradorId: Integer): Integer;
    function ObtenerCapacidadObrador(AObradorId: Integer): Double;
    procedure SincronizarAlmacenConObrador;
    function GetSelectedAlmacenId: Integer;
    function GetSelectedObradorId: Integer;

  public
    class procedure MostrarPlan(AOwner: TComponent; AEmpresaId, AFechaEntregaVal, AEstadoIndex: Integer;
      AFiltrarFecha: Boolean; AFechaDesde, AFechaHasta: TDateTime; const ASearch: string);
    class procedure MostrarPlanReceta(AOwner: TComponent; ARecetaId: Integer);
    procedure CargarRecetasPlan;
    procedure SeleccionarReceta(ARecetaId: Integer);
    function ObtenerIdRecetaMasaMadre: Integer;
    function ObtenerPesoTotalRecetaKg(ARecetaId: Integer): Double;
    function GenerarTextoInformeProduccion: string;
  end;

var
  frmPlanificacionMasasProduccion: TfrmPlanificacionMasasProduccion;

implementation

uses
  frm_Main;

{$R *.dfm}

{ TSaborRepartoItem }

constructor TSaborRepartoItem.Create;
begin
  inherited Create;
  RecetaId := 0;
  RecetaDesc := '';
  PrefijoLote := 'P';
  ArticuloId := 0;
  ArticuloDesc := '';
  Porcentaje := 100.0;
  UnidadesBase := 189.0;
  UnidadesCalculadas := 189;
  UnidadesXL := 189;
  UnidadesL := 0;
  LoteCodigo := '';
end;

{ TMasaBaseItem }

constructor TMasaBaseItem.Create(ANumero: Integer);
begin
  inherited Create;
  NumeroMasa := ANumero;
  NombreMasa := Format('Masa %d', [ANumero]);
  LoteCodigo := '';
  Lote1erEmpasteCodigo := '';
  Multiplicador := 1.0;
  EsExistente := False;
  Sabores := TObjectList<TSaborRepartoItem>.Create(True);
end;

destructor TMasaBaseItem.Destroy;
begin
  Sabores.Free;
  inherited Destroy;
end;

function TMasaBaseItem.TotalPorcentaje: Double;
var
  i: Integer;
begin
  Result := 0.0;
  for i := 0 to Sabores.Count - 1 do
    Result := Result + Sabores[i].Porcentaje;
end;

{ TPlanFabricacion }

constructor TPlanFabricacion.Create;
begin
  inherited Create;
  Masas := TObjectList<TMasaBaseItem>.Create(True);
  Limpiar;
end;

destructor TPlanFabricacion.Destroy;
begin
  Masas.Free;
  inherited Destroy;
end;

procedure TPlanFabricacion.Limpiar;
begin
  Fecha := Date;
  AlmacenId := 1;
  AlmacenNombre := '';
  ObradorId := 1;
  ObradorNombre := '';
  RecetaPrincipalId := 0;
  RecetaPrincipalDesc := '';
  PrefijoPrincipal := '';
  EsMasaBase := False;
  EsMasaMadre := False;
  CantidadMasasPrincipal := 1;

  MasasBaseManana := 0;
  Requiere1erEmpaste := False;
  Receta1erEmpasteId := 22;
  RequiereMasaMadre := False;
  RecetaMasaMadreId := 3;
  LoteMasaMadreCodigo := '';
  Lote1erEmpasteCodigo := '';
  MasaMadrePorMasaKg := 10.005;
  MasaMadreExtraKg := 0.0;
  MasaMadreHoyKg := 0.0;
  MasaMadreTotalKg := 0.0;

  Masas.Clear;
end;

procedure TPlanFabricacion.RecalcularTotales;
var
  LPesoMMRef, LTotalMultMasas: Double;
  i: Integer;
begin
  LPesoMMRef := MasaMadrePorMasaKg;
  if LPesoMMRef <= 0.001 then
    LPesoMMRef := 10.005;

  if EsMasaBase then
  begin
    Requiere1erEmpaste := True;
    Receta1erEmpasteId := 22;
    RequiereMasaMadre := True;
    if RecetaMasaMadreId <= 0 then
      RecetaMasaMadreId := 3;
    // Masa Madre para hoy: suma de porciones de las masas base * peso de masa madre por masa (dinámico según receta)
    LTotalMultMasas := 0.0;
    for i := 0 to Masas.Count - 1 do
      LTotalMultMasas := LTotalMultMasas + Masas[i].Multiplicador;
    if LTotalMultMasas <= 0.001 then
      LTotalMultMasas := CantidadMasasPrincipal;

    MasaMadreHoyKg := LTotalMultMasas * LPesoMMRef;
    // La Masa Madre extra directa/calculada contiene la semilla necesaria para las masas de mañana
    MasaMadreTotalKg := MasaMadreHoyKg + MasaMadreExtraKg;
  end
  else if EsMasaMadre then
  begin
    Requiere1erEmpaste := False;
    RequiereMasaMadre := True;
    RecetaMasaMadreId := RecetaPrincipalId;
    MasaMadreHoyKg := CantidadMasasPrincipal * LPesoMMRef;
    MasaMadreTotalKg := MasaMadreHoyKg + MasaMadreExtraKg;
  end
  else
  begin
    Requiere1erEmpaste := False;
    RequiereMasaMadre := False;
    MasaMadreHoyKg := 0.0;
    MasaMadreTotalKg := 0.0;
  end;
end;

{ TfrmPlanificacionMasasProduccion }

class procedure TfrmPlanificacionMasasProduccion.MostrarPlan(AOwner: TComponent;
  AEmpresaId, AFechaEntregaVal, AEstadoIndex: Integer; AFiltrarFecha: Boolean;
  AFechaDesde, AFechaHasta: TDateTime; const ASearch: string);
var
  LFrm: TfrmPlanificacionMasasProduccion;
begin
  LFrm := TfrmPlanificacionMasasProduccion.Create(AOwner);
  try
    LFrm.FEmpresaId := AEmpresaId;
    LFrm.FFechaEntregaVal := AFechaEntregaVal;
    LFrm.FEstadoIndex := AEstadoIndex;
    LFrm.FFiltrarFecha := AFiltrarFecha;
    LFrm.FFechaDesde := AFechaDesde;
    LFrm.FFechaHasta := AFechaHasta;
    LFrm.FSearch := ASearch;

    if Assigned(LFrm.pcModo) then
      LFrm.pcModo.ActivePage := LFrm.tsCalculoPedidos;

    LFrm.ShowModal;
  finally
    LFrm.Free;
  end;
end;

class procedure TfrmPlanificacionMasasProduccion.MostrarPlanReceta(AOwner: TComponent; ARecetaId: Integer);
var
  LFrm: TfrmPlanificacionMasasProduccion;
begin
  if Assigned(frmMain) then
  begin
    LFrm := TfrmPlanificacionMasasProduccion(frmMain.OpenFormInTab(TfrmPlanificacionMasasProduccion, 'Planificación de Producción'));
    if Assigned(LFrm) then
    begin
      LFrm.CargarRecetasPlan;
      if ARecetaId > 0 then
        LFrm.SeleccionarReceta(ARecetaId);
    end;
  end
  else
  begin
    LFrm := TfrmPlanificacionMasasProduccion.Create(AOwner);
    try
      if Assigned(LFrm.pcModo) then
        LFrm.pcModo.ActivePage := LFrm.tsPlanManual;
      LFrm.CargarRecetasPlan;
      if ARecetaId > 0 then
        LFrm.SeleccionarReceta(ARecetaId);
      LFrm.ShowModal;
    finally
      LFrm.Free;
    end;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.FormCreate(Sender: TObject);
begin
  TAppTheme.ApplyToForm(Self);
  DoubleBuffered := True;
  pnlPlanLeft.DoubleBuffered := True;
  sbxLineasMasa.DoubleBuffered := True;
  pnlPlanRight.DoubleBuffered := True;
  tvProduccion.DoubleBuffered := True;
  FMaxArticuloDroppedWidth := 580;

  FPlan := TPlanFabricacion.Create;
  FProductosFinales := TObjectList<TProductoFinalItem>.Create(True);
  FRepartoRows := TObjectList<TMasaRepartoRow>.Create(True);
  FUpdatingControls := False;

  FEmpresaId := 0;
  FFechaEntregaVal := 0;
  FEstadoIndex := 0;
  FFiltrarFecha := False;
  FFechaDesde := Date;
  FFechaHasta := Date + 30;
  FSearch := '';

  qAlmacenes.Connection := dmgMain.dbConn;
  qObradores.Connection := dmgMain.dbConn;
  qCargaPlan.Connection := dmgMain.dbConn;
  qExec.Connection := dmgMain.dbConn;

  ConfigurarEstructuraTablas;
  SetupGrids;
  InicializarPestanaCalendario;
end;

procedure TfrmPlanificacionMasasProduccion.FormDestroy(Sender: TObject);
begin
  FRepartoRows.Free;
  FProductosFinales.Free;
  FPlan.Free;
end;

procedure TfrmPlanificacionMasasProduccion.FormShow(Sender: TObject);
begin
  dtpFechaLote.Date := Date;
  CargarAlmacenes;
  CargarObradores;
  CargarRecetasPlan;

  if (FEmpresaId > 0) and (pcModo.ActivePage = tsCalculoPedidos) then
  begin
    chkSoloConDeficit.Visible := True;
    btnRecalcular.Visible := True;
    btnGenerarLoteReceta.Visible := True;
    btnGenerarTodosLotes.Visible := True;
    CargarDatosPlanificacion;
  end
  else
  begin
    pcModo.ActivePage := tsPlanManual;
    chkSoloConDeficit.Visible := False;
    btnRecalcular.Visible := False;
    btnGenerarLoteReceta.Visible := False;
    btnGenerarTodosLotes.Visible := False;

    // Disparar selección de primera receta (preferiblemente 2º Empaste Masa Base)
    if cbbRecetaPlan.Items.Count > 0 then
    begin
      cbbRecetaPlan.ItemIndex := 0;
      cbbRecetaPlanChange(nil);
    end;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.pcModoChange(Sender: TObject);
begin
  if pcModo.ActivePage = tsPlanManual then
  begin
    chkSoloConDeficit.Visible := False;
    btnRecalcular.Visible := False;
    btnGenerarLoteReceta.Visible := False;
    btnGenerarTodosLotes.Visible := False;
    btnGuardarPlan.Visible := True;
    btnVerInforme.Visible := True;
    btnVerOrdenesFabricacion.Visible := True;
  end
  else
  begin
    chkSoloConDeficit.Visible := True;
    btnRecalcular.Visible := True;
    btnGenerarLoteReceta.Visible := True;
    btnGenerarTodosLotes.Visible := True;
    btnGuardarPlan.Visible := False;
    btnVerInforme.Visible := False;
    btnVerOrdenesFabricacion.Visible := True;
    if mtRecetas.IsEmpty then
      CargarDatosPlanificacion;
    if pcModo.ActivePage = FTabCalendario then
      RefrescarCalendarioVisual;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.dtpFechaLoteChange(Sender: TObject);
begin
  if FUpdatingControls then Exit;
  if FPlan <> nil then
  begin
    FPlan.Fecha := dtpFechaLote.Date;
    CargarPlanDesdeFecha(dtpFechaLote.Date);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.CargarPlanDesdeFecha(AFecha: TDateTime);
var
  LQry, LQryRep: TFDQuery;
  LRecetaId, LObradorId, LNumMasasTotal, i: Integer;
  LRecetaDesc, LPrefijo: string;
  LEsMasaBase, LEsMasaMadre: Boolean;
  LMasa: TMasaBaseItem;
  LSabor: TSaborRepartoItem;
  LFoundOrders: Boolean;
  LExisteMasaMadre: Boolean;
  LProdMatch: TProductoFinalItem;
  LMasasMananaGuardadas, LPos, LPos2: Integer;
  LObsMM, LSub: string;
begin
  LMasasMananaGuardadas := 0;
  LQry := TFDQuery.Create(nil);
  LQryRep := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;
    LQryRep.Connection := dmgMain.dbConn;

    // Buscar si existen elaboraciones para esta fecha
    LQry.SQL.Text :=
      'SELECT e.id, e.tipo, e.id_obrador, e.id_receta, r.descripcion AS receta_desc, ' +
      '       COALESCE(r.prefijo_lote, ''P'') AS prefijo_lote, r.es_masa_base, r.es_masa_madre, ' +
      '       e.lote_id, e.multiplicador, e.numero_masas, e.observaciones, e.elaboracion_origen_id, ' +
      '       COALESCE(l.codigo_antiguo, CAST(l.codigo AS CHAR), '''') AS lote_codigo, ' +
      '       COALESCE(l_orig.codigo_antiguo, CAST(l_orig.codigo AS CHAR), '''') AS lote_1e_codigo ' +
      'FROM ob_elaboraciones e ' +
      'JOIN ob_recetas r ON e.id_receta = r.id ' +
      'LEFT JOIN ge_lotes l ON e.lote_id = l.id ' +
      'LEFT JOIN ob_elaboraciones e_orig ON e.elaboracion_origen_id = e_orig.id ' +
      'LEFT JOIN ge_lotes l_orig ON e_orig.lote_id = l_orig.id ' +
      'WHERE e.fecha = :fecha ' +
      'ORDER BY r.es_masa_base DESC, r.es_masa_madre DESC, e.id ASC';
    LQry.ParamByName('fecha').AsDate := AFecha;
    LQry.Open;

    if LQry.IsEmpty then
    begin
      // No hay órdenes guardadas para esta fecha -> Generar estructura limpia por defecto
      btnAplicarMasasClick(nil);
      Exit;
    end;

    // Verificar si hay órdenes de masa base
    LFoundOrders := False;
    LEsMasaBase := True;
    LEsMasaMadre := False;
    LObradorId := 1;
    LRecetaDesc := '';
    LPrefijo := 'P';

    // 1. Detectar receta principal (prioridad: segundo_empaste o es_masa_base)
    LQry.First;
    LRecetaId := 0;
    while not LQry.Eof do
    begin
      if (LQry.FieldByName('tipo').AsString = 'segundo_empaste') or (LQry.FieldByName('es_masa_base').AsInteger = 1) then
      begin
        LRecetaId := LQry.FieldByName('id_receta').AsInteger;
        LRecetaDesc := LQry.FieldByName('receta_desc').AsString;
        LPrefijo := LQry.FieldByName('prefijo_lote').AsString;
        LEsMasaBase := True;
        LEsMasaMadre := False;
        LObradorId := LQry.FieldByName('id_obrador').AsInteger;
        LFoundOrders := True;
        Break;
      end;
      LQry.Next;
    end;

    // Si no hay segundo_empaste ni masa base, tomar la primera orden encontrada
    if not LFoundOrders then
    begin
      LQry.First;
      LRecetaId := LQry.FieldByName('id_receta').AsInteger;
      LRecetaDesc := LQry.FieldByName('receta_desc').AsString;
      LPrefijo := LQry.FieldByName('prefijo_lote').AsString;
      LEsMasaBase := (LQry.FieldByName('es_masa_base').AsInteger = 1);
      LEsMasaMadre := (LQry.FieldByName('es_masa_madre').AsInteger = 1);
      LObradorId := LQry.FieldByName('id_obrador').AsInteger;
    end;

    // Seleccionar combo de obrador y receta
    FUpdatingControls := True;
    try
      for i := 0 to cbbObrador.Items.Count - 1 do
      begin
        if Integer(IntPtr(cbbObrador.Items.Objects[i])) = LObradorId then
        begin
          cbbObrador.ItemIndex := i;
          FPlan.ObradorId := LObradorId;
          FPlan.ObradorNombre := cbbObrador.Text;
          SincronizarAlmacenConObrador;
          Break;
        end;
      end;

      for i := 0 to cbbRecetaPlan.Items.Count - 1 do
      begin
        if Integer(IntPtr(cbbRecetaPlan.Items.Objects[i])) = LRecetaId then
        begin
          cbbRecetaPlan.ItemIndex := i;
          Break;
        end;
      end;
    finally
      FUpdatingControls := False;
    end;

    // Configurar FPlan básico
    FPlan.RecetaPrincipalId := LRecetaId;
    FPlan.RecetaPrincipalDesc := LRecetaDesc;
    FPlan.PrefijoPrincipal := LPrefijo;
    FPlan.EsMasaBase := LEsMasaBase;
    FPlan.EsMasaMadre := LEsMasaMadre;
    FPlan.Fecha := AFecha;
    FPlan.Masas.Clear;

    if FPlan.RecetaMasaMadreId <= 0 then
      FPlan.RecetaMasaMadreId := ObtenerIdRecetaMasaMadre;

    // 2. Extraer lotes de Masa Madre y 1er Empaste si existen
    LQry.First;
    while not LQry.Eof do
    begin
      if LQry.FieldByName('es_masa_madre').AsInteger = 1 then
      begin
        FPlan.LoteMasaMadreCodigo := LQry.FieldByName('lote_codigo').AsString;
        LExisteMasaMadre := True;
        LObsMM := LQry.FieldByName('observaciones').AsString;
        LPos := Pos('Reserva Mañana [', LObsMM);
        if LPos > 0 then
        begin
          LSub := Copy(LObsMM, LPos + Length('Reserva Mañana ['), 50);
          LPos2 := Pos(' masas', LSub);
          if LPos2 > 0 then
            LMasasMananaGuardadas := StrToIntDef(Trim(Copy(LSub, 1, LPos2 - 1)), 0);
        end;
      end
      else if LQry.FieldByName('id_receta').AsInteger = 22 then
      begin
        FPlan.Lote1erEmpasteCodigo := LQry.FieldByName('lote_codigo').AsString;
      end;
      LQry.Next;
    end;

    // 3. Extraer Masas de 2º Empaste / Elaboraciones Principales y sus repartos
    LQry.First;
    LNumMasasTotal := 0;
    while not LQry.Eof do
    begin
      if (LEsMasaBase and (LQry.FieldByName('tipo').AsString = 'segundo_empaste')) or
         ((not LEsMasaBase) and (LQry.FieldByName('id_receta').AsInteger = LRecetaId)) then
      begin
        Inc(LNumMasasTotal);
        LMasa := TMasaBaseItem.Create(LNumMasasTotal);
        LMasa.NombreMasa := Format('Masa %d', [LNumMasasTotal]);
        LMasa.Multiplicador := LQry.FieldByName('multiplicador').AsFloat;
        if LMasa.Multiplicador <= 0.001 then LMasa.Multiplicador := 1.0;
        LMasa.EsExistente := True;
        LMasa.LoteCodigo := LQry.FieldByName('lote_codigo').AsString;
        LMasa.Lote1erEmpasteCodigo := LQry.FieldByName('lote_1e_codigo').AsString;
        if (FPlan.Lote1erEmpasteCodigo = '') and (LMasa.Lote1erEmpasteCodigo <> '') then
          FPlan.Lote1erEmpasteCodigo := LMasa.Lote1erEmpasteCodigo;

        // Cargar repartos de esta elaboración
        AsegurarColumnaArticuloReparto;
        LQryRep.Close;
        LQryRep.SQL.Text :=
          'SELECT rep.id, rep.sabor, rep.porcentaje, rep.cantidad, ' +
          '       COALESCE(l.codigo_antiguo, CAST(l.codigo AS CHAR), '''') AS lote_codigo, ' +
          '       COALESCE(NULLIF(rep.id_articulo, 0), l.id_articulo) AS id_articulo, ' +
          '       a.descripcion AS art_desc, ' +
          '       COALESCE(r.prefijo_lote, ''P'') AS prefijo_lote, ' +
          '       COALESCE(rp.unidades_base, 189.0) AS unidades_base ' +
          'FROM ob_elaboraciones_reparto rep ' +
          'LEFT JOIN ge_lotes l ON rep.lote_inclusion_id = l.id ' +
          'LEFT JOIN ge_articulos a ON COALESCE(NULLIF(rep.id_articulo, 0), l.id_articulo) = a.id ' +
          'LEFT JOIN ob_recetas r ON COALESCE( ' +
          '  (SELECT rp2.receta_id FROM ob_recetas_productos rp2 WHERE rp2.articulo_id = COALESCE(NULLIF(rep.id_articulo, 0), l.id_articulo) AND rp2.activo = 1 LIMIT 1), ' +
          '  l.id_receta ' +
          ') = r.id ' +
          'LEFT JOIN ob_recetas_productos rp ON rp.articulo_id = COALESCE(NULLIF(rep.id_articulo, 0), l.id_articulo) AND rp.activo = 1 ' +
          'WHERE rep.elaboracion_id = :id ' +
          'ORDER BY rep.id ASC';
        LQryRep.ParamByName('id').AsInteger := LQry.FieldByName('id').AsInteger;
        LQryRep.Open;

        while not LQryRep.Eof do
        begin
          LSabor := TSaborRepartoItem.Create;
          LSabor.ArticuloId := LQryRep.FieldByName('id_articulo').AsInteger;
          LSabor.ArticuloDesc := LQryRep.FieldByName('art_desc').AsString;
          if LSabor.ArticuloDesc = '' then
            LSabor.ArticuloDesc := LQryRep.FieldByName('sabor').AsString;
          LSabor.Porcentaje := LQryRep.FieldByName('porcentaje').AsFloat;
          LSabor.UnidadesCalculadas := Round(LQryRep.FieldByName('cantidad').AsFloat);
          LSabor.UnidadesXL := LSabor.UnidadesCalculadas;
          LSabor.UnidadesBase := LQryRep.FieldByName('unidades_base').AsFloat;
          LSabor.PrefijoLote := LQryRep.FieldByName('prefijo_lote').AsString;
          LSabor.LoteCodigo := LQryRep.FieldByName('lote_codigo').AsString;

          // Buscar datos de producto final si es posible
          for i := 0 to FProductosFinales.Count - 1 do
          begin
            if FProductosFinales[i].ArticuloId = LSabor.ArticuloId then
            begin
              LSabor.RecetaId := FProductosFinales[i].RecetaId;
              LSabor.RecetaDesc := FProductosFinales[i].RecetaDesc;
              Break;
            end;
          end;

          LMasa.Sabores.Add(LSabor);
          LQryRep.Next;
        end;

        // Si no tenía repartos en ob_elaboraciones_reparto pero sí orden de elaboración
        if LMasa.Sabores.Count = 0 then
        begin
          if FProductosFinales.Count > 0 then
          begin
            LProdMatch := FProductosFinales[0];
            LSabor := TSaborRepartoItem.Create;
            LSabor.ArticuloId := LProdMatch.ArticuloId;
            LSabor.ArticuloDesc := LProdMatch.ArticuloDesc;
            LSabor.RecetaId := LProdMatch.RecetaId;
            LSabor.RecetaDesc := LProdMatch.RecetaDesc;
            LSabor.Porcentaje := 100.0;
            LSabor.UnidadesBase := LProdMatch.UnidadesBase;
            LSabor.UnidadesCalculadas := Round(LProdMatch.UnidadesBase);
            LSabor.UnidadesXL := LSabor.UnidadesCalculadas;
            LSabor.PrefijoLote := LProdMatch.PrefijoLote;
            LSabor.LoteCodigo := FormatearCodigoLoteSabor(LSabor.PrefijoLote, AFecha, LMasa.NumeroMasa, LMasa.LoteCodigo, 0);
            LMasa.Sabores.Add(LSabor);
          end;
        end;

        FPlan.Masas.Add(LMasa);
      end;
      LQry.Next;
    end;

    // Garantizar que cada masa tenga un lote de 1er empaste único y diferenciado
    if FPlan.EsMasaBase and (FPlan.Masas.Count > 0) then
    begin
      var LDictCheck1E := TDictionary<string, Boolean>.Create;
      try
        for i := 0 to FPlan.Masas.Count - 1 do
        begin
          LMasa := FPlan.Masas[i];
          var LCod := Trim(LMasa.Lote1erEmpasteCodigo);
          if (LCod = '') or LDictCheck1E.ContainsKey(LCod) then
            LMasa.Lote1erEmpasteCodigo := IntToStr(dmgMain.GetNextCodigoLote);
          LDictCheck1E.AddOrSetValue(Trim(LMasa.Lote1erEmpasteCodigo), True);
        end;
        FPlan.Lote1erEmpasteCodigo := FPlan.Masas[0].Lote1erEmpasteCodigo;
      finally
        LDictCheck1E.Free;
      end;
    end;

    if LNumMasasTotal > 0 then
      FPlan.CantidadMasasPrincipal := LNumMasasTotal
    else
      FPlan.CantidadMasasPrincipal := 1;

    // Si viene guardado de una orden previa, respetarlo; de lo contrario, poner por defecto el mismo número de masas a producir
    if LMasasMananaGuardadas > 0 then
      FPlan.MasasBaseManana := LMasasMananaGuardadas
    else
      FPlan.MasasBaseManana := FPlan.CantidadMasasPrincipal;

    // Regla de obrador: 2,0 kg de masa madre extra por cada masa del día
    FPlan.MasaMadreExtraKg := FPlan.MasasBaseManana * 2.0;

    FUpdatingControls := True;
    try
      edtCantidadMasas.Text := IntToStr(FPlan.CantidadMasasPrincipal);
      edtPesoMasaMadreKg.Text := FormatFloat('0.00', FPlan.MasaMadrePorMasaKg);
      edtMasasBaseManana.Text := IntToStr(FPlan.MasasBaseManana);
      edtMasaMadreExtraKg.Text := FormatFloat('0.00', FPlan.MasaMadreExtraKg);
      if (cbbPorcionMasa <> nil) and (FPlan.Masas.Count > 0) then
      begin
        var LFirstMult := FPlan.Masas[0].Multiplicador;
        if LFirstMult <= 0.30 then cbbPorcionMasa.ItemIndex := 3
        else if LFirstMult <= 0.60 then cbbPorcionMasa.ItemIndex := 2
        else if LFirstMult <= 0.85 then cbbPorcionMasa.ItemIndex := 1
        else cbbPorcionMasa.ItemIndex := 0;
      end;
    finally
      FUpdatingControls := False;
    end;

    // Actualizar visibilidad de paneles
    if FPlan.EsMasaBase then
    begin
      pnlMasaMadreParams.Visible := True;
      pnlRepartoSabores.Visible := True;
      lblSubrecetasInfo.Caption := Format('• Requiere 1er Empaste (Receta 22) y Masa Madre (Receta %d: %.2f kg/masa base)',
        [FPlan.RecetaMasaMadreId, FPlan.MasaMadrePorMasaKg]);
    end
    else if FPlan.EsMasaMadre then
    begin
      pnlMasaMadreParams.Visible := True;
      pnlRepartoSabores.Visible := False;
    end
    else
    begin
      pnlMasaMadreParams.Visible := False;
      pnlRepartoSabores.Visible := True;
      lblRepartoTitle.Caption := Format('Planificación de %s', [FPlan.RecetaPrincipalDesc]);
    end;

    FPlan.RecalcularTotales;
    ReconstruirFilasReparto;
    ActualizarArbolProduccion;
    ValidarSumaPorcentajesSlots;
  finally
    LQryRep.Free;
    LQry.Free;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.cbbAlmacenChange(Sender: TObject);
begin
  if FPlan <> nil then
  begin
    FPlan.AlmacenId := GetSelectedAlmacenId;
    if cbbAlmacen.ItemIndex >= 0 then
      FPlan.AlmacenNombre := cbbAlmacen.Text;
    ActualizarArbolProduccion;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.cbbObradorChange(Sender: TObject);
begin
  if FPlan <> nil then
  begin
    FPlan.ObradorId := GetSelectedObradorId;
    if cbbObrador.ItemIndex >= 0 then
      FPlan.ObradorNombre := cbbObrador.Text;
    SincronizarAlmacenConObrador;
    ActualizarArbolProduccion;
    if pcModo.ActivePageIndex = 1 then
      CargarDatosPlanificacion;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.CargarAlmacenes;
begin
  cbbAlmacen.Clear;
  qAlmacenes.Close;
  qAlmacenes.SQL.Text :=
    'SELECT id, descripcion FROM ge_almacenes WHERE activo = 1 ORDER BY descripcion ASC';
  qAlmacenes.Open;

  while not qAlmacenes.Eof do
  begin
    cbbAlmacen.Items.AddObject(qAlmacenes.FieldByName('descripcion').AsString,
      TObject(IntPtr(qAlmacenes.FieldByName('id').AsInteger)));
    qAlmacenes.Next;
  end;

  if cbbAlmacen.Items.Count > 0 then
  begin
    cbbAlmacen.ItemIndex := 0;
    FPlan.AlmacenId := GetSelectedAlmacenId;
    FPlan.AlmacenNombre := cbbAlmacen.Text;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.CargarObradores;
begin
  cbbObrador.Clear;
  qObradores.Close;
  qObradores.SQL.Text := 'SELECT id, nombre FROM ge_obradores WHERE activo = 1 ORDER BY id ASC';
  qObradores.Open;

  while not qObradores.Eof do
  begin
    cbbObrador.Items.AddObject(qObradores.FieldByName('nombre').AsString,
      TObject(IntPtr(qObradores.FieldByName('id').AsInteger)));
    qObradores.Next;
  end;

  if cbbObrador.Items.Count > 0 then
  begin
    cbbObrador.ItemIndex := 0;
    FPlan.ObradorId := GetSelectedObradorId;
    FPlan.ObradorNombre := cbbObrador.Text;
    SincronizarAlmacenConObrador;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.CargarRecetasPlan;
var
  LQry: TFDQuery;
  LDesc: string;
  LId: Integer;
  LProd: TProductoFinalItem;
  i: Integer;
begin
  cbbRecetaPlan.Clear;
  FProductosFinales.Clear;

  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;

    // 1. Cargar recetas principales para elaboración (Masa Base, Masa Madre, etc.)
    LQry.SQL.Text :=
      'SELECT id, descripcion, es_masa_madre, es_masa_base, prefijo_lote ' +
      'FROM ob_recetas WHERE activo = 1 ' +
      'ORDER BY es_masa_base DESC, es_masa_madre DESC, descripcion ASC';
    LQry.Open;

    while not LQry.Eof do
    begin
      LId := LQry.FieldByName('id').AsInteger;
      LDesc := LQry.FieldByName('descripcion').AsString;
      cbbRecetaPlan.Items.AddObject(LDesc, TObject(IntPtr(LId)));
      LQry.Next;
    end;
    SendMessage(cbbRecetaPlan.Handle, CB_SETDROPPEDWIDTH, 680, 0);

    // 2. Cargar los productos finales asignados a las recetas desde ge_articulos y ob_recetas_productos
    // Cada artículo final tiene asignada su receta y la cantidad resultante por masa (unidades_base)
    LQry.Close;
    LQry.SQL.Text :=
      'SELECT ' +
      '  rp.id AS receta_producto_id, ' +
      '  rp.articulo_id, ' +
      '  a.descripcion AS articulo_desc, ' +
      '  rp.receta_id, ' +
      '  r.descripcion AS receta_desc, ' +
      '  COALESCE(r.prefijo_lote, ''P'') AS prefijo_lote, ' +
      '  COALESCE(rp.unidades_base, 189.0) AS unidades_base ' +
      'FROM ob_recetas_productos rp ' +
      'JOIN ge_articulos a ON a.id = rp.articulo_id AND a.activo = 1 ' +
      'JOIN ob_recetas r ON r.id = rp.receta_id AND r.activo = 1 ' +
      'WHERE rp.activo = 1 ' +
      '  AND r.es_masa_base = 0 ' +
      '  AND r.es_masa_madre = 0 ' +
      '  AND r.id <> 22 ' +
      'ORDER BY a.descripcion ASC';
    LQry.Open;

    while not LQry.Eof do
    begin
      LProd := TProductoFinalItem.Create;
      LProd.ArticuloId := LQry.FieldByName('articulo_id').AsInteger;
      LProd.ArticuloDesc := LQry.FieldByName('articulo_desc').AsString;
      LProd.RecetaId := LQry.FieldByName('receta_id').AsInteger;
      LProd.RecetaDesc := LQry.FieldByName('receta_desc').AsString;
      LProd.PrefijoLote := LQry.FieldByName('prefijo_lote').AsString;
      LProd.UnidadesBase := LQry.FieldByName('unidades_base').AsFloat;
      if LProd.UnidadesBase <= 0 then LProd.UnidadesBase := 189.0;
      FProductosFinales.Add(LProd);

      LQry.Next;
    end;

    // Fallback: Si hubiera alguna receta final sin productos asignados en ob_recetas_productos, añadirla
    LQry.Close;
    LQry.SQL.Text :=
      'SELECT r.id, r.descripcion, COALESCE(r.prefijo_lote, ''P'') AS prefijo_lote ' +
      'FROM ob_recetas r ' +
      'WHERE r.activo = 1 AND r.es_masa_base = 0 AND r.es_masa_madre = 0 AND r.id <> 22 ' +
      '  AND r.id NOT IN (SELECT DISTINCT receta_id FROM ob_recetas_productos WHERE activo = 1) ' +
      'ORDER BY r.descripcion ASC';
    LQry.Open;
    while not LQry.Eof do
    begin
      LProd := TProductoFinalItem.Create;
      LProd.ArticuloId := 0;
      LProd.ArticuloDesc := LQry.FieldByName('descripcion').AsString;
      LProd.RecetaId := LQry.FieldByName('id').AsInteger;
      LProd.RecetaDesc := LQry.FieldByName('descripcion').AsString;
      LProd.PrefijoLote := LQry.FieldByName('prefijo_lote').AsString;
      LProd.UnidadesBase := 189.0;
      FProductosFinales.Add(LProd);

      LQry.Next;
    end;

    FMaxArticuloDroppedWidth := 580;
    for i := 0 to FProductosFinales.Count - 1 do
    begin
      var LTextW := Canvas.TextWidth(FProductosFinales[i].ArticuloDesc) + 50;
      if LTextW > FMaxArticuloDroppedWidth then
        FMaxArticuloDroppedWidth := LTextW;
    end;

    FPlan.RecetaMasaMadreId := ObtenerIdRecetaMasaMadre;
    FPlan.MasaMadrePorMasaKg := ObtenerPesoTotalRecetaKg(FPlan.RecetaMasaMadreId);
    FUpdatingControls := True;
    try
      edtPesoMasaMadreKg.Text := FormatFloat('0.00', FPlan.MasaMadrePorMasaKg);
    finally
      FUpdatingControls := False;
    end;

  finally
    LQry.Free;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.SeleccionarReceta(ARecetaId: Integer);
var
  I: Integer;
begin
  for I := 0 to cbbRecetaPlan.Items.Count - 1 do
  begin
    if Integer(IntPtr(cbbRecetaPlan.Items.Objects[I])) = ARecetaId then
    begin
      cbbRecetaPlan.ItemIndex := I;
      cbbRecetaPlanChange(cbbRecetaPlan);
      Break;
    end;
  end;
end;

function TfrmPlanificacionMasasProduccion.ObtenerIdRecetaMasaMadre: Integer;
var
  LQry: TFDQuery;
begin
  Result := 3;
  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;
    LQry.SQL.Text := 'SELECT id FROM ob_recetas WHERE es_masa_madre = 1 AND activo = 1 ORDER BY id ASC LIMIT 1';
    LQry.Open;
    if not LQry.IsEmpty then
      Result := LQry.FieldByName('id').AsInteger;
  except
    Result := 3;
  end;
  LQry.Free;
end;

function TfrmPlanificacionMasasProduccion.ObtenerPesoTotalRecetaKg(ARecetaId: Integer): Double;
var
  LQry: TFDQuery;
  LTotalG: Double;
begin
  Result := 10.005;
  if ARecetaId <= 0 then Exit;
  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;
    LQry.SQL.Text :=
      'SELECT COALESCE(rendimiento_canonico, 0) AS total_g ' +
      'FROM vw_recetas_rendimiento ' +
      'WHERE receta_id = :receta_id';
    LQry.ParamByName('receta_id').AsInteger := ARecetaId;
    LQry.Open;
    if not LQry.IsEmpty then
    begin
      LTotalG := LQry.FieldByName('total_g').AsFloat;
      if LTotalG > 0.1 then
        Result := RoundTo(LTotalG / 1000.0, -3);
    end;
  except
    Result := 10.005;
  end;
  LQry.Free;
end;

function TfrmPlanificacionMasasProduccion.ObtenerAlmacenDeObrador(AObradorId: Integer): Integer;
var
  LQry: TFDQuery;
  LNombreObrador: string;
begin
  Result := 1;
  if AObradorId <= 0 then Exit;

  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;
    // 1. Consultar campo id_almacen configurado en ge_obradores
    LQry.SQL.Text := 'SELECT id_almacen, nombre FROM ge_obradores WHERE id = :id';
    LQry.ParamByName('id').AsInteger := AObradorId;
    LQry.Open;
    if not LQry.IsEmpty then
    begin
      if not LQry.FieldByName('id_almacen').IsNull and (LQry.FieldByName('id_almacen').AsInteger > 0) then
      begin
        Result := LQry.FieldByName('id_almacen').AsInteger;
        Exit;
      end;
      LNombreObrador := UpperCase(Trim(LQry.FieldByName('nombre').AsString));
    end;

    // 2. Fallback heurístico por concordancia de nombre
    LQry.Close;
    if Pos('PARQUE', LNombreObrador) > 0 then
    begin
      LQry.SQL.Text := 'SELECT id FROM ge_almacenes WHERE descripcion LIKE ''%PARQUE%'' AND activo = 1 LIMIT 1';
      LQry.Open;
      if not LQry.IsEmpty then Result := LQry.FieldByName('id').AsInteger;
    end
    else if Pos('PANETTONE', LNombreObrador) > 0 then
    begin
      LQry.SQL.Text := 'SELECT id FROM ge_almacenes WHERE descripcion LIKE ''%PANETTONE%'' AND activo = 1 LIMIT 1';
      LQry.Open;
      if not LQry.IsEmpty then Result := LQry.FieldByName('id').AsInteger;
    end
    else if Pos('NOVELDA', LNombreObrador) > 0 then
    begin
      LQry.SQL.Text := 'SELECT id FROM ge_almacenes WHERE descripcion LIKE ''%NOVELDA%'' AND activo = 1 LIMIT 1';
      LQry.Open;
      if not LQry.IsEmpty then Result := LQry.FieldByName('id').AsInteger;
    end;
  finally
    LQry.Free;
  end;
end;

function TfrmPlanificacionMasasProduccion.ObtenerCapacidadObrador(AObradorId: Integer): Double;
var
  LQry: TFDQuery;
begin
  Result := 0;
  if AObradorId <= 0 then Exit;
  LQry := TFDQuery.Create(nil);
  try
    try
      LQry.Connection := dmgMain.dbConn;
      LQry.SQL.Text := 'SELECT COALESCE(capacidad_produccion, 0) AS cap FROM ge_obradores WHERE id = :id';
      LQry.ParamByName('id').AsInteger := AObradorId;
      LQry.Open;
      if not LQry.IsEmpty then
        Result := Max(0.0, LQry.FieldByName('cap').AsFloat);
    except
      Result := 0;
    end;
  finally
    LQry.Free;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.SincronizarAlmacenConObrador;
var
  LObradorId, LAlmId, i: Integer;
begin
  LObradorId := GetSelectedObradorId;
  LAlmId := ObtenerAlmacenDeObrador(LObradorId);

  for i := 0 to cbbAlmacen.Items.Count - 1 do
  begin
    if Integer(IntPtr(cbbAlmacen.Items.Objects[i])) = LAlmId then
    begin
      cbbAlmacen.ItemIndex := i;
      Break;
    end;
  end;

  if FPlan <> nil then
  begin
    FPlan.AlmacenId := LAlmId;
    if cbbAlmacen.ItemIndex >= 0 then
      FPlan.AlmacenNombre := cbbAlmacen.Text;
  end;
end;

function TfrmPlanificacionMasasProduccion.GetSelectedAlmacenId: Integer;
var
  LObrId: Integer;
begin
  LObrId := GetSelectedObradorId;
  Result := ObtenerAlmacenDeObrador(LObrId);

  if Result <= 0 then
  begin
    if (cbbAlmacen.ItemIndex >= 0) and (cbbAlmacen.Items.Objects[cbbAlmacen.ItemIndex] <> nil) then
      Result := Integer(IntPtr(cbbAlmacen.Items.Objects[cbbAlmacen.ItemIndex]));
  end;

  if Result <= 0 then Result := 1;
end;

function TfrmPlanificacionMasasProduccion.GetSelectedObradorId: Integer;
begin
  Result := 1;
  if (cbbObrador.ItemIndex >= 0) and (cbbObrador.Items.Objects[cbbObrador.ItemIndex] <> nil) then
    Result := Integer(IntPtr(cbbObrador.Items.Objects[cbbObrador.ItemIndex]));
end;

procedure TfrmPlanificacionMasasProduccion.cbbRecetaPlanChange(Sender: TObject);
var
  LRecetaId: Integer;
  LQry: TFDQuery;
  LPesoMM: Double;
begin
  if cbbRecetaPlan.ItemIndex < 0 then Exit;
  LRecetaId := Integer(IntPtr(cbbRecetaPlan.Items.Objects[cbbRecetaPlan.ItemIndex]));
  if LRecetaId <= 0 then Exit;

  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;
    LQry.SQL.Text := 'SELECT id, descripcion, es_masa_madre, es_masa_base, prefijo_lote FROM ob_recetas WHERE id = :id';
    LQry.ParamByName('id').AsInteger := LRecetaId;
    LQry.Open;

    if not LQry.IsEmpty then
    begin
      FPlan.RecetaPrincipalId := LRecetaId;
      FPlan.RecetaPrincipalDesc := LQry.FieldByName('descripcion').AsString;
      FPlan.PrefijoPrincipal := LQry.FieldByName('prefijo_lote').AsString;
      FPlan.EsMasaBase := (LQry.FieldByName('es_masa_base').AsInteger = 1);
      FPlan.EsMasaMadre := (LQry.FieldByName('es_masa_madre').AsInteger = 1);
      FPlan.CantidadMasasPrincipal := StrToIntDef(Trim(edtCantidadMasas.Text), 1);

      if FPlan.RecetaMasaMadreId <= 0 then
        FPlan.RecetaMasaMadreId := ObtenerIdRecetaMasaMadre;

      if FPlan.EsMasaMadre then
        LPesoMM := ObtenerPesoTotalRecetaKg(LRecetaId)
      else
        LPesoMM := ObtenerPesoTotalRecetaKg(FPlan.RecetaMasaMadreId);

      if LPesoMM > 0.001 then
        FPlan.MasaMadrePorMasaKg := LPesoMM;

      FUpdatingControls := True;
      try
        edtPesoMasaMadreKg.Text := FormatFloat('0.00', FPlan.MasaMadrePorMasaKg);
      finally
        FUpdatingControls := False;
      end;

      if FPlan.EsMasaBase then
      begin
        pnlMasaMadreParams.Visible := True;
        pnlRepartoSabores.Visible := True;
        lblSubrecetasInfo.Caption := Format('• Requiere 1er Empaste (Receta 22) y Masa Madre (Receta %d: %.2f kg/masa base)',
          [FPlan.RecetaMasaMadreId, FPlan.MasaMadrePorMasaKg]);
        lblMasaMadreManana.Caption := Format('Masas base a producir MAÑANA (%.1f kg c/u):', [FPlan.MasaMadrePorMasaKg]);
        lblMasaMadreManana.Visible := True;
        edtMasasBaseManana.Visible := True;
        lblMasaMadreExtra.Caption := 'Masa Madre EXTRA calculada (kg):';
        lblMasaMadreExtra.Visible := True;
        edtMasaMadreExtraKg.Visible := True;
      end
      else if FPlan.EsMasaMadre then
      begin
        pnlMasaMadreParams.Visible := True;
        pnlRepartoSabores.Visible := False;
        lblSubrecetasInfo.Caption := Format('• Receta de Masa Madre para refrescos (%.2f kg por cada masa base)',
          [FPlan.MasaMadrePorMasaKg]);
        lblMasaMadreManana.Caption := Format('Masas base a producir MAÑANA (%.1f kg c/u):', [FPlan.MasaMadrePorMasaKg]);
        lblMasaMadreManana.Visible := True;
        edtMasasBaseManana.Visible := True;
        lblMasaMadreExtra.Caption := 'Masa Madre EXTRA calculada (kg):';
        lblMasaMadreExtra.Visible := True;
        edtMasaMadreExtraKg.Visible := True;
      end
      else
      begin
        pnlMasaMadreParams.Visible := False;
        pnlRepartoSabores.Visible := True;
        lblRepartoTitle.Caption := Format('Planificación de %s', [FPlan.RecetaPrincipalDesc]);
      end;

      btnAplicarMasasClick(nil);
    end;
  finally
    LQry.Free;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.edtPesoMasaMadreKgChange(Sender: TObject);
var
  LVal: Double;
  LText: string;
begin
  if FUpdatingControls then Exit;
  if FPlan <> nil then
  begin
    LText := Trim(edtPesoMasaMadreKg.Text);
    LText := StringReplace(LText, '.', FormatSettings.DecimalSeparator, [rfReplaceAll]);
    LText := StringReplace(LText, ',', FormatSettings.DecimalSeparator, [rfReplaceAll]);
    if TryStrToFloat(LText, LVal) and (LVal > 0) then
      FPlan.MasaMadrePorMasaKg := LVal
    else
      FPlan.MasaMadrePorMasaKg := 10.005;

    FPlan.RecalcularTotales;
    ActualizarArbolProduccion;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.edtCantidadMasasKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_RETURN then
  begin
    Key := 0;
    btnAplicarMasasClick(nil);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.edtCantidadMasasExit(Sender: TObject);
var
  N: Integer;
begin
  N := StrToIntDef(Trim(edtCantidadMasas.Text), 1);
  if (FPlan = nil) or (N <> FPlan.CantidadMasasPrincipal) then
    btnAplicarMasasClick(nil);
end;

procedure TfrmPlanificacionMasasProduccion.edtCantidadMasasChange(Sender: TObject);
var
  NMasas: Integer;
begin
  if FUpdatingControls then Exit;
  if FPlan = nil then Exit;

  NMasas := StrToIntDef(Trim(edtCantidadMasas.Text), 0);
  if NMasas > 0 then
  begin
    FPlan.MasasBaseManana := NMasas;
    // Regla de obrador: 2,0 kg de masa madre extra por cada masa del día
    FPlan.MasaMadreExtraKg := FPlan.MasasBaseManana * 2.0;

    FUpdatingControls := True;
    try
      edtMasasBaseManana.Text := IntToStr(FPlan.MasasBaseManana);
      edtMasaMadreExtraKg.Text := FormatFloat('0.00', FPlan.MasaMadreExtraKg);
    finally
      FUpdatingControls := False;
    end;

    FPlan.RecalcularTotales;
    ActualizarArbolProduccion;
  end;
end;

function TfrmPlanificacionMasasProduccion.GetPorcionMultiplicador: Double;
begin
  if cbbPorcionMasa <> nil then
  begin
    case cbbPorcionMasa.ItemIndex of
      1: Result := 0.75;
      2: Result := 0.50;
      3: Result := 0.25;
    else
      Result := 1.0;
    end;
  end
  else
    Result := 1.0;
end;

procedure TfrmPlanificacionMasasProduccion.btnAplicarMasasClick(Sender: TObject);
var
  NMasas, StartNum, i, LTotalHoy, LNextAutoLote: Integer;
  LMasa: TMasaBaseItem;
  LSabor: TSaborRepartoItem;
  LQry: TFDQuery;
  LMult: Double;
begin
  LockWindowUpdate(Self.Handle);
  try
    NMasas := StrToIntDef(Trim(edtCantidadMasas.Text), 1);
    if NMasas < 1 then NMasas := 1;
    FPlan.CantidadMasasPrincipal := NMasas;
    LMult := GetPorcionMultiplicador;

    FPlan.Masas.Clear;

    LNextAutoLote := dmgMain.GetNextCodigoLote;

    if FPlan.EsMasaBase then
    begin
      FPlan.LoteMasaMadreCodigo := IntToStr(LNextAutoLote);
      Inc(LNextAutoLote);

      LQry := TFDQuery.Create(nil);
      try
        LQry.Connection := dmgMain.dbConn;
        LQry.SQL.Text :=
          'SELECT COUNT(*) AS total_hoy FROM ge_lotes ' +
          'WHERE fecha = :fecha AND id_receta = :id_receta AND activo = 1';
        LQry.ParamByName('fecha').AsDate := dtpFechaLote.Date;
        LQry.ParamByName('id_receta').AsInteger := FPlan.RecetaPrincipalId;
        LQry.Open;
        LTotalHoy := LQry.FieldByName('total_hoy').AsInteger;
        StartNum := LTotalHoy + 1;
      finally
        LQry.Free;
      end;

      // 1. Crear las masas y asignar el lote correlativo de 1er Empaste a cada una
      for i := 1 to NMasas do
      begin
        LMasa := TMasaBaseItem.Create(StartNum + i - 1);
        LMasa.NombreMasa := Format('Masa %d', [LMasa.NumeroMasa]);
        LMasa.Multiplicador := LMult;
        LMasa.EsExistente := False;
        LMasa.Lote1erEmpasteCodigo := IntToStr(LNextAutoLote);
        Inc(LNextAutoLote);

        // Inicializar cada masa al 100% sin ningún artículo asignado previamente
        LSabor := TSaborRepartoItem.Create;
        LSabor.ArticuloId := 0;
        LSabor.ArticuloDesc := '';
        LSabor.RecetaId := 0;
        LSabor.RecetaDesc := '';
        LSabor.Porcentaje := 100.0;
        LSabor.UnidadesBase := 189.0;
        LSabor.UnidadesCalculadas := Round(LSabor.UnidadesBase * LMult);
        LSabor.UnidadesXL := LSabor.UnidadesCalculadas;
        LSabor.UnidadesL := 0;
        LSabor.PrefijoLote := IfThen(FPlan.PrefijoPrincipal <> '', FPlan.PrefijoPrincipal, 'P');
        LSabor.LoteCodigo := '';
        LMasa.Sabores.Add(LSabor);

        FPlan.Masas.Add(LMasa);
      end;

      // 2. Asignar el lote correlativo de 2º Empaste a cada masa
      for i := 0 to FPlan.Masas.Count - 1 do
      begin
        FPlan.Masas[i].LoteCodigo := IntToStr(LNextAutoLote);
        Inc(LNextAutoLote);
      end;

      if FPlan.Masas.Count > 0 then
        FPlan.Lote1erEmpasteCodigo := FPlan.Masas[0].Lote1erEmpasteCodigo;
    end
    else if FPlan.EsMasaMadre then
    begin
      FPlan.LoteMasaMadreCodigo := IntToStr(LNextAutoLote);
    end
    else
    begin
      // Elaboración para receta normal / individual
      for i := 1 to NMasas do
      begin
        LMasa := TMasaBaseItem.Create(i);
        LMasa.NombreMasa := Format('%s %d', [FPlan.RecetaPrincipalDesc, i]);
        LMasa.Multiplicador := LMult;
        LMasa.EsExistente := False;
        LMasa.LoteCodigo := IntToStr(LNextAutoLote);
        Inc(LNextAutoLote);

        LSabor := TSaborRepartoItem.Create;
        LSabor.RecetaId := FPlan.RecetaPrincipalId;
        LSabor.RecetaDesc := FPlan.RecetaPrincipalDesc;
        LSabor.ArticuloDesc := FPlan.RecetaPrincipalDesc;
        LSabor.Porcentaje := 100.0;
        LSabor.UnidadesCalculadas := 1;
        LSabor.UnidadesXL := 1;
        LSabor.LoteCodigo := LMasa.LoteCodigo;
        LMasa.Sabores.Add(LSabor);

        FPlan.Masas.Add(LMasa);
      end;
    end;

    // Por defecto, la cantidad de masas de masa madre para el día siguiente se iguala a las masas a producir hoy
    FPlan.MasasBaseManana := NMasas;
    // Regla de obrador: 2,0 kg de masa madre extra por cada masa del día
    FPlan.MasaMadreExtraKg := FPlan.MasasBaseManana * 2.0;
    FUpdatingControls := True;
    try
      edtMasasBaseManana.Text := IntToStr(FPlan.MasasBaseManana);
      edtMasaMadreExtraKg.Text := FormatFloat('0.00', FPlan.MasaMadreExtraKg);
    finally
      FUpdatingControls := False;
    end;

    FPlan.RecalcularTotales;
    ReconstruirFilasReparto;
    ActualizarArbolProduccion;
    ValidarSumaPorcentajesSlots;
  finally
    LockWindowUpdate(0);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnAnadirMasasClick(Sender: TObject);
var
  NMasasNuevas, StartNum, i, LNextAutoLote: Integer;
  LMasa: TMasaBaseItem;
  LSabor: TSaborRepartoItem;
  LMult: Double;
begin
  if FPlan = nil then Exit;

  NMasasNuevas := StrToIntDef(Trim(edtCantidadMasas.Text), 1);
  if NMasasNuevas < 1 then NMasasNuevas := 1;
  LMult := GetPorcionMultiplicador;

  LockWindowUpdate(Self.Handle);
  try
    StartNum := FPlan.Masas.Count + 1;
    LNextAutoLote := dmgMain.GetNextCodigoLote;

    for i := 1 to NMasasNuevas do
    begin
      LMasa := TMasaBaseItem.Create(StartNum + i - 1);
      LMasa.NombreMasa := Format('Masa %d', [LMasa.NumeroMasa]);
      LMasa.Multiplicador := LMult;
      LMasa.EsExistente := False;

      if FPlan.EsMasaBase then
      begin
        LMasa.Lote1erEmpasteCodigo := IntToStr(LNextAutoLote);
        Inc(LNextAutoLote);
        LMasa.LoteCodigo := IntToStr(LNextAutoLote);
        Inc(LNextAutoLote);
      end
      else
      begin
        LMasa.LoteCodigo := IntToStr(LNextAutoLote);
        Inc(LNextAutoLote);
      end;

      LSabor := TSaborRepartoItem.Create;
      LSabor.ArticuloId := 0;
      LSabor.ArticuloDesc := '';
      LSabor.RecetaId := 0;
      LSabor.RecetaDesc := '';
      LSabor.Porcentaje := 100.0;
      LSabor.UnidadesBase := 189.0;
      LSabor.UnidadesCalculadas := Round(LSabor.UnidadesBase * LMult);
      LSabor.UnidadesXL := LSabor.UnidadesCalculadas;
      LSabor.UnidadesL := 0;
      LSabor.PrefijoLote := IfThen(FPlan.PrefijoPrincipal <> '', FPlan.PrefijoPrincipal, 'P');
      LSabor.LoteCodigo := '';
      LMasa.Sabores.Add(LSabor);

      FPlan.Masas.Add(LMasa);
    end;

    FPlan.CantidadMasasPrincipal := FPlan.Masas.Count;
    FPlan.MasasBaseManana := FPlan.Masas.Count;
    // Regla de obrador: 2,0 kg de masa madre extra por cada masa del día
    FPlan.MasaMadreExtraKg := FPlan.MasasBaseManana * 2.0;

    FUpdatingControls := True;
    try
      edtCantidadMasas.Text := '1';
      edtMasasBaseManana.Text := IntToStr(FPlan.MasasBaseManana);
      edtMasaMadreExtraKg.Text := FormatFloat('0.00', FPlan.MasaMadreExtraKg);
    finally
      FUpdatingControls := False;
    end;

    FPlan.RecalcularTotales;
    ReconstruirFilasReparto;
    ActualizarArbolProduccion;
    ValidarSumaPorcentajesSlots;
  finally
    LockWindowUpdate(0);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.edtMasasBaseMananaChange(Sender: TObject);
begin
  if FUpdatingControls then Exit;
  if FPlan <> nil then
  begin
    FPlan.MasasBaseManana := StrToIntDef(Trim(edtMasasBaseManana.Text), 0);
    // Regla de obrador: 2,0 kg de masa madre extra por cada masa del día
    FPlan.MasaMadreExtraKg := FPlan.MasasBaseManana * 2.0;

    FUpdatingControls := True;
    try
      edtMasaMadreExtraKg.Text := FormatFloat('0.00', FPlan.MasaMadreExtraKg);
    finally
      FUpdatingControls := False;
    end;

    FPlan.RecalcularTotales;
    ActualizarArbolProduccion;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.edtMasaMadreExtraKgChange(Sender: TObject);
var
  LVal: Double;
  LText: string;
begin
  if FUpdatingControls then Exit;
  if FPlan <> nil then
  begin
    LText := Trim(edtMasaMadreExtraKg.Text);
    LText := StringReplace(LText, '.', FormatSettings.DecimalSeparator, [rfReplaceAll]);
    LText := StringReplace(LText, ',', FormatSettings.DecimalSeparator, [rfReplaceAll]);
    if TryStrToFloat(LText, LVal) then
      FPlan.MasaMadreExtraKg := LVal
    else
      FPlan.MasaMadreExtraKg := 0.0;

    FPlan.RecalcularTotales;
    ActualizarArbolProduccion;
  end;
end;

{ TMasaRepartoRow }

constructor TMasaRepartoRow.Create(AOwner: TfrmPlanificacionMasasProduccion;
  AMasa: TMasaBaseItem; ASabor: TSaborRepartoItem; AIndexInMasa: Integer);
var
  i, LIdx: Integer;
  LProd: TProductoFinalItem;
begin
  inherited Create;
  OwnerForm := AOwner;
  MasaItem := AMasa;
  SaborItem := ASabor;

  RowPanel := TPanel.Create(AOwner.sbxLineasMasa);
  RowPanel.Parent := AOwner.sbxLineasMasa;
  RowPanel.Top := 999999;
  RowPanel.Width := AOwner.sbxLineasMasa.ClientWidth;
  RowPanel.Align := alTop;
  RowPanel.Height := 28;
  RowPanel.BevelOuter := bvNone;
  if (AIndexInMasa mod 2 = 0) then
    RowPanel.Color := clWhite
  else
    RowPanel.Color := $00F9F9F9;
  RowPanel.ParentBackground := False;

  // Label Masa
  lblMasa := TLabel.Create(RowPanel);
  lblMasa.Parent := RowPanel;
  lblMasa.Left := 8;
  lblMasa.Top := 5;
  lblMasa.Width := 65;
  lblMasa.Height := 18;
  var LPortionTag := '';
  if AMasa.Multiplicador < 0.99 then
    LPortionTag := Format(' (%.0f%%)', [AMasa.Multiplicador * 100]);

  if AMasa.Sabores.Count > 1 then
    lblMasa.Caption := Format('%s%s [%d]', [AMasa.NombreMasa, LPortionTag, AIndexInMasa + 1])
  else
    lblMasa.Caption := Format('%s%s', [AMasa.NombreMasa, LPortionTag]);
  lblMasa.Font.Name := 'Segoe UI';
  lblMasa.Font.Size := 9;
  lblMasa.Font.Style := [fsBold];
  if AMasa.EsExistente then
    lblMasa.Font.Color := $00804000
  else
    lblMasa.Font.Color := $00008000;
  lblMasa.Cursor := crHandPoint;
  lblMasa.Hint := 'Clic para cambiar la porción de masa (25, 50, 75 o 100%)';
  lblMasa.ShowHint := True;
  lblMasa.OnClick := OnMasaLabelClick;

  // ComboBox Porcentaje (Desplegable)
  cbbPorc := TComboBox.Create(RowPanel);
  cbbPorc.Parent := RowPanel;
  cbbPorc.Left := 74;
  cbbPorc.Top := 3;
  cbbPorc.Width := 62;
  cbbPorc.Height := 22;
  cbbPorc.Style := csDropDown;
  cbbPorc.DropDownCount := 10;
  cbbPorc.Font.Name := 'Segoe UI';
  cbbPorc.Font.Size := 9;
  cbbPorc.Font.Style := [fsBold];
  cbbPorc.Items.BeginUpdate;
  try
    cbbPorc.Items.Add('100%');
    cbbPorc.Items.Add('75%');
    cbbPorc.Items.Add('50%');
    cbbPorc.Items.Add('33,3%');
    cbbPorc.Items.Add('25%');
    cbbPorc.Items.Add('20%');
    cbbPorc.Items.Add('15%');
    cbbPorc.Items.Add('10%');
    cbbPorc.Items.Add('5%');
  finally
    cbbPorc.Items.EndUpdate;
  end;
  cbbPorc.Text := FormatFloat('0.#', ASabor.Porcentaje) + '%';
  cbbPorc.OnExit := OnPorcExit;
  cbbPorc.OnKeyDown := OnPorcKeyDown;
  cbbPorc.OnCloseUp := OnPorcCloseUp;

  // ComboBox Articulo Final / Formato
  cbbArticulo := TComboBox.Create(RowPanel);
  cbbArticulo.Parent := RowPanel;
  cbbArticulo.Left := 138;
  cbbArticulo.Top := 3;
  cbbArticulo.Width := 310;
  cbbArticulo.Height := 22;
  cbbArticulo.Style := csDropDownList;
  cbbArticulo.DropDownCount := 18;
  cbbArticulo.Font.Name := 'Segoe UI';
  cbbArticulo.Font.Size := 9;

  cbbArticulo.Items.BeginUpdate;
  try
    LIdx := -1;
    for i := 0 to OwnerForm.FProductosFinales.Count - 1 do
    begin
      LProd := OwnerForm.FProductosFinales[i];
      cbbArticulo.Items.AddObject(LProd.ArticuloDesc, LProd);
      if (ASabor.ArticuloId > 0) and (LProd.ArticuloId = ASabor.ArticuloId) then
        LIdx := cbbArticulo.Items.Count - 1
      else if (LIdx < 0) and (ASabor.RecetaId > 0) and (LProd.RecetaId = ASabor.RecetaId) then
        LIdx := cbbArticulo.Items.Count - 1;
    end;
  finally
    cbbArticulo.Items.EndUpdate;
  end;

  if (ASabor.ArticuloId > 0) and (LIdx >= 0) then
    cbbArticulo.ItemIndex := LIdx
  else
    cbbArticulo.ItemIndex := -1;

  cbbArticulo.OnChange := OnArticuloChange;

  if OwnerForm.FMaxArticuloDroppedWidth <= 0 then
    OwnerForm.FMaxArticuloDroppedWidth := 580;
  SendMessage(cbbArticulo.Handle, CB_SETDROPPEDWIDTH, OwnerForm.FMaxArticuloDroppedWidth, 0);

  // Edit Unidades
  edtUnidades := TEdit.Create(RowPanel);
  edtUnidades.Parent := RowPanel;
  edtUnidades.Left := 454;
  edtUnidades.Top := 3;
  edtUnidades.Width := 60;
  edtUnidades.Height := 22;
  edtUnidades.Alignment := taCenter;
  edtUnidades.NumbersOnly := True;
  edtUnidades.Font.Name := 'Segoe UI';
  edtUnidades.Font.Size := 9;
  edtUnidades.Font.Style := [fsBold];
  if ASabor.UnidadesXL > 0 then
    edtUnidades.Text := IntToStr(ASabor.UnidadesXL)
  else
    edtUnidades.Text := '';
  edtUnidades.OnExit := OnUnidadesExit;
  edtUnidades.OnKeyDown := OnUnidadesKeyDown;

  // Edit Total Acumulado del Artículo en su línea
  edtAcumulado := TEdit.Create(RowPanel);
  edtAcumulado.Parent := RowPanel;
  edtAcumulado.Left := 518;
  edtAcumulado.Top := 3;
  edtAcumulado.Width := 68;
  edtAcumulado.Height := 22;
  edtAcumulado.Alignment := taCenter;
  edtAcumulado.ReadOnly := True;
  edtAcumulado.TabStop := False;
  edtAcumulado.Color := $00F9F9F9;
  edtAcumulado.Font.Name := 'Segoe UI';
  edtAcumulado.Font.Size := 9;
  edtAcumulado.Font.Style := [fsBold];
  edtAcumulado.Font.Color := clNavy;
  edtAcumulado.Text := '';

  // Edit Lote
  edtLote := TEdit.Create(RowPanel);
  edtLote.Parent := RowPanel;
  edtLote.Left := 590;
  edtLote.Top := 3;
  edtLote.Width := 92;
  edtLote.Height := 22;
  edtLote.Alignment := taCenter;
  edtLote.Font.Name := 'Segoe UI';
  edtLote.Font.Size := 9;
  edtLote.Font.Style := [fsBold];
  edtLote.Text := ASabor.LoteCodigo;
  edtLote.OnChange := OnLoteChange;

  // Botón Eliminar
  btnEliminar := TSpeedButton.Create(RowPanel);
  btnEliminar.Parent := RowPanel;
  btnEliminar.Left := 688;
  btnEliminar.Top := 3;
  btnEliminar.Width := 22;
  btnEliminar.Height := 22;
  btnEliminar.Caption := '✕';
  btnEliminar.Flat := True;
  btnEliminar.Font.Name := 'Segoe UI';
  btnEliminar.Font.Style := [fsBold];
  btnEliminar.Font.Color := clRed;
  btnEliminar.Visible := (AMasa.Sabores.Count > 1);
  btnEliminar.OnClick := OnEliminarClick;
end;

destructor TMasaRepartoRow.Destroy;
begin
  if RowPanel <> nil then
  begin
    RowPanel.Parent := nil;
    FreeAndNil(RowPanel);
  end;
  inherited;
end;

procedure TMasaRepartoRow.OnMasaLabelClick(Sender: TObject);
var
  LStr: string;
  LPorc: Double;
  s: TSaborRepartoItem;
begin
  if (MasaItem = nil) or (OwnerForm = nil) or (OwnerForm.FPlan = nil) then Exit;
  LStr := FormatFloat('0', MasaItem.Multiplicador * 100);
  if InputQuery('Porción de Masa Base',
                Format('Indique la porción de la %s (25, 50, 75 o 100%%):', [MasaItem.NombreMasa]),
                LStr) then
  begin
    LPorc := StrToFloatDef(Trim(StringReplace(LStr, '%', '', [rfReplaceAll])), 100.0);
    if LPorc <= 0 then LPorc := 100.0;
    if LPorc > 100.0 then LPorc := 100.0;
    MasaItem.Multiplicador := LPorc / 100.0;

    for s in MasaItem.Sabores do
    begin
      s.UnidadesCalculadas := Round(s.UnidadesBase * (s.Porcentaje / 100.0) * MasaItem.Multiplicador);
      s.UnidadesXL := s.UnidadesCalculadas;
    end;

    OwnerForm.FPlan.RecalcularTotales;
    OwnerForm.ReconstruirFilasReparto;
    OwnerForm.ActualizarArbolProduccion;
  end;
end;

procedure TMasaRepartoRow.OnPorcKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_RETURN then
  begin
    Key := 0;
    OnPorcExit(Sender);
  end;
end;

procedure TMasaRepartoRow.OnPorcCloseUp(Sender: TObject);
begin
  if not OwnerForm.FUpdatingControls then
    OnPorcExit(Sender);
end;

procedure TMasaRepartoRow.OnPorcExit(Sender: TObject);
var
  LStr: string;
  LNewPorc, LDiff, LRestante: Double;
  LIdx: Integer;
  LRowAddedOrDeleted: Boolean;
begin
  if OwnerForm.FUpdatingControls then Exit;

  LStr := StringReplace(cbbPorc.Text, '%', '', [rfReplaceAll]);
  LStr := Trim(StringReplace(LStr, ',', FormatSettings.DecimalSeparator, [rfReplaceAll]));
  LStr := StringReplace(LStr, '.', FormatSettings.DecimalSeparator, [rfReplaceAll]);
  LNewPorc := StrToFloatDef(LStr, SaborItem.Porcentaje);

  if LNewPorc <= 0 then
    LNewPorc := 5.0
  else if LNewPorc > 100.0 then
    LNewPorc := 100.0;

  if SameValue(LNewPorc, SaborItem.Porcentaje, 0.05) then
  begin
    cbbPorc.Text := FormatFloat('0.#', SaborItem.Porcentaje) + '%';
    Exit;
  end;

  LIdx := MasaItem.Sabores.IndexOf(SaborItem);
  if LIdx < 0 then Exit;

  LRowAddedOrDeleted := False;

  if (LNewPorc < SaborItem.Porcentaje) and (MasaItem.Sabores.Count = LIdx + 1) then
  begin
    LRestante := 100.0 - (MasaItem.TotalPorcentaje - SaborItem.Porcentaje + LNewPorc);
    SaborItem.Porcentaje := LNewPorc;
    SaborItem.UnidadesCalculadas := Round(SaborItem.UnidadesBase * (LNewPorc / 100.0) * MasaItem.Multiplicador);
    SaborItem.UnidadesXL := SaborItem.UnidadesCalculadas;

    if LRestante > 0.1 then
    begin
      OwnerForm.AgregarLineaRestanteMasa(MasaItem, SaborItem, LRestante);
      LRowAddedOrDeleted := True;
    end;
  end
  else if MasaItem.Sabores.Count > LIdx + 1 then
  begin
    LDiff := LNewPorc - SaborItem.Porcentaje;
    SaborItem.Porcentaje := LNewPorc;
    SaborItem.UnidadesCalculadas := Round(SaborItem.UnidadesBase * (LNewPorc / 100.0) * MasaItem.Multiplicador);
    SaborItem.UnidadesXL := SaborItem.UnidadesCalculadas;

    var LNextSabor := MasaItem.Sabores[LIdx + 1];
    LNextSabor.Porcentaje := Max(0.0, LNextSabor.Porcentaje - LDiff);
    LNextSabor.UnidadesCalculadas := Round(LNextSabor.UnidadesBase * (LNextSabor.Porcentaje / 100.0) * MasaItem.Multiplicador);
    LNextSabor.UnidadesXL := LNextSabor.UnidadesCalculadas;

    if LNextSabor.Porcentaje <= 0.01 then
    begin
      MasaItem.Sabores.Delete(LIdx + 1);
      LRowAddedOrDeleted := True;
    end;
  end
  else
  begin
    SaborItem.Porcentaje := LNewPorc;
    SaborItem.UnidadesCalculadas := Round(SaborItem.UnidadesBase * (LNewPorc / 100.0) * MasaItem.Multiplicador);
    SaborItem.UnidadesXL := SaborItem.UnidadesCalculadas;
  end;

  if LRowAddedOrDeleted then
    OwnerForm.PostReconstruirFilasReparto
  else
    OwnerForm.SincronizarValoresFilas;
end;

procedure TMasaRepartoRow.OnUnidadesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_RETURN then
  begin
    Key := 0;
    OnUnidadesExit(Sender);
  end;
end;

procedure TMasaRepartoRow.OnUnidadesExit(Sender: TObject);
var
  NUds, LIdx: Integer;
  LBase, LPorcCalculado, LRestante, LDiff: Double;
  LRowAddedOrDeleted: Boolean;
begin
  if OwnerForm.FUpdatingControls then Exit;

  NUds := StrToIntDef(Trim(edtUnidades.Text), SaborItem.UnidadesXL);
  if NUds < 0 then NUds := 0;

  LBase := SaborItem.UnidadesBase * MasaItem.Multiplicador;
  if LBase <= 0.1 then LBase := 189.0 * MasaItem.Multiplicador;

  LPorcCalculado := (NUds / LBase) * 100.0;
  if LPorcCalculado > 100.0 then
  begin
    LPorcCalculado := 100.0;
    NUds := Round(LBase);
  end;

  LIdx := MasaItem.Sabores.IndexOf(SaborItem);
  if LIdx < 0 then Exit;

  LRowAddedOrDeleted := False;

  if (LPorcCalculado < SaborItem.Porcentaje) and (MasaItem.Sabores.Count = LIdx + 1) then
  begin
    LRestante := 100.0 - (MasaItem.TotalPorcentaje - SaborItem.Porcentaje + LPorcCalculado);
    SaborItem.Porcentaje := LPorcCalculado;
    SaborItem.UnidadesCalculadas := NUds;
    SaborItem.UnidadesXL := NUds;

    if LRestante > 0.1 then
    begin
      OwnerForm.AgregarLineaRestanteMasa(MasaItem, SaborItem, LRestante);
      LRowAddedOrDeleted := True;
    end;
  end
  else if MasaItem.Sabores.Count > LIdx + 1 then
  begin
    LDiff := LPorcCalculado - SaborItem.Porcentaje;
    SaborItem.Porcentaje := LPorcCalculado;
    SaborItem.UnidadesCalculadas := NUds;
    SaborItem.UnidadesXL := NUds;

    var LNextSabor := MasaItem.Sabores[LIdx + 1];
    LNextSabor.Porcentaje := Max(0.0, LNextSabor.Porcentaje - LDiff);
    LNextSabor.UnidadesCalculadas := Round(LNextSabor.UnidadesBase * (LNextSabor.Porcentaje / 100.0) * MasaItem.Multiplicador);
    LNextSabor.UnidadesXL := LNextSabor.UnidadesCalculadas;

    if LNextSabor.Porcentaje <= 0.01 then
    begin
      MasaItem.Sabores.Delete(LIdx + 1);
      LRowAddedOrDeleted := True;
    end;
  end
  else
  begin
    SaborItem.Porcentaje := LPorcCalculado;
    SaborItem.UnidadesCalculadas := NUds;
    SaborItem.UnidadesXL := NUds;
  end;

  if LRowAddedOrDeleted then
    OwnerForm.PostReconstruirFilasReparto
  else
    OwnerForm.SincronizarValoresFilas;
end;

procedure TMasaRepartoRow.OnArticuloChange(Sender: TObject);
var
  LProd: TProductoFinalItem;
begin
  if OwnerForm.FUpdatingControls then Exit;
  if (cbbArticulo.ItemIndex >= 0) and (cbbArticulo.Items.Objects[cbbArticulo.ItemIndex] <> nil) then
  begin
    LProd := TProductoFinalItem(cbbArticulo.Items.Objects[cbbArticulo.ItemIndex]);
    SaborItem.ArticuloId := LProd.ArticuloId;
    SaborItem.ArticuloDesc := LProd.ArticuloDesc;
    SaborItem.RecetaId := LProd.RecetaId;
    SaborItem.RecetaDesc := LProd.RecetaDesc;
    SaborItem.UnidadesBase := LProd.UnidadesBase;
    SaborItem.PrefijoLote := LProd.PrefijoLote;
    SaborItem.UnidadesCalculadas := Round(LProd.UnidadesBase * (SaborItem.Porcentaje / 100.0) * MasaItem.Multiplicador);
    SaborItem.UnidadesXL := SaborItem.UnidadesCalculadas;

    SaborItem.LoteCodigo := OwnerForm.FormatearCodigoLoteSabor(
      LProd.PrefijoLote, OwnerForm.dtpFechaLote.Date, MasaItem.NumeroMasa, MasaItem.LoteCodigo, MasaItem.Sabores.IndexOf(SaborItem));

    edtUnidades.Text := IntToStr(SaborItem.UnidadesXL);
    edtLote.Text := SaborItem.LoteCodigo;

    OwnerForm.ActualizarArbolProduccion;
    OwnerForm.ActualizarTotalesAcumulados;
  end
  else
  begin
    SaborItem.ArticuloId := 0;
    SaborItem.ArticuloDesc := '';
    SaborItem.RecetaId := 0;
    SaborItem.RecetaDesc := '';
    SaborItem.UnidadesBase := 0;
    SaborItem.PrefijoLote := '';
    SaborItem.UnidadesCalculadas := 0;
    SaborItem.UnidadesXL := 0;
    SaborItem.LoteCodigo := '';
    edtUnidades.Text := '';
    edtLote.Text := '';
    OwnerForm.ActualizarArbolProduccion;
    OwnerForm.ActualizarTotalesAcumulados;
  end;
end;

procedure TMasaRepartoRow.OnLoteChange(Sender: TObject);
begin
  if not OwnerForm.FUpdatingControls then
  begin
    SaborItem.LoteCodigo := Trim(edtLote.Text);
    OwnerForm.ActualizarArbolProduccion;
  end;
end;

procedure TMasaRepartoRow.OnEliminarClick(Sender: TObject);
var
  LIdx: Integer;
begin
  LIdx := MasaItem.Sabores.IndexOf(SaborItem);
  if (LIdx > 0) then
  begin
    var LPrevSabor := MasaItem.Sabores[LIdx - 1];
    LPrevSabor.Porcentaje := LPrevSabor.Porcentaje + SaborItem.Porcentaje;
    LPrevSabor.UnidadesCalculadas := Round(LPrevSabor.UnidadesBase * (LPrevSabor.Porcentaje / 100.0));
    LPrevSabor.UnidadesXL := LPrevSabor.UnidadesCalculadas;

    MasaItem.Sabores.Delete(LIdx);
    OwnerForm.PostReconstruirFilasReparto;
  end
  else if (LIdx = 0) and (MasaItem.Sabores.Count > 1) then
  begin
    var LNextSabor := MasaItem.Sabores[1];
    LNextSabor.Porcentaje := LNextSabor.Porcentaje + SaborItem.Porcentaje;
    LNextSabor.UnidadesCalculadas := Round(LNextSabor.UnidadesBase * (LNextSabor.Porcentaje / 100.0));
    LNextSabor.UnidadesXL := LNextSabor.UnidadesCalculadas;

    MasaItem.Sabores.Delete(0);
    OwnerForm.PostReconstruirFilasReparto;
  end;
end;

{ Métodos de Planificación y Reparto Dinámico }

procedure TfrmPlanificacionMasasProduccion.ReconstruirFilasReparto;
var
  mIdx, sIdx: Integer;
  LMasa: TMasaBaseItem;
  LSabor: TSaborRepartoItem;
  LRow: TMasaRepartoRow;
begin
  FUpdatingControls := True;
  LockWindowUpdate(Self.Handle);
  try
    if (ActiveControl <> nil) and (sbxLineasMasa.ContainsControl(ActiveControl)) then
      ActiveControl := nil;

    FRepartoRows.Clear;

    if FPlan <> nil then
    begin
      for mIdx := 0 to FPlan.Masas.Count - 1 do
      begin
        LMasa := FPlan.Masas[mIdx];
        for sIdx := 0 to LMasa.Sabores.Count - 1 do
        begin
          LSabor := LMasa.Sabores[sIdx];
          LRow := TMasaRepartoRow.Create(Self, LMasa, LSabor, sIdx);
          FRepartoRows.Add(LRow);
        end;
      end;
    end;
    ActualizarTotalesAcumulados;
  finally
    LockWindowUpdate(0);
    FUpdatingControls := False;
    ValidarSumaPorcentajesSlots;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.PostReconstruirFilasReparto;
begin
  TThread.Queue(nil,
    TThreadProcedure(
      procedure
      begin
        if Assigned(Self) and not (csDestroying in ComponentState) then
        begin
          LockWindowUpdate(Self.Handle);
          try
            ReconstruirFilasReparto;
            ActualizarArbolProduccion;
            ValidarSumaPorcentajesSlots;
          finally
            LockWindowUpdate(0);
          end;
        end;
      end));
end;

procedure TfrmPlanificacionMasasProduccion.SincronizarValoresFilas;
var
  i: Integer;
  LRow: TMasaRepartoRow;
begin
  FUpdatingControls := True;
  try
    for i := 0 to FRepartoRows.Count - 1 do
    begin
      LRow := FRepartoRows[i];
      if (LRow.cbbPorc <> nil) and (LRow.SaborItem <> nil) then
        LRow.cbbPorc.Text := FormatFloat('0.#', LRow.SaborItem.Porcentaje) + '%';
      if (LRow.edtUnidades <> nil) and (LRow.SaborItem <> nil) then
        LRow.edtUnidades.Text := IntToStr(LRow.SaborItem.UnidadesXL);
      if (LRow.edtLote <> nil) and (LRow.SaborItem <> nil) then
        LRow.edtLote.Text := LRow.SaborItem.LoteCodigo;
      if (LRow.btnEliminar <> nil) and (LRow.MasaItem <> nil) then
        LRow.btnEliminar.Visible := (LRow.MasaItem.Sabores.Count > 1);
    end;
  finally
    FUpdatingControls := False;
  end;
  ActualizarTotalesAcumulados;
  ActualizarArbolProduccion;
  ValidarSumaPorcentajesSlots;
end;

procedure TfrmPlanificacionMasasProduccion.ActualizarTotalesAcumulados;
var
  i, LArtId, LRunning: Integer;
  LRow: TMasaRepartoRow;
  LDict: TDictionary<Integer, Integer>;
begin
  LDict := TDictionary<Integer, Integer>.Create;
  try
    for i := 0 to FRepartoRows.Count - 1 do
    begin
      LRow := FRepartoRows[i];
      if (LRow <> nil) and (LRow.SaborItem <> nil) and (LRow.SaborItem.ArticuloId > 0) then
      begin
        LArtId := LRow.SaborItem.ArticuloId;
        LRunning := 0;
        LDict.TryGetValue(LArtId, LRunning);
        LRunning := LRunning + LRow.SaborItem.UnidadesXL;
        LDict.AddOrSetValue(LArtId, LRunning);

        if LRow.edtAcumulado <> nil then
          LRow.edtAcumulado.Text := IntToStr(LRunning);
      end
      else
      begin
        if (LRow <> nil) and (LRow.edtAcumulado <> nil) then
          LRow.edtAcumulado.Text := '';
      end;
    end;
  finally
    LDict.Free;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.AgregarLineaRestanteMasa(
  AMasa: TMasaBaseItem; APrevSabor: TSaborRepartoItem; ARestantePorc: Double);
var
  LNuevoSabor: TSaborRepartoItem;
begin
  LNuevoSabor := TSaborRepartoItem.Create;
  LNuevoSabor.ArticuloId := 0;
  LNuevoSabor.ArticuloDesc := '';
  LNuevoSabor.RecetaId := 0;
  LNuevoSabor.RecetaDesc := '';
  LNuevoSabor.Porcentaje := ARestantePorc;
  LNuevoSabor.UnidadesBase := 0;
  LNuevoSabor.UnidadesCalculadas := 0;
  LNuevoSabor.UnidadesXL := 0;
  LNuevoSabor.PrefijoLote := 'P';
  LNuevoSabor.LoteCodigo := '';

  AMasa.Sabores.Add(LNuevoSabor);
end;

function TfrmPlanificacionMasasProduccion.BuscarSiguienteFormato(ACurrentArtId, ARecetaId: Integer): TProductoFinalItem;
var
  i, LCurrentIdx: Integer;
  LItem: TProductoFinalItem;
begin
  Result := nil;
  LCurrentIdx := -1;

  for i := 0 to FProductosFinales.Count - 1 do
  begin
    if (ACurrentArtId > 0) and (FProductosFinales[i].ArticuloId = ACurrentArtId) then
    begin
      LCurrentIdx := i;
      Break;
    end
    else if (LCurrentIdx < 0) and (ARecetaId > 0) and (FProductosFinales[i].RecetaId = ARecetaId) then
      LCurrentIdx := i;
  end;

  // 1. Buscar otro formato de la misma receta (ej. de XL a L, o de L a MINI)
  if (ARecetaId > 0) and (LCurrentIdx >= 0) then
  begin
    for i := LCurrentIdx + 1 to FProductosFinales.Count - 1 do
    begin
      LItem := FProductosFinales[i];
      if (LItem.RecetaId = ARecetaId) and (LItem.ArticuloId <> ACurrentArtId) then
      begin
        Result := LItem;
        Exit;
      end;
    end;
    for i := 0 to LCurrentIdx - 1 do
    begin
      LItem := FProductosFinales[i];
      if (LItem.RecetaId = ARecetaId) and (LItem.ArticuloId <> ACurrentArtId) then
      begin
        Result := LItem;
        Exit;
      end;
    end;
  end;

  // 2. Si no hay más formatos de la misma receta, tomar el siguiente producto de la lista
  if (LCurrentIdx >= 0) and (LCurrentIdx + 1 < FProductosFinales.Count) then
  begin
    Result := FProductosFinales[LCurrentIdx + 1];
    Exit;
  end;

  // 3. Fallback al primer producto disponible
  if FProductosFinales.Count > 0 then
    Result := FProductosFinales[0];
end;

procedure TfrmPlanificacionMasasProduccion.btnTpl100Click(Sender: TObject);
var
  i: Integer;
  LMasa: TMasaBaseItem;
begin
  LockWindowUpdate(Self.Handle);
  try
    for i := 0 to FPlan.Masas.Count - 1 do
    begin
      LMasa := FPlan.Masas[i];
      while LMasa.Sabores.Count > 1 do
        LMasa.Sabores.Delete(LMasa.Sabores.Count - 1);
      if LMasa.Sabores.Count = 1 then
      begin
        LMasa.Sabores[0].Porcentaje := 100.0;
        LMasa.Sabores[0].UnidadesCalculadas := Round(LMasa.Sabores[0].UnidadesBase * LMasa.Multiplicador);
        LMasa.Sabores[0].UnidadesXL := LMasa.Sabores[0].UnidadesCalculadas;
      end;
    end;
    ReconstruirFilasReparto;
    ActualizarArbolProduccion;
    ValidarSumaPorcentajesSlots;
  finally
    LockWindowUpdate(0);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnTpl5050Click(Sender: TObject);
var
  i: Integer;
  LMasa: TMasaBaseItem;
  LSabor1: TSaborRepartoItem;
begin
  LockWindowUpdate(Self.Handle);
  try
    for i := 0 to FPlan.Masas.Count - 1 do
    begin
      LMasa := FPlan.Masas[i];
      while LMasa.Sabores.Count > 1 do
        LMasa.Sabores.Delete(LMasa.Sabores.Count - 1);
      if LMasa.Sabores.Count = 1 then
      begin
        LSabor1 := LMasa.Sabores[0];
        LSabor1.Porcentaje := 50.0;
        LSabor1.UnidadesCalculadas := Round(LSabor1.UnidadesBase * 0.50 * LMasa.Multiplicador);
        LSabor1.UnidadesXL := LSabor1.UnidadesCalculadas;
        AgregarLineaRestanteMasa(LMasa, LSabor1, 50.0);
      end;
    end;
    ReconstruirFilasReparto;
    ActualizarArbolProduccion;
    ValidarSumaPorcentajesSlots;
  finally
    LockWindowUpdate(0);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnTpl7525Click(Sender: TObject);
var
  i: Integer;
  LMasa: TMasaBaseItem;
  LSabor1: TSaborRepartoItem;
begin
  LockWindowUpdate(Self.Handle);
  try
    for i := 0 to FPlan.Masas.Count - 1 do
    begin
      LMasa := FPlan.Masas[i];
      while LMasa.Sabores.Count > 1 do
        LMasa.Sabores.Delete(LMasa.Sabores.Count - 1);
      if LMasa.Sabores.Count = 1 then
      begin
        LSabor1 := LMasa.Sabores[0];
        LSabor1.Porcentaje := 75.0;
        LSabor1.UnidadesCalculadas := Round(LSabor1.UnidadesBase * 0.75 * LMasa.Multiplicador);
        LSabor1.UnidadesXL := LSabor1.UnidadesCalculadas;
        AgregarLineaRestanteMasa(LMasa, LSabor1, 25.0);
      end;
    end;
    ReconstruirFilasReparto;
    ActualizarArbolProduccion;
    ValidarSumaPorcentajesSlots;
  finally
    LockWindowUpdate(0);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnTpl4x25Click(Sender: TObject);
var
  i, k: Integer;
  LMasa: TMasaBaseItem;
  LSabor: TSaborRepartoItem;
begin
  LockWindowUpdate(Self.Handle);
  try
    for i := 0 to FPlan.Masas.Count - 1 do
    begin
      LMasa := FPlan.Masas[i];
      while LMasa.Sabores.Count > 1 do
        LMasa.Sabores.Delete(LMasa.Sabores.Count - 1);
      if LMasa.Sabores.Count = 1 then
      begin
        LSabor := LMasa.Sabores[0];
        LSabor.Porcentaje := 25.0;
        LSabor.UnidadesCalculadas := Round(LSabor.UnidadesBase * 0.25 * LMasa.Multiplicador);
        LSabor.UnidadesXL := LSabor.UnidadesCalculadas;
        for k := 1 to 3 do
          AgregarLineaRestanteMasa(LMasa, LMasa.Sabores[LMasa.Sabores.Count - 1], 25.0);
      end;
    end;
    ReconstruirFilasReparto;
    ActualizarArbolProduccion;
    ValidarSumaPorcentajesSlots;
  finally
    LockWindowUpdate(0);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.ValidarSumaPorcentajesSlots;
var
  i: Integer;
  LMasa: TMasaBaseItem;
  LTotalesOk: Boolean;
  LMsg: string;
begin
  if (FPlan = nil) or (FPlan.Masas.Count = 0) then
  begin
    lblSumaPorc.Caption := '';
    Exit;
  end;

  LTotalesOk := True;
  LMsg := '';

  for i := 0 to FPlan.Masas.Count - 1 do
  begin
    LMasa := FPlan.Masas[i];
    if not SameValue(LMasa.TotalPorcentaje, 100.0, 0.05) then
    begin
      LTotalesOk := False;
      if LMsg <> '' then LMsg := LMsg + ', ';
      LMsg := LMsg + Format('%s: %.0f%%', [LMasa.NombreMasa, LMasa.TotalPorcentaje]);
    end;
  end;

  if LTotalesOk then
  begin
    lblSumaPorc.Font.Color := clGreen;
    lblSumaPorc.Caption := Format('Total Masas: %d | Todas las masas al 100%% (Correcto)', [FPlan.Masas.Count]);
  end
  else
  begin
    lblSumaPorc.Font.Color := clRed;
    lblSumaPorc.Caption := Format('Reparto incompleto en: %s (Debe sumar 100%% c/u)', [LMsg]);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnGuardarMasaRepartoClick(Sender: TObject);
begin
  ActualizarArbolProduccion;
  ValidarSumaPorcentajesSlots;
end;

procedure TfrmPlanificacionMasasProduccion.AsegurarColumnaArticuloReparto;
var
  LQryCheck: TFDQuery;
begin
  LQryCheck := TFDQuery.Create(nil);
  try
    LQryCheck.Connection := dmgMain.dbConn;
    LQryCheck.SQL.Text :=
      'SELECT COUNT(*) AS cnt FROM INFORMATION_SCHEMA.COLUMNS ' +
      'WHERE TABLE_SCHEMA = DATABASE() ' +
      '  AND TABLE_NAME = ''ob_elaboraciones_reparto'' ' +
      '  AND COLUMN_NAME = ''id_articulo''';
    LQryCheck.Open;
    if LQryCheck.FieldByName('cnt').AsInteger = 0 then
    begin
      LQryCheck.Close;
      LQryCheck.SQL.Text :=
        'ALTER TABLE ob_elaboraciones_reparto ' +
        'ADD COLUMN id_articulo INT(11) DEFAULT NULL AFTER elaboracion_id, ' +
        'ADD KEY idx_ob_elab_reparto_articulo (id_articulo)';
      LQryCheck.ExecSQL;
    end;
  finally
    LQryCheck.Free;
  end;
end;

function TfrmPlanificacionMasasProduccion.FormatearCodigoLoteSabor(const APrefijo: string;
  AFecha: TDateTime; ANumeroMasa: Integer; const ALoteBase: string; ASubIndex: Integer): string;
var
  LPrefChar: Char;
  LDayStr, LMesStr, LUltimoDigitoAno, LMasaStr: string;
  LYear, LMonth, LDay: Word;
  LMasaNum: Integer;
begin
  // 1. Primer dígito: el prefijo registrado en la receta (por defecto 'P')
  if Trim(APrefijo) <> '' then
    LPrefChar := UpperCase(Trim(APrefijo))[1]
  else
    LPrefChar := 'P';

  // 2. Dos siguientes: día del mes (2 dígitos)
  DecodeDate(AFecha, LYear, LMonth, LDay);
  LDayStr := Format('%.2d', [LDay]);

  // 3. Dos dígitos del mes: sustituyendo '0' por 'X' (1 al 9) y '1' por 'A' (10 al 12)
  if (LMonth >= 1) and (LMonth <= 9) then
    LMesStr := 'X' + IntToStr(LMonth)
  else if LMonth = 10 then
    LMesStr := 'A0'
  else if LMonth = 11 then
    LMesStr := 'A1'
  else if LMonth = 12 then
    LMesStr := 'A2'
  else
    LMesStr := 'X1';

  // 4. Tres últimos dígitos:
  // - El primer dígito es el último de la fecha (último dígito del año, ej. 2026 -> 6)
  // - Los 2 últimos se corresponden con el número de masa (formateado a 2 dígitos)
  LUltimoDigitoAno := IntToStr(LYear mod 10);

  if ANumeroMasa <= 0 then
    LMasaNum := 1
  else
    LMasaNum := ANumeroMasa;
  LMasaStr := Format('%.2d', [LMasaNum]);

  // Estructura: [Prefijo:1][Día:2][Mes:2][Año:1][Masa:2] = 8 caracteres exactos
  Result := Format('%s%s%s%s%s', [LPrefChar, LDayStr, LMesStr, LUltimoDigitoAno, LMasaStr]);
  if Length(Result) > 8 then
    Result := Copy(Result, 1, 8);
end;

procedure TfrmPlanificacionMasasProduccion.ActualizarArbolProduccion;
var
  LRootNode, LNodeMB, LNodeMasa: TTreeNode;
  LMasa: TMasaBaseItem;
  LSabor: TSaborRepartoItem;
  i, LTotalUds, k: Integer;
  LAlmStr, LObrStr: string;
  LSelectedData: Pointer;
begin
  SendMessage(tvProduccion.Handle, WM_SETREDRAW, 0, 0);
  tvProduccion.Items.BeginUpdate;
  try
    LSelectedData := nil;
    if tvProduccion.Selected <> nil then
      LSelectedData := tvProduccion.Selected.Data;

    tvProduccion.Items.Clear;
    if FPlan = nil then Exit;

    LAlmStr := cbbAlmacen.Text;
    if LAlmStr = '' then LAlmStr := 'Almacén Central';
    LObrStr := cbbObrador.Text;
    if LObrStr = '' then LObrStr := 'Obrador Central';

    LRootNode := tvProduccion.Items.Add(nil, Format('📅 Plan de Producción: %s | %s',
      [FormatDateTime('dd/MM/yyyy', dtpFechaLote.Date), LObrStr]));

    LTotalUds := 0;

    if FPlan.EsMasaBase then
    begin
      // 1. Masa Madre
      if FPlan.RequiereMasaMadre then
      begin
        if FPlan.MasasBaseManana > 0 then
          tvProduccion.Items.AddChildObject(LRootNode,
            Format('🌾 MASA MADRE (Receta 3) (Lote: %s) - Total a Elaborar: %.2f kg (Hoy: %.2f kg | Reserva Mañana [%d masas x 2,0 kg]: %.2f kg)',
              [FPlan.LoteMasaMadreCodigo, FPlan.MasaMadreTotalKg, FPlan.MasaMadreHoyKg, FPlan.MasasBaseManana, FPlan.MasaMadreExtraKg]), FPlan)
        else
          tvProduccion.Items.AddChildObject(LRootNode,
            Format('🌾 MASA MADRE (Receta 3) (Lote: %s) - Total a Elaborar: %.2f kg (Hoy: %.2f kg | Extra: %.2f kg)',
              [FPlan.LoteMasaMadreCodigo, FPlan.MasaMadreTotalKg, FPlan.MasaMadreHoyKg, FPlan.MasaMadreExtraKg]), FPlan);
      end;

      // 2. 1er Empaste
      if FPlan.Requiere1erEmpaste then
      begin
        var LTotalKg1E: Double := 0.0;
        for i := 0 to FPlan.Masas.Count - 1 do
          LTotalKg1E := LTotalKg1E + (FPlan.Masas[i].Multiplicador * 93.0);

        var LNode1E := tvProduccion.Items.AddChild(LRootNode,
          Format('🥣 1ER EMPASTE (Receta 22) - %d masas individuales (%.1f kg)',
            [FPlan.Masas.Count, LTotalKg1E]));
        for i := 0 to FPlan.Masas.Count - 1 do
        begin
          LMasa := FPlan.Masas[i];
          var LPorcMasa := Round(LMasa.Multiplicador * 100);
          var LPorcText := IfThen(LPorcMasa = 100, '1 masa', Format('Porción %d%%', [LPorcMasa]));
          tvProduccion.Items.AddChild(LNode1E,
            Format('🔸 1er Empaste %s (Lote: %s) - %s (%.1f kg)',
              [LMasa.NombreMasa, LMasa.Lote1erEmpasteCodigo, LPorcText, LMasa.Multiplicador * 93.0]));
        end;
      end;

      // 3. 2º Empaste / Masa Base
      LNodeMB := tvProduccion.Items.AddChild(LRootNode,
        Format('🍞 2º EMPASTE - MASA BASE (Receta 5) - %d masas planificadas',
          [FPlan.Masas.Count]));

      for i := 0 to FPlan.Masas.Count - 1 do
      begin
        LMasa := FPlan.Masas[i];
        var LPorcMasa2 := Round(LMasa.Multiplicador * 100);
        var LTagPorc := IfThen(LPorcMasa2 = 100, '', Format(' [Porción %d%%]', [LPorcMasa2]));
        var LTagEstado := IfThen(LMasa.EsExistente, '', ' [NUEVA]');
        LNodeMasa := tvProduccion.Items.AddChildObject(LNodeMB,
          Format('🔹 %s%s%s (Lote: %s) - %s',
            [LMasa.NombreMasa, LTagPorc, LTagEstado, LMasa.LoteCodigo,
             IfThen(SameValue(LMasa.TotalPorcentaje, 100.0, 0.01), '100% Repartido',
                    Format('%.0f%% Pendiente', [LMasa.TotalPorcentaje]))]), LMasa);

        for LSabor in LMasa.Sabores do
        begin
          var LDescSabor := Trim(LSabor.ArticuloDesc);
          if LDescSabor = '' then
            LDescSabor := '⚠️ [Sin artículo seleccionado]';
          var LLoteStr := LSabor.LoteCodigo;
          if LLoteStr = '' then
            LLoteStr := 'Pendiente';
          tvProduccion.Items.AddChildObject(LNodeMasa,
            Format('✨ [%.0f%%] %s | Lote: %s | Est.: %d uds',
              [LSabor.Porcentaje, LDescSabor, LLoteStr, LSabor.UnidadesXL]), LSabor);
          Inc(LTotalUds, LSabor.UnidadesXL);
        end;
      end;
    end
    else if FPlan.EsMasaMadre then
    begin
      if FPlan.MasasBaseManana > 0 then
        tvProduccion.Items.AddChildObject(LRootNode,
          Format('🌾 MASA MADRE (Lote: %s) - %d masas hoy (%.1f kg) | Reserva mañana [%d masas x 2,0 kg]: %.2f kg | Total a Elaborar: %.2f kg',
            [FPlan.LoteMasaMadreCodigo, FPlan.CantidadMasasPrincipal, FPlan.MasaMadreHoyKg, FPlan.MasasBaseManana,
             FPlan.MasaMadreExtraKg, FPlan.MasaMadreTotalKg]), FPlan)
      else
        tvProduccion.Items.AddChildObject(LRootNode,
          Format('🌾 MASA MADRE (Lote: %s) - %d masas hoy (%.1f kg) | Extra: %.2f kg | Total a Elaborar: %.2f kg',
            [FPlan.LoteMasaMadreCodigo, FPlan.CantidadMasasPrincipal, FPlan.MasaMadreHoyKg, FPlan.MasaMadreExtraKg, FPlan.MasaMadreTotalKg]), FPlan);
    end
    else
    begin
      tvProduccion.Items.AddChild(LRootNode,
        Format('📦 %s - %d masas / unidades planificadas',
          [FPlan.RecetaPrincipalDesc, FPlan.CantidadMasasPrincipal]));
      LTotalUds := FPlan.CantidadMasasPrincipal;
    end;

    tvProduccion.FullExpand;

    if LSelectedData <> nil then
    begin
      for k := 0 to tvProduccion.Items.Count - 1 do
      begin
        if tvProduccion.Items[k].Data = LSelectedData then
        begin
          tvProduccion.Selected := tvProduccion.Items[k];
          Break;
        end;
      end;
    end;

    lblKpiTreeMasas.Caption := Format('Masas Base: %d', [FPlan.Masas.Count]);
    lblKpiTreeMM.Caption := Format('Masa Madre: %.1f kg', [FPlan.MasaMadreTotalKg]);
    lblKpiTreeUds.Caption := Format('Panettones Est.: %d uds', [LTotalUds]);

    lblKpiMasasVal.Caption := IntToStr(FPlan.Masas.Count);
    lblKpiUnidadesVal.Caption := IntToStr(LTotalUds);
  finally
    tvProduccion.Items.EndUpdate;
    SendMessage(tvProduccion.Handle, WM_SETREDRAW, 1, 0);
    RedrawWindow(tvProduccion.Handle, nil, 0, RDW_INVALIDATE or RDW_ALLCHILDREN or RDW_UPDATENOW or RDW_ERASE);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.ModificarLoteNodoSeleccionado;
var
  LNode: TTreeNode;
  LObj: TObject;
  LSabor: TSaborRepartoItem;
  LMasa: TMasaBaseItem;
  LNuevoLote, LPrompt: string;
begin
  LNode := tvProduccion.Selected;
  if (LNode = nil) or (LNode.Data = nil) then
  begin
    MessageDlg('Seleccione en el árbol una masa o un producto/sabor para modificar su código de lote.',
      mtInformation, [mbOK], 0);
    Exit;
  end;

  LObj := TObject(LNode.Data);
  if LObj is TSaborRepartoItem then
  begin
    LSabor := TSaborRepartoItem(LObj);
    LNuevoLote := LSabor.LoteCodigo;
    LPrompt := Format('Modificar código de lote para:'#13#10'• Producto: %s'#13#10'• Reparto: %.0f%% (Est.: %d uds)',
      [LSabor.ArticuloDesc, LSabor.Porcentaje, LSabor.UnidadesXL]);
    if InputQuery('Modificar Código de Lote', LPrompt, LNuevoLote) then
    begin
      LNuevoLote := Trim(LNuevoLote);
      if LNuevoLote <> '' then
      begin
        LSabor.LoteCodigo := LNuevoLote;
        ActualizarArbolProduccion;
        ReconstruirFilasReparto;
      end;
    end;
  end
  else if LObj is TMasaBaseItem then
  begin
    LMasa := TMasaBaseItem(LObj);
    LNuevoLote := LMasa.LoteCodigo;
    LPrompt := Format('Modificar código de lote para la masa base:'#13#10'• %s', [LMasa.NombreMasa]);
    if InputQuery('Modificar Lote de Masa Base', LPrompt, LNuevoLote) then
    begin
      LNuevoLote := Trim(LNuevoLote);
      if LNuevoLote <> '' then
      begin
        LMasa.LoteCodigo := LNuevoLote;
        for var sIdx := 0 to LMasa.Sabores.Count - 1 do
        begin
          var LSubSabor := LMasa.Sabores[sIdx];
          LSubSabor.LoteCodigo := FormatearCodigoLoteSabor(LSubSabor.PrefijoLote, dtpFechaLote.Date, LMasa.NumeroMasa, LMasa.LoteCodigo, sIdx);
        end;
        ReconstruirFilasReparto;
        ActualizarArbolProduccion;
      end;
    end;
  end
  else if LObj is TPlanFabricacion then
  begin
    LNuevoLote := FPlan.LoteMasaMadreCodigo;
    LPrompt := 'Modificar código de lote para la Masa Madre:';
    if InputQuery('Modificar Lote de Masa Madre', LPrompt, LNuevoLote) then
    begin
      LNuevoLote := Trim(LNuevoLote);
      if LNuevoLote <> '' then
      begin
        FPlan.LoteMasaMadreCodigo := LNuevoLote;
        ActualizarArbolProduccion;
      end;
    end;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnModificarLoteClick(Sender: TObject);
begin
  ModificarLoteNodoSeleccionado;
end;

procedure TfrmPlanificacionMasasProduccion.tvProduccionDblClick(Sender: TObject);
begin
  if (tvProduccion.Selected <> nil) and (tvProduccion.Selected.Data <> nil) then
    ModificarLoteNodoSeleccionado;
end;

procedure TfrmPlanificacionMasasProduccion.tvProduccionKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if (Key = VK_F2) or (Key = VK_RETURN) then
  begin
    Key := 0;
    ModificarLoteNodoSeleccionado;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.RegistrarMateriasPrimasTeoricasElaboracion(
  AElabId, ARecetaId: Integer; AMultiplicador: Double; AUserId: Integer; AIncluirMasaMadreKg: Double = 0.0);
var
  LQryIng: TFDQuery;
  LCant: Double;
  LUnidad: string;
  LSB: TStringBuilder;
  LFirst: Boolean;
  LMpId: Integer;
begin
  if (AElabId <= 0) or (ARecetaId <= 0) then Exit;
  if AMultiplicador <= 0.0001 then AMultiplicador := 1.0;

  LQryIng := TFDQuery.Create(nil);
  LSB := TStringBuilder.Create;
  try
    LQryIng.Connection := dmgMain.dbConn;
    LQryIng.SQL.Text :=
      'SELECT mp.id AS mp_id, mp.descripcion AS mp_nom, pi.unidad, SUM(pi.cantidad_base) AS cant_base ' +
      'FROM ob_recetas_procesos rp ' +
      'JOIN ob_procesos_ingredientes pi ON pi.proceso_id = rp.id ' +
      'JOIN ge_materias_primas mp ON mp.id = pi.id_materia_prima ' +
      'WHERE rp.receta_id = :receta AND pi.tipo_origen = ''MP'' ' +
      'GROUP BY mp.id, mp.descripcion, pi.unidad ' +
      'ORDER BY mp.descripcion ASC';
    LQryIng.ParamByName('receta').AsInteger := ARecetaId;
    LQryIng.Open;

    if not LQryIng.IsEmpty or (AIncluirMasaMadreKg > 0.001) then
    begin
      LSB.Append('INSERT INTO ob_lotes_consumidos ' +
        '(elaboracion_id, id_materia_prima, cantidad, cantidad_teorica, cantidad_real, unidad, id_user_creator) VALUES ');
      LFirst := True;

      while not LQryIng.Eof do
      begin
        LMpId := LQryIng.FieldByName('mp_id').AsInteger;
        LCant := LQryIng.FieldByName('cant_base').AsFloat * AMultiplicador;
        LUnidad := LowerCase(Trim(LQryIng.FieldByName('unidad').AsString));
        if (LUnidad = 'g') and (LCant >= 1000.0) then
        begin
          LCant := LCant / 1000.0;
          LUnidad := 'kg';
        end;

        if not LFirst then LSB.Append(', ');
        LFirst := False;

        LSB.AppendFormat('(%d, %d, %s, %s, 0.0, %s, %d)', [
          AElabId,
          LMpId,
          FloatToStr(LCant, TFormatSettings.Invariant),
          FloatToStr(LCant, TFormatSettings.Invariant),
          QuotedStr(LUnidad),
          AUserId
        ]);

        LQryIng.Next;
      end;

      if AIncluirMasaMadreKg > 0.001 then
      begin
        var LCantMM := AIncluirMasaMadreKg * AMultiplicador;
        if not LFirst then LSB.Append(', ');
        LFirst := False;
        LSB.AppendFormat('(%d, 131, %s, %s, 0.0, ''kg'', %d)', [
          AElabId,
          FloatToStr(LCantMM, TFormatSettings.Invariant),
          FloatToStr(LCantMM, TFormatSettings.Invariant),
          AUserId
        ]);
      end;

      if not LFirst then
      begin
        qExec.Close;
        qExec.SQL.Text := LSB.ToString;
        qExec.ExecSQL;
      end;
    end;
  finally
    LSB.Free;
    LQryIng.Free;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.RegistrarMateriasPrimasInclusionesElaboracion(
  AElabId, ARecetaId: Integer; AMultiplicador: Double;
  AIdLoteMB: Integer; const ALoteMBCodigo: string; AUserId: Integer);
var
  LQryIng: TFDQuery;
  LCant: Double;
  LUnidad: string;
  LMpId: Integer;
  LMasaBaseIncluida: Boolean;
  LSB: TStringBuilder;
  LFirst: Boolean;
begin
  if (AElabId <= 0) or (ARecetaId <= 0) then Exit;
  if AMultiplicador <= 0.0001 then AMultiplicador := 1.0;

  LMasaBaseIncluida := False;
  LQryIng := TFDQuery.Create(nil);
  LSB := TStringBuilder.Create;
  try
    LQryIng.Connection := dmgMain.dbConn;
    LQryIng.SQL.Text :=
      'SELECT pi.id_materia_prima AS mp_id, ' +
      '       COALESCE(mp.descripcion, a.descripcion, sr.descripcion, CONCAT(''Materia #'', pi.id_materia_prima)) AS mp_nom, ' +
      '       pi.unidad, SUM(pi.cantidad_base) AS cant_base ' +
      'FROM ob_recetas_procesos rp ' +
      'JOIN ob_procesos_ingredientes pi ON pi.proceso_id = rp.id ' +
      'LEFT JOIN ge_materias_primas mp ON pi.tipo_origen = ''MP'' AND mp.id = pi.id_materia_prima ' +
      'LEFT JOIN ge_articulos a ON pi.tipo_origen = ''ART'' AND a.id = pi.id_materia_prima ' +
      'LEFT JOIN ob_recetas sr ON sr.id = pi.id_subreceta ' +
      'WHERE rp.receta_id = :receta ' +
      'GROUP BY pi.tipo_origen, pi.id_materia_prima, pi.id_subreceta, mp.descripcion, a.descripcion, sr.descripcion, pi.unidad ' +
      'ORDER BY (pi.id_materia_prima = 3161) DESC, mp_nom ASC';
    LQryIng.ParamByName('receta').AsInteger := ARecetaId;
    LQryIng.Open;

    if not LQryIng.IsEmpty then
    begin
      LSB.Append('INSERT INTO ob_lotes_consumidos ' +
        '(elaboracion_id, id_materia_prima, lote_consumido_id, lote_real, cantidad, cantidad_teorica, cantidad_real, unidad, id_user_creator) VALUES ');
      LFirst := True;

      while not LQryIng.Eof do
      begin
        LMpId := LQryIng.FieldByName('mp_id').AsInteger;
        LCant := LQryIng.FieldByName('cant_base').AsFloat * AMultiplicador;
        LUnidad := LowerCase(Trim(LQryIng.FieldByName('unidad').AsString));

        if (LUnidad = 'g') and (LCant >= 1000.0) then
        begin
          LCant := LCant / 1000.0;
          LUnidad := 'kg';
        end;

        if not LFirst then LSB.Append(', ');
        LFirst := False;

        if LMpId = 3161 then
        begin
          LMasaBaseIncluida := True;
          var LLoteStr: string;
          if AIdLoteMB > 0 then
            LLoteStr := IntToStr(AIdLoteMB)
          else
            LLoteStr := 'NULL';

          LSB.AppendFormat('(%d, %d, %s, %s, %s, %s, %s, %s, %d)', [
            AElabId,
            LMpId,
            LLoteStr,
            QuotedStr(ALoteMBCodigo),
            FloatToStr(LCant, TFormatSettings.Invariant),
            FloatToStr(LCant, TFormatSettings.Invariant),
            FloatToStr(LCant, TFormatSettings.Invariant),
            QuotedStr(LUnidad),
            AUserId
          ]);
        end
        else
        begin
          LSB.AppendFormat('(%d, %d, NULL, NULL, %s, %s, 0.0, %s, %d)', [
            AElabId,
            LMpId,
            FloatToStr(LCant, TFormatSettings.Invariant),
            FloatToStr(LCant, TFormatSettings.Invariant),
            QuotedStr(LUnidad),
            AUserId
          ]);
        end;

        LQryIng.Next;
      end;

      if not LFirst then
      begin
        qExec.Close;
        qExec.SQL.Text := LSB.ToString;
        qExec.ExecSQL;
      end;
    end;

    // Si por alguna razón la receta no tuviera explícitamente el ingrediente 3161 (Masa Base),
    // vincular igualmente el consumo de masa base para garantizar la trazabilidad de origen
    if (not LMasaBaseIncluida) and (AIdLoteMB > 0) then
    begin
      var LCantMB := 171.9568 * AMultiplicador;
      qExec.Close;
      qExec.SQL.Text :=
        'INSERT INTO ob_lotes_consumidos ' +
        '  (elaboracion_id, id_materia_prima, lote_consumido_id, lote_real, cantidad, cantidad_teorica, cantidad_real, unidad, id_user_creator) ' +
        'VALUES ' +
        '  (:elab, 3161, :lote_id, :lote_real, :cant, :cant_teorica, :cant_real, ''kg'', :user)';
      qExec.ParamByName('elab').AsInteger := AElabId;
      qExec.ParamByName('lote_id').AsInteger := AIdLoteMB;
      qExec.ParamByName('lote_real').AsString := ALoteMBCodigo;
      qExec.ParamByName('cant').AsFloat := LCantMB;
      qExec.ParamByName('cant_teorica').AsFloat := LCantMB;
      qExec.ParamByName('cant_real').AsFloat := LCantMB;
      qExec.ParamByName('user').AsInteger := AUserId;
      qExec.ExecSQL;
    end;
  finally
    LSB.Free;
    LQryIng.Free;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnGuardarPlanClick(Sender: TObject);
var
  i, j, LObradorId, LAlmId, LUserId: Integer;
  LMasa: TMasaBaseItem;
  LSabor: TSaborRepartoItem;
  LIdLoteMM, LIdLote1E, LIdLoteMB, LIdLoteSabor: Integer;
  LCodMM, LCod1E, LCodMB, LCodSabor: Integer;
  LCodigoAntMM, LCodigoAnt1E, LCodigoAntMB, LCodigoAntSabor: string;
  LElab1EId, LElabMBId, LElabSaborId, LRecetaSaborId: Integer;
  LObs: string;
begin
  if FPlan.EsMasaBase then
  begin
    for i := 0 to FPlan.Masas.Count - 1 do
    begin
      LMasa := FPlan.Masas[i];
      if not SameValue(LMasa.TotalPorcentaje, 100.0, 0.01) then
      begin
        MessageDlg(Format('Atención: La %s tiene un reparto de %.0f%% (debe sumar exactamente 100%%).' + sLineBreak +
                          'Por favor, ajuste los porcentajes antes de guardar.', [LMasa.NombreMasa, LMasa.TotalPorcentaje]),
                   mtWarning, [mbOK], 0);
        Exit;
      end;
      for j := 0 to LMasa.Sabores.Count - 1 do
      begin
        LSabor := LMasa.Sabores[j];
        if (LSabor.ArticuloId <= 0) and (LSabor.RecetaId <= 0) then
        begin
          MessageDlg(Format('Atención: En la %s (línea %d) no se ha seleccionado ningún artículo o formato.' + sLineBreak +
                            'Por favor, seleccione el artículo a elaborar en cada masa antes de generar la producción.',
                            [LMasa.NombreMasa, j + 1]), mtWarning, [mbOK], 0);
          Exit;
        end;
      end;
    end;
  end;

  // Verificar si hay masas existentes y/o nuevas
  var LHasExisting: Boolean := False;
  var LHasNew: Boolean := False;
  var LNumNuevas: Integer := 0;
  for i := 0 to FPlan.Masas.Count - 1 do
  begin
    if FPlan.Masas[i].EsExistente then
      LHasExisting := True
    else
    begin
      LHasNew := True;
      Inc(LNumNuevas);
    end;
  end;

  if (Sender <> btnDuplicarPlan) and (Sender <> btnDuplicarPlanFooter) then
  begin
    if LHasExisting and LHasNew then
    begin
      if MessageDlg(Format('¿Confirma añadir %d nueva(s) masa(s) a las órdenes de fabricación ya existentes para la fecha %s?' + sLineBreak +
                           'Las órdenes y masas ya creadas se mantendrán intactas.',
                           [LNumNuevas, FormatDateTime('dd/MM/yyyy', dtpFechaLote.Date)]),
                    mtConfirmation, [mbYes, mbNo], 0) <> mrYes then Exit;
    end
    else
    begin
      if MessageDlg(Format('¿Confirma la generación de órdenes de fabricación, lotes correlativos y ' +
                           'stock envasado con estado PENDIENTE para la fecha %s?',
                           [FormatDateTime('dd/MM/yyyy', dtpFechaLote.Date)]),
                    mtConfirmation, [mbYes, mbNo], 0) <> mrYes then Exit;
    end;
  end;

  LObradorId := GetSelectedObradorId;
  LAlmId := GetSelectedAlmacenId;
  LUserId := StrToIntDef(dmgMain.CurrentUserId, 1);

  // Si no se están añadiendo masas a un plan existente, comprobar si existen órdenes ya iniciadas que impidan el reemplazo
  if not (LHasExisting and LHasNew) then
  begin
    qExec.Close;
    qExec.SQL.Text :=
      'SELECT COUNT(*) AS total_iniciadas ' +
      'FROM ob_elaboraciones ' +
      'WHERE fecha = :fecha AND (hora_inicio IS NOT NULL OR hora_fin IS NOT NULL)';
    qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
    qExec.Open;
    if qExec.FieldByName('total_iniciadas').AsInteger > 0 then
    begin
      MessageDlg('No se puede modificar la planificación para esta fecha porque ya existen órdenes de fabricación ' +
                 'en proceso ("EN AMASADO") o terminadas ("FINALIZADAS").' + sLineBreak +
                 'Solo se permite actualizar órdenes en estado "PENDIENTE".' + sLineBreak +
                 'Si desea añadir más producción, utilice la opción "+ Añadir Masas".', mtError, [mbOK], 0);
      Exit;
    end;
  end;

  AsegurarColumnaArticuloReparto;

  dmgMain.dbConn.StartTransaction;
  try
    // Si no estamos añadiendo masas a un plan existente, limpiar elaboraciones pendientes previas para reemplazarlas
    if not (LHasExisting and LHasNew) then
    begin
      qExec.Close;
      qExec.SQL.Text :=
        'DELETE se FROM ge_stock_envasado se ' +
        'JOIN ob_elaboraciones_reparto rep ON rep.lote_inclusion_id = se.id_lote ' +
        'JOIN ob_elaboraciones e ON e.id = rep.elaboracion_id ' +
        'WHERE DATE(e.fecha) = :fecha AND COALESCE(se.estado_fabricacion, ''PENDIENTE'') = ''PENDIENTE''';
      qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
      qExec.ExecSQL;

      // Asegurar también la limpieza de stock envasado pendiente asociado a lotes de esta fecha
      qExec.Close;
      qExec.SQL.Text :=
        'DELETE se FROM ge_stock_envasado se ' +
        'JOIN ge_lotes l ON l.id = se.id_lote ' +
        'WHERE DATE(l.fecha) = :fecha AND COALESCE(se.estado_fabricacion, ''PENDIENTE'') = ''PENDIENTE''';
      qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
      qExec.ExecSQL;

      // Limpiar materias primas teóricas/consumidas de elaboraciones pendientes de esta fecha
      qExec.Close;
      qExec.SQL.Text :=
        'DELETE c FROM ob_lotes_consumidos c ' +
        'JOIN ob_elaboraciones e ON e.id = c.elaboracion_id ' +
        'WHERE e.fecha = :fecha AND e.hora_inicio IS NULL AND e.hora_fin IS NULL';
      qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
      qExec.ExecSQL;

      qExec.Close;
      qExec.SQL.Text :=
        'DELETE rep FROM ob_elaboraciones_reparto rep ' +
        'JOIN ob_elaboraciones e ON e.id = rep.elaboracion_id ' +
        'WHERE e.fecha = :fecha';
      qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
      qExec.ExecSQL;

      qExec.Close;
      qExec.SQL.Text :=
        'DELETE FROM ob_elaboraciones ' +
        'WHERE fecha = :fecha AND hora_inicio IS NULL AND hora_fin IS NULL';
      qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
      qExec.ExecSQL;

      // Eliminar lotes huérfanos previos de esa fecha si no se usan ni tienen stock ni órdenes
      qExec.Close;
      qExec.SQL.Text :=
        'DELETE l FROM ge_lotes l ' +
        'WHERE l.fecha = :fecha ' +
        '  AND NOT EXISTS (SELECT 1 FROM ob_elaboraciones e WHERE e.lote_id = l.id) ' +
        '  AND NOT EXISTS (SELECT 1 FROM ob_elaboraciones_reparto r WHERE r.lote_inclusion_id = l.id) ' +
        '  AND NOT EXISTS (SELECT 1 FROM ge_stock_envasado s WHERE s.id_lote = l.id) ' +
        '  AND NOT EXISTS (' +
        '    SELECT 1 FROM ge_albaranes_lineas alb ' +
        '    WHERE (NULLIF(l.codigo_antiguo, '''') IS NOT NULL AND alb.lotes LIKE CONCAT(''%'', l.codigo_antiguo, ''%'')) ' +
        '       OR alb.lotes LIKE CONCAT(''%'', CAST(l.codigo AS CHAR), ''%'')' +
        '  )';
      qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
      qExec.ExecSQL;
    end;

    if FPlan.EsMasaBase then
    begin
      var LPesoMMRef := FPlan.MasaMadrePorMasaKg;
      if LPesoMMRef <= 0.001 then
        LPesoMMRef := 10.005;

      if FPlan.MasasBaseManana > 0 then
        LObs := Format('Masa Madre - Total a Elaborar: %.2f kg (Hoy: %.2f kg, Reserva Mañana [%d masas x 2,0 kg]: %.2f kg)',
          [FPlan.MasaMadreTotalKg, FPlan.MasaMadreHoyKg, FPlan.MasasBaseManana, FPlan.MasaMadreExtraKg])
      else
        LObs := Format('Masa Madre - Total a Elaborar: %.2f kg (Hoy: %.2f kg, Extra: %.2f kg)',
          [FPlan.MasaMadreTotalKg, FPlan.MasaMadreHoyKg, FPlan.MasaMadreExtraKg]);

      // Comprobar si ya existe orden de Masa Madre para esta fecha
      var LElabMMId: Integer := 0;
      qExec.Close;
      qExec.SQL.Text :=
        'SELECT id, lote_id FROM ob_elaboraciones ' +
        'WHERE fecha = :fecha AND id_receta = :receta LIMIT 1';
      qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
      qExec.ParamByName('receta').AsInteger := FPlan.RecetaMasaMadreId;
      qExec.Open;
      if not qExec.IsEmpty then
      begin
        LElabMMId := qExec.FieldByName('id').AsInteger;
        LIdLoteMM := qExec.FieldByName('lote_id').AsInteger;

        qExec.Close;
        qExec.SQL.Text :=
          'UPDATE ob_elaboraciones SET multiplicador = :mult, numero_masas = :num, observaciones = :obs WHERE id = :id';
        qExec.ParamByName('id').AsInteger := LElabMMId;
        qExec.ParamByName('mult').AsFloat := FPlan.MasaMadreTotalKg / LPesoMMRef;
        qExec.ParamByName('num_masas').AsInteger := Max(1, Ceil(FPlan.MasaMadreTotalKg / LPesoMMRef));
        qExec.ParamByName('obs').AsString := LObs;
        qExec.ExecSQL;

        if LIdLoteMM > 0 then
        begin
          qExec.Close;
          qExec.SQL.Text := 'UPDATE ge_lotes SET observaciones = :obs WHERE id = :id';
          qExec.ParamByName('id').AsInteger := LIdLoteMM;
          qExec.ParamByName('obs').AsString := LObs;
          qExec.ExecSQL;
        end;
      end
      else
      begin
        // 1. Crear Lote y Orden para Receta 3 (MASA MADRE)
        if not TryStrToInt(Trim(FPlan.LoteMasaMadreCodigo), LCodMM) then
          LCodMM := dmgMain.GetNextCodigoLote;
        LCodigoAntMM := Trim(FPlan.LoteMasaMadreCodigo);
        if LCodigoAntMM = '' then LCodigoAntMM := IntToStr(LCodMM);

        qExec.Close;
        qExec.SQL.Text := 'SELECT id FROM ge_lotes WHERE codigo_antiguo = :cod LIMIT 1';
        qExec.ParamByName('cod').AsString := LCodigoAntMM;
        qExec.Open;
        if not qExec.IsEmpty then
        begin
          LIdLoteMM := qExec.FieldByName('id').AsInteger;
          qExec.Close;
          qExec.SQL.Text :=
            'UPDATE ge_lotes SET id_receta = :receta, id_obrador = :id_obrador, fecha = :fecha, ' +
            '  observaciones = :observaciones, id_user_update = :user WHERE id = :id';
          qExec.ParamByName('id').AsInteger := LIdLoteMM;
          qExec.ParamByName('receta').AsInteger := FPlan.RecetaMasaMadreId;
          qExec.ParamByName('id_obrador').AsInteger := LObradorId;
          qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
          qExec.ParamByName('observaciones').AsString := LObs;
          qExec.ParamByName('user').AsInteger := LUserId;
          qExec.ExecSQL;
        end
        else
        begin
          qExec.Close;
          qExec.SQL.Text :=
            'INSERT INTO ge_lotes (codigo, codigo_antiguo, id_receta, id_obrador, fecha, observaciones, activo, id_user_creator, id_user_update) ' +
            'VALUES (:codigo, :codigo_antiguo, :receta, :id_obrador, :fecha, :observaciones, 1, :user, :user)';
          qExec.ParamByName('codigo').AsInteger := LCodMM;
          qExec.ParamByName('codigo_antiguo').AsString := LCodigoAntMM;
          qExec.ParamByName('receta').AsInteger := FPlan.RecetaMasaMadreId;
          qExec.ParamByName('id_obrador').AsInteger := LObradorId;
          qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
          qExec.ParamByName('observaciones').AsString := LObs;
          qExec.ParamByName('user').AsInteger := LUserId;
          qExec.ExecSQL;

          qExec.Close;
          qExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS last_id';
          qExec.Open;
          LIdLoteMM := qExec.FieldByName('last_id').AsInteger;
        end;

        qExec.Close;
        qExec.SQL.Text :=
          'INSERT INTO ob_elaboraciones (tipo, fecha, id_obrador, id_receta, lote_id, multiplicador, numero_masas, observaciones, id_user_creator) ' +
          'VALUES (''primer_empaste'', :fecha, :id_obrador, :receta, :lote_id, :mult, :num_masas, :obs, :user)';
        qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
        qExec.ParamByName('id_obrador').AsInteger := LObradorId;
        qExec.ParamByName('receta').AsInteger := FPlan.RecetaMasaMadreId;
        qExec.ParamByName('lote_id').AsInteger := LIdLoteMM;
        qExec.ParamByName('mult').AsFloat := FPlan.MasaMadreTotalKg / LPesoMMRef;
        qExec.ParamByName('num_masas').AsInteger := Max(1, Ceil(FPlan.MasaMadreTotalKg / LPesoMMRef));
        qExec.ParamByName('obs').AsString := LObs;
        qExec.ParamByName('user').AsInteger := LUserId;
        qExec.ExecSQL;

        qExec.Close;
        qExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS last_id';
        qExec.Open;
        LElabMMId := qExec.FieldByName('last_id').AsInteger;

        // Registrar materias primas teóricas para la Masa Madre
        RegistrarMateriasPrimasTeoricasElaboracion(LElabMMId, FPlan.RecetaMasaMadreId, FPlan.MasaMadreTotalKg / LPesoMMRef, LUserId);
      end;

      // 2. Para cada Masa Base: Crear Orden de 1ER EMPASTE individual y Orden de 2º EMPASTE vinculada
      var LUsedLotes1E := TList<string>.Create;
      var LUsedLotesMB := TList<string>.Create;
      try
        for i := 0 to FPlan.Masas.Count - 1 do
        begin
          LMasa := FPlan.Masas[i];

          // Si ya existe en la base de datos y estamos en modo añadir, no tocar la masa
          if LHasExisting and LHasNew and LMasa.EsExistente then
          begin
            if LMasa.Lote1erEmpasteCodigo <> '' then
              LUsedLotes1E.Add(Trim(LMasa.Lote1erEmpasteCodigo));
            if LMasa.LoteCodigo <> '' then
              LUsedLotesMB.Add(Trim(LMasa.LoteCodigo));
            Continue;
          end;

          // --- A. Orden y Lote de 1ER EMPASTE individual para esta masa ---
          LCodigoAnt1E := Trim(LMasa.Lote1erEmpasteCodigo);
          if (LCodigoAnt1E = '') or LUsedLotes1E.Contains(LCodigoAnt1E) then
          begin
            LCod1E := dmgMain.GetNextCodigoLote;
            LCodigoAnt1E := IntToStr(LCod1E);
            LMasa.Lote1erEmpasteCodigo := LCodigoAnt1E;
          end
          else if not TryStrToInt(LCodigoAnt1E, LCod1E) then
          begin
            LCod1E := dmgMain.GetNextCodigoLote;
            LCodigoAnt1E := IntToStr(LCod1E);
            LMasa.Lote1erEmpasteCodigo := LCodigoAnt1E;
          end;
          LUsedLotes1E.Add(LCodigoAnt1E);

          LObs := Format('%s - 1er Empaste', [LMasa.NombreMasa]);

          qExec.Close;
          qExec.SQL.Text := 'SELECT id FROM ge_lotes WHERE codigo_antiguo = :cod LIMIT 1';
          qExec.ParamByName('cod').AsString := LCodigoAnt1E;
          qExec.Open;
          if not qExec.IsEmpty then
          begin
            LIdLote1E := qExec.FieldByName('id').AsInteger;
            qExec.Close;
            qExec.SQL.Text :=
              'UPDATE ge_lotes SET id_receta = 22, id_obrador = :id_obrador, fecha = :fecha, ' +
              '  observaciones = :observaciones, id_user_update = :user WHERE id = :id';
            qExec.ParamByName('id').AsInteger := LIdLote1E;
            qExec.ParamByName('id_obrador').AsInteger := LObradorId;
            qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
            qExec.ParamByName('observaciones').AsString := LObs;
            qExec.ParamByName('user').AsInteger := LUserId;
            qExec.ExecSQL;
          end
          else
          begin
            qExec.Close;
            qExec.SQL.Text :=
              'INSERT INTO ge_lotes (codigo, codigo_antiguo, id_receta, id_obrador, fecha, observaciones, activo, id_user_creator, id_user_update) ' +
              'VALUES (:codigo, :codigo_antiguo, 22, :id_obrador, :fecha, :observaciones, 1, :user, :user)';
            qExec.ParamByName('codigo').AsInteger := LCod1E;
            qExec.ParamByName('codigo_antiguo').AsString := LCodigoAnt1E;
            qExec.ParamByName('id_obrador').AsInteger := LObradorId;
            qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
            qExec.ParamByName('observaciones').AsString := LObs;
            qExec.ParamByName('user').AsInteger := LUserId;
            qExec.ExecSQL;

            qExec.Close;
            qExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS last_id';
            qExec.Open;
            LIdLote1E := qExec.FieldByName('last_id').AsInteger;
          end;

          qExec.Close;
          qExec.SQL.Text :=
            'INSERT INTO ob_elaboraciones (tipo, fecha, id_obrador, id_receta, lote_id, multiplicador, numero_masas, observaciones, id_user_creator) ' +
            'VALUES (''primer_empaste'', :fecha, :id_obrador, 22, :lote_id, :mult, 1, :obs, :user)';
          qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
          qExec.ParamByName('id_obrador').AsInteger := LObradorId;
          qExec.ParamByName('lote_id').AsInteger := LIdLote1E;
          qExec.ParamByName('mult').AsFloat := LMasa.Multiplicador;
          qExec.ParamByName('obs').AsString := LObs;
          qExec.ParamByName('user').AsInteger := LUserId;
          qExec.ExecSQL;

          qExec.Close;
          qExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS last_id';
          qExec.Open;
          LElab1EId := qExec.FieldByName('last_id').AsInteger;

          // Registrar materias primas teóricas para la orden de 1er empaste de esta masa individual
          RegistrarMateriasPrimasTeoricasElaboracion(LElab1EId, 22, LMasa.Multiplicador, LUserId, LPesoMMRef);

          // --- B. Orden y Lote de 2º EMPASTE para esta masa ---
          LCodigoAntMB := Trim(LMasa.LoteCodigo);
          if (LCodigoAntMB = '') or LUsedLotesMB.Contains(LCodigoAntMB) or LUsedLotes1E.Contains(LCodigoAntMB) then
          begin
            LCodMB := dmgMain.GetNextCodigoLote;
            LCodigoAntMB := IntToStr(LCodMB);
            LMasa.LoteCodigo := LCodigoAntMB;
          end
          else if not TryStrToInt(LCodigoAntMB, LCodMB) then
          begin
            LCodMB := dmgMain.GetNextCodigoLote;
            LCodigoAntMB := IntToStr(LCodMB);
            LMasa.LoteCodigo := LCodigoAntMB;
          end;
          LUsedLotesMB.Add(LCodigoAntMB);

          qExec.Close;
          qExec.SQL.Text := 'SELECT id FROM ge_lotes WHERE codigo_antiguo = :cod LIMIT 1';
          qExec.ParamByName('cod').AsString := LCodigoAntMB;
          qExec.Open;
        if not qExec.IsEmpty then
        begin
          LIdLoteMB := qExec.FieldByName('id').AsInteger;
          qExec.Close;
          qExec.SQL.Text :=
            'UPDATE ge_lotes SET id_receta = :id_receta, id_obrador = :id_obrador, fecha = :fecha, ' +
            '  observaciones = :observaciones, id_user_update = :user WHERE id = :id';
          qExec.ParamByName('id').AsInteger := LIdLoteMB;
          qExec.ParamByName('id_receta').AsInteger := FPlan.RecetaPrincipalId;
          qExec.ParamByName('id_obrador').AsInteger := LObradorId;
          qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
          qExec.ParamByName('observaciones').AsString := LMasa.NombreMasa + ' (2º Empaste)';
          qExec.ParamByName('user').AsInteger := LUserId;
          qExec.ExecSQL;
        end
        else
        begin
          qExec.Close;
          qExec.SQL.Text :=
            'INSERT INTO ge_lotes (codigo, codigo_antiguo, id_receta, id_obrador, fecha, observaciones, activo, id_user_creator, id_user_update) ' +
            'VALUES (:codigo, :codigo_antiguo, :id_receta, :id_obrador, :fecha, :observaciones, 1, :user, :user)';
          qExec.ParamByName('codigo').AsInteger := LCodMB;
          qExec.ParamByName('codigo_antiguo').AsString := LCodigoAntMB;
          qExec.ParamByName('id_receta').AsInteger := FPlan.RecetaPrincipalId;
          qExec.ParamByName('id_obrador').AsInteger := LObradorId;
          qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
          qExec.ParamByName('observaciones').AsString := LMasa.NombreMasa + ' (2º Empaste)';
          qExec.ParamByName('user').AsInteger := LUserId;
          qExec.ExecSQL;

          qExec.Close;
          qExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS last_id';
          qExec.Open;
          LIdLoteMB := qExec.FieldByName('last_id').AsInteger;
        end;

        qExec.Close;
        qExec.SQL.Text :=
          'INSERT INTO ob_elaboraciones (tipo, fecha, id_obrador, id_receta, lote_id, multiplicador, numero_masas, ' +
          '  elaboracion_origen_id, reparto_modo, observaciones, id_user_creator) ' +
          'VALUES (''segundo_empaste'', :fecha, :id_obrador, :id_receta, :lote_id, :mult, 1, :origen, ''porcentaje'', :obs, :user)';
        qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
        qExec.ParamByName('id_obrador').AsInteger := LObradorId;
        qExec.ParamByName('id_receta').AsInteger := FPlan.RecetaPrincipalId;
        qExec.ParamByName('lote_id').AsInteger := LIdLoteMB;
        qExec.ParamByName('mult').AsFloat := LMasa.Multiplicador;
        qExec.ParamByName('origen').AsInteger := LElab1EId;
        qExec.ParamByName('obs').AsString := Format('%s - Reparto de sabores', [LMasa.NombreMasa]);
        qExec.ParamByName('user').AsInteger := LUserId;
        qExec.ExecSQL;

        qExec.Close;
        qExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS last_id';
        qExec.Open;
        LElabMBId := qExec.FieldByName('last_id').AsInteger;

        // Registrar materias primas teóricas para la orden de 2º empaste de esta masa individual
        RegistrarMateriasPrimasTeoricasElaboracion(LElabMBId, FPlan.RecetaPrincipalId, LMasa.Multiplicador, LUserId);

        // 4. Crear Lotes de Sabores, Repartos en ob_elaboraciones_reparto y Stock Envasado PENDIENTE
        // Misma masa + mismo sabor (aunque cambie el formato L/XL/MINI) debe compartir un único lote.
        var LLotesEnMasa := TDictionary<string, Integer>.Create;
        try
        for j := 0 to LMasa.Sabores.Count - 1 do
        begin
          LSabor := LMasa.Sabores[j];
          LCodigoAntSabor := Trim(LSabor.LoteCodigo);

          LIdLoteSabor := 0;
          var LLoteYaCreadoEnMasa := False;
          if (LCodigoAntSabor <> '') and LLotesEnMasa.TryGetValue(UpperCase(LCodigoAntSabor), LIdLoteSabor) then
          begin
            LLoteYaCreadoEnMasa := True;
          end
          else
          begin
            // Verificar si ya existe el lote con este codigo_antiguo.
            // Si pertenece a esta misma masa (codigo = LCodMB), compartirlo entre formatos;
            // solo desambiguar si colisiona con otra masa/fecha distinta.
            var LCandSuf := 0;
            var LCodBaseSabor := LCodigoAntSabor;
            while True do
            begin
              qExec.Close;
              qExec.SQL.Text := 'SELECT id, codigo, COALESCE(id_articulo, 0) AS id_art FROM ge_lotes WHERE codigo_antiguo = :cod LIMIT 1';
              qExec.ParamByName('cod').AsString := LCodigoAntSabor;
              qExec.Open;
              if qExec.IsEmpty then
                Break;

              if (qExec.FieldByName('codigo').AsInteger = LCodMB) or
                 ((LSabor.ArticuloId > 0) and (qExec.FieldByName('id_art').AsInteger = LSabor.ArticuloId)) or
                 ((LSabor.ArticuloId <= 0) and (qExec.FieldByName('id_art').AsInteger = 0)) then
              begin
                LIdLoteSabor := qExec.FieldByName('id').AsInteger;
                if qExec.FieldByName('codigo').AsInteger = LCodMB then
                  LLoteYaCreadoEnMasa := True;
                Break;
              end;

              Inc(LCandSuf);
              LCodigoAntSabor := LCodBaseSabor + '-' + IntToStr(LCandSuf + 1);
            end;
          end;
          LSabor.LoteCodigo := LCodigoAntSabor;

          if LIdLoteSabor > 0 then
          begin
            if not LLoteYaCreadoEnMasa then
            begin
              qExec.Close;
              qExec.SQL.Text :=
                'UPDATE ge_lotes SET id_receta = :id_receta, id_articulo = :id_articulo, id_obrador = :id_obrador, ' +
                '  fecha = :fecha, observaciones = :observaciones, id_user_update = :user WHERE id = :id';
              qExec.ParamByName('id').AsInteger := LIdLoteSabor;
              qExec.ParamByName('id_receta').AsInteger := LSabor.RecetaId;
              if LSabor.ArticuloId > 0 then
                qExec.ParamByName('id_articulo').AsInteger := LSabor.ArticuloId
              else
                qExec.ParamByName('id_articulo').Clear;
              qExec.ParamByName('id_obrador').AsInteger := LObradorId;
              qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
              qExec.ParamByName('observaciones').AsString := Format('%s (%.0f%% de %s)', [LSabor.ArticuloDesc, LSabor.Porcentaje, LMasa.NombreMasa]);
              qExec.ParamByName('user').AsInteger := LUserId;
              qExec.ExecSQL;
            end;
          end
          else
          begin
            // Lote de sabor en ge_lotes: el campo codigo coincide con el codigo de la masa base (LCodMB)
            qExec.Close;
            qExec.SQL.Text :=
              'INSERT INTO ge_lotes (codigo, codigo_antiguo, id_receta, id_articulo, id_obrador, fecha, observaciones, activo, id_user_creator, id_user_update) ' +
              'VALUES (:codigo, :codigo_antiguo, :id_receta, :id_articulo, :id_obrador, :fecha, :observaciones, 1, :user, :user)';
            qExec.ParamByName('codigo').AsInteger := LCodMB;
            qExec.ParamByName('codigo_antiguo').AsString := LCodigoAntSabor;
            qExec.ParamByName('id_receta').AsInteger := LSabor.RecetaId;
            if LSabor.ArticuloId > 0 then
              qExec.ParamByName('id_articulo').AsInteger := LSabor.ArticuloId
            else
              qExec.ParamByName('id_articulo').Clear;
            qExec.ParamByName('id_obrador').AsInteger := LObradorId;
            qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
            qExec.ParamByName('observaciones').AsString := Format('%s (%.0f%% de %s)', [LSabor.ArticuloDesc, LSabor.Porcentaje, LMasa.NombreMasa]);
            qExec.ParamByName('user').AsInteger := LUserId;
            qExec.ExecSQL;

            qExec.Close;
            qExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS last_id';
            qExec.Open;
            LIdLoteSabor := qExec.FieldByName('last_id').AsInteger;
          end;

          if (LCodigoAntSabor <> '') and (LIdLoteSabor > 0) then
            LLotesEnMasa.AddOrSetValue(UpperCase(LCodigoAntSabor), LIdLoteSabor);

          // Reparto en ob_elaboraciones_reparto
          qExec.Close;
          qExec.SQL.Text :=
            'INSERT INTO ob_elaboraciones_reparto (elaboracion_id, id_articulo, sabor, porcentaje, cantidad, lote_inclusion_id, id_user_creator) ' +
            'VALUES (:elab, :art, :sabor, :porc, :cant, :lote_inc, :user)';
          qExec.ParamByName('elab').AsInteger := LElabMBId;
          if LSabor.ArticuloId > 0 then
            qExec.ParamByName('art').AsInteger := LSabor.ArticuloId
          else
          begin
            qExec.ParamByName('art').DataType := ftInteger;
            qExec.ParamByName('art').Clear;
          end;
          qExec.ParamByName('sabor').AsString := LSabor.ArticuloDesc;
          qExec.ParamByName('porc').AsFloat := LSabor.Porcentaje;
          qExec.ParamByName('cant').AsFloat := LSabor.UnidadesXL;
          qExec.ParamByName('lote_inc').AsInteger := LIdLoteSabor;
          qExec.ParamByName('user').AsInteger := LUserId;
          qExec.ExecSQL;

          // 5. REGISTRO EN ge_stock_envasado CON ESTADO 'PENDIENTE'
          if LSabor.ArticuloId > 0 then
          begin
            qExec.Close;
            qExec.SQL.Text :=
              'INSERT INTO ge_stock_envasado (id_almacen, id_articulo, id_lote, id_formato_presentacion, ' +
              '  estado_fabricacion, cantidad_unidades, cantidad_producida, cantidad_reservada, created_at, id_user_creator) ' +
              'VALUES (:alm, :art, :lote, 1, ''PENDIENTE'', :cant_uds, :cant_fabricada, 0.0, NOW(), :user) ' +
              'ON DUPLICATE KEY UPDATE ' +
              '  cantidad_unidades = cantidad_unidades + VALUES(cantidad_unidades), ' +
              '  cantidad_producida = cantidad_producida + VALUES(cantidad_producida), ' +
              '  estado_fabricacion = ''PENDIENTE'', ' +
              '  id_user_update = VALUES(id_user_creator)';
            qExec.ParamByName('alm').AsInteger := LAlmId;
            qExec.ParamByName('art').AsInteger := LSabor.ArticuloId;
            qExec.ParamByName('lote').AsInteger := LIdLoteSabor;
            qExec.ParamByName('cant_uds').AsFloat := LSabor.UnidadesXL;
            qExec.ParamByName('cant_fabricada').AsFloat := LSabor.UnidadesXL;
            qExec.ParamByName('user').AsInteger := LUserId;
            qExec.ExecSQL;
          end;

          // 6. CREAR ORDEN DE ELABORACIÓN PARA EL ARTÍCULO FINAL (SABOR / INCLUSIONES)
          LRecetaSaborId := LSabor.RecetaId;
          if (LRecetaSaborId <= 0) and (LSabor.ArticuloId > 0) then
          begin
            qExec.Close;
            qExec.SQL.Text := 'SELECT receta_id FROM ob_recetas_productos WHERE articulo_id = :art LIMIT 1';
            qExec.ParamByName('art').AsInteger := LSabor.ArticuloId;
            qExec.Open;
            if not qExec.IsEmpty then
              LRecetaSaborId := qExec.FieldByName('receta_id').AsInteger;
          end;

          if LRecetaSaborId > 0 then
          begin
            qExec.Close;
            qExec.SQL.Text :=
              'INSERT INTO ob_elaboraciones (tipo, fecha, id_obrador, id_receta, lote_id, multiplicador, numero_masas, ' +
              '  elaboracion_origen_id, reparto_modo, observaciones, id_user_creator) ' +
              'VALUES (''articulo_final'', :fecha, :id_obrador, :id_receta, :lote_id, :mult, 1, :origen, ''porcentaje'', :obs, :user)';
            qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
            qExec.ParamByName('id_obrador').AsInteger := LObradorId;
            qExec.ParamByName('id_receta').AsInteger := LRecetaSaborId;
            qExec.ParamByName('lote_id').AsInteger := LIdLoteSabor;
            qExec.ParamByName('mult').AsFloat := LMasa.Multiplicador * (LSabor.Porcentaje / 100.0);
            qExec.ParamByName('origen').AsInteger := LElabMBId;
            qExec.ParamByName('obs').AsString := Format('%s - %s (%.0f%%)', [LMasa.NombreMasa, LSabor.ArticuloDesc, LSabor.Porcentaje]);
            qExec.ParamByName('user').AsInteger := LUserId;
            qExec.ExecSQL;

            qExec.Close;
            qExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS last_id';
            qExec.Open;
            LElabSaborId := qExec.FieldByName('last_id').AsInteger;

            // Registrar materias primas teóricas para la orden del artículo final (masa base consumida + inclusiones)
            RegistrarMateriasPrimasInclusionesElaboracion(
              LElabSaborId, LRecetaSaborId, LMasa.Multiplicador * (LSabor.Porcentaje / 100.0),
              LIdLoteMB, LMasa.LoteCodigo, LUserId);
          end;
        end;
        finally
          LLotesEnMasa.Free;
        end;

        LMasa.EsExistente := True;
      end;
    finally
      LUsedLotes1E.Free;
      LUsedLotesMB.Free;
    end;
  end
    else if FPlan.EsMasaMadre then
    begin
      // Crear o Reutilizar Lote y Orden para Receta de Masa Madre directa
      if not TryStrToInt(Trim(FPlan.LoteMasaMadreCodigo), LCodMM) then
        LCodMM := dmgMain.GetNextCodigoLote;
      LCodigoAntMM := Trim(FPlan.LoteMasaMadreCodigo);
      if LCodigoAntMM = '' then LCodigoAntMM := IntToStr(LCodMM);

      if FPlan.MasasBaseManana > 0 then
        LObs := Format('Masa Madre - Total a Elaborar: %.2f kg (Hoy: %.2f kg, Reserva Mañana [%d masas x 2,0 kg]: %.2f kg)',
          [FPlan.MasaMadreTotalKg, FPlan.MasaMadreHoyKg, FPlan.MasasBaseManana, FPlan.MasaMadreExtraKg])
      else
        LObs := Format('Masa Madre - Total a Elaborar: %.2f kg (Hoy: %.2f kg, Extra: %.2f kg)',
          [FPlan.MasaMadreTotalKg, FPlan.MasaMadreHoyKg, FPlan.MasaMadreExtraKg]);

      qExec.Close;
      qExec.SQL.Text := 'SELECT id FROM ge_lotes WHERE codigo_antiguo = :cod LIMIT 1';
      qExec.ParamByName('cod').AsString := LCodigoAntMM;
      qExec.Open;
      if not qExec.IsEmpty then
      begin
        LIdLoteMM := qExec.FieldByName('id').AsInteger;
        qExec.Close;
        qExec.SQL.Text :=
          'UPDATE ge_lotes SET id_receta = :receta, id_obrador = :id_obrador, fecha = :fecha, ' +
          '  observaciones = :observaciones, id_user_update = :user WHERE id = :id';
        qExec.ParamByName('id').AsInteger := LIdLoteMM;
        qExec.ParamByName('receta').AsInteger := FPlan.RecetaPrincipalId;
        qExec.ParamByName('id_obrador').AsInteger := LObradorId;
        qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
        qExec.ParamByName('observaciones').AsString := LObs;
        qExec.ParamByName('user').AsInteger := LUserId;
        qExec.ExecSQL;
      end
      else
      begin
        qExec.Close;
        qExec.SQL.Text :=
          'INSERT INTO ge_lotes (codigo, codigo_antiguo, id_receta, id_obrador, fecha, observaciones, activo, id_user_creator, id_user_update) ' +
          'VALUES (:codigo, :codigo_antiguo, :receta, :id_obrador, :fecha, :observaciones, 1, :user, :user)';
        qExec.ParamByName('codigo').AsInteger := LCodMM;
        qExec.ParamByName('codigo_antiguo').AsString := LCodigoAntMM;
        qExec.ParamByName('receta').AsInteger := FPlan.RecetaPrincipalId;
        qExec.ParamByName('id_obrador').AsInteger := LObradorId;
        qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
        qExec.ParamByName('observaciones').AsString := LObs;
        qExec.ParamByName('user').AsInteger := LUserId;
        qExec.ExecSQL;

        qExec.Close;
        qExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS last_id';
        qExec.Open;
        LIdLoteMM := qExec.FieldByName('last_id').AsInteger;
      end;

      var LPesoMMRef := FPlan.MasaMadrePorMasaKg;
      if LPesoMMRef <= 0.001 then
        LPesoMMRef := 10.005;

      qExec.Close;
      qExec.SQL.Text :=
        'INSERT INTO ob_elaboraciones (tipo, fecha, id_obrador, id_receta, lote_id, multiplicador, numero_masas, observaciones, id_user_creator) ' +
        'VALUES (''primer_empaste'', :fecha, :id_obrador, :receta, :lote_id, :mult, :num_masas, :obs, :user)';
      qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
      qExec.ParamByName('id_obrador').AsInteger := LObradorId;
      qExec.ParamByName('receta').AsInteger := FPlan.RecetaPrincipalId;
      qExec.ParamByName('lote_id').AsInteger := LIdLoteMM;
      qExec.ParamByName('mult').AsFloat := FPlan.MasaMadreTotalKg / LPesoMMRef;
      qExec.ParamByName('num_masas').AsInteger := Max(1, Ceil(FPlan.MasaMadreTotalKg / LPesoMMRef));
      qExec.ParamByName('obs').AsString := LObs;
      qExec.ParamByName('user').AsInteger := LUserId;
      qExec.ExecSQL;

      qExec.Close;
      qExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS last_id';
      qExec.Open;
      var LElabMMDirectaId := qExec.FieldByName('last_id').AsInteger;
      RegistrarMateriasPrimasTeoricasElaboracion(LElabMMDirectaId, FPlan.RecetaPrincipalId, FPlan.MasaMadreTotalKg / LPesoMMRef, LUserId);
    end;

    // Limpiar cualquier lote de la fecha que haya quedado huérfano tras el reemplazo
    if not (LHasExisting and LHasNew) then
    begin
      qExec.Close;
      qExec.SQL.Text :=
        'DELETE l FROM ge_lotes l ' +
        'WHERE l.fecha = :fecha ' +
        '  AND NOT EXISTS (SELECT 1 FROM ob_elaboraciones e WHERE e.lote_id = l.id) ' +
        '  AND NOT EXISTS (SELECT 1 FROM ob_elaboraciones_reparto r WHERE r.lote_inclusion_id = l.id) ' +
        '  AND NOT EXISTS (SELECT 1 FROM ge_stock_envasado s WHERE s.id_lote = l.id)';
      qExec.ParamByName('fecha').AsDate := dtpFechaLote.Date;
      qExec.ExecSQL;
    end;

    dmgMain.dbConn.Commit;
    if LHasExisting and LHasNew then
      MessageDlg('✅ Nuevas masas añadidas correctamente:' + sLineBreak +
                 '• Las órdenes de fabricación ya existentes se mantuvieron intactas.' + sLineBreak +
                 '• Nuevas órdenes de fabricación creadas en ob_elaboraciones.' + sLineBreak +
                 '• Nuevos lotes correlativos registrados en ge_lotes.',
                 mtInformation, [mbOK], 0)
    else
      MessageDlg('✅ Planificación guardada correctamente:' + sLineBreak +
                 '• Órdenes de fabricación creadas en ob_elaboraciones' + sLineBreak +
                 '• Lotes correlativos creados en ge_lotes' + sLineBreak +
                 '• Registros de stock envasado generados con estado PENDIENTE.',
                 mtInformation, [mbOK], 0);

    CargarPlanDesdeFecha(dtpFechaLote.Date);

    // Emitir el informe automáticamente
    btnVerInformeClick(nil);
  except
    on E: Exception do
    begin
      dmgMain.dbConn.Rollback;
      MessageDlg('Error al guardar la planificación de fabricación: ' + E.Message, mtError, [mbOK], 0);
    end;
  end;
end;

function TfrmPlanificacionMasasProduccion.SolicitarFechaDestino(
  const ACaption, APrompt: string; var AFecha: TDateTime): Boolean;
var
  LDlg: TForm;
  LLbl: TLabel;
  LDtp: TDateTimePicker;
  LBtnOk, LBtnCancel: TBitBtn;
  LPnlBottom: TPanel;
begin
  Result := False;
  LDlg := TForm.Create(nil);
  try
    LDlg.BorderStyle := bsDialog;
    LDlg.Position := poOwnerFormCenter;
    LDlg.Caption := ACaption;
    LDlg.ClientWidth := 360;
    LDlg.ClientHeight := 155;
    LDlg.Font.Name := 'Segoe UI';
    LDlg.Font.Size := 9;
    LDlg.Color := clWhite;

    LLbl := TLabel.Create(LDlg);
    LLbl.Parent := LDlg;
    LLbl.Left := 20;
    LLbl.Top := 16;
    LLbl.Width := 320;
    LLbl.AutoSize := False;
    LLbl.WordWrap := True;
    LLbl.Font.Name := 'Segoe UI Semibold';
    LLbl.Font.Size := 9;
    LLbl.Caption := APrompt;

    LDtp := TDateTimePicker.Create(LDlg);
    LDtp.Parent := LDlg;
    LDtp.Left := 20;
    LDtp.Top := 60;
    LDtp.Width := 140;
    LDtp.Height := 25;
    LDtp.Font.Name := 'Segoe UI';
    LDtp.Font.Size := 10;
    LDtp.Date := AFecha;

    LPnlBottom := TPanel.Create(LDlg);
    LPnlBottom.Parent := LDlg;
    LPnlBottom.Align := alBottom;
    LPnlBottom.Height := 48;
    LPnlBottom.BevelOuter := bvNone;
    LPnlBottom.Color := $00F2F2F2;
    LPnlBottom.ParentBackground := False;

    LBtnOk := TBitBtn.Create(LPnlBottom);
    LBtnOk.Parent := LPnlBottom;
    LBtnOk.Left := 160;
    LBtnOk.Top := 10;
    LBtnOk.Width := 90;
    LBtnOk.Height := 28;
    LBtnOk.Caption := 'Aceptar';
    LBtnOk.Font.Name := 'Segoe UI';
    LBtnOk.Font.Style := [fsBold];
    LBtnOk.ModalResult := mrOk;
    LBtnOk.Default := True;

    LBtnCancel := TBitBtn.Create(LPnlBottom);
    LBtnCancel.Parent := LPnlBottom;
    LBtnCancel.Left := 258;
    LBtnCancel.Top := 10;
    LBtnCancel.Width := 90;
    LBtnCancel.Height := 28;
    LBtnCancel.Caption := 'Cancelar';
    LBtnCancel.Font.Name := 'Segoe UI';
    LBtnCancel.ModalResult := mrCancel;
    LBtnCancel.Cancel := True;

    if LDlg.ShowModal = mrOk then
    begin
      AFecha := Trunc(LDtp.Date);
      Result := True;
    end;
  finally
    LDlg.Free;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnDuplicarPlanClick(Sender: TObject);
var
  LFechaDestino: TDateTime;
  LQry: TFDQuery;
  LTotalIniciadas, LTotalPendientes: Integer;
  i, j: Integer;
  LMasa, LMasaOrigen: TMasaBaseItem;
  LSabor, LSaborOrigen: TSaborRepartoItem;
  LListaMasasNueva: TObjectList<TMasaBaseItem>;
begin
  if (FPlan = nil) or (FPlan.Masas.Count = 0) then
  begin
    MessageDlg('No hay ninguna masa o planificación configurada para duplicar.' + sLineBreak +
               'Primero configure las masas o cargue una planificación existente.', mtInformation, [mbOK], 0);
    Exit;
  end;

  // 1. Proponer por defecto el día siguiente a la fecha del plan actual
  LFechaDestino := Trunc(dtpFechaLote.Date) + 1;

  // 2. Solicitar al usuario la fecha de destino con calendario interactivo
  if not SolicitarFechaDestino('Duplicar Planificación de Producción',
                              Format('Se va a duplicar la planificación del %s.' + sLineBreak +
                                     'Seleccione la fecha de destino a la que desea copiarla:',
                                     [FormatDateTime('dd/MM/yyyy', dtpFechaLote.Date)]),
                              LFechaDestino) then
    Exit;

  // 3. Validar que la fecha destino sea distinta a la actual
  if Trunc(LFechaDestino) = Trunc(dtpFechaLote.Date) then
  begin
    MessageDlg('La fecha de destino debe ser diferente a la fecha actual de la planificación.', mtWarning, [mbOK], 0);
    Exit;
  end;

  // 4. Validar contra la BD si existen elaboraciones en la fecha destino
  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;

    // Comprobar si hay órdenes en curso o finalizadas
    LQry.SQL.Text :=
      'SELECT COUNT(*) AS total_iniciadas ' +
      'FROM ob_elaboraciones ' +
      'WHERE fecha = :fecha AND (hora_inicio IS NOT NULL OR hora_fin IS NOT NULL)';
    LQry.ParamByName('fecha').AsDate := LFechaDestino;
    LQry.Open;
    LTotalIniciadas := LQry.FieldByName('total_iniciadas').AsInteger;
    LQry.Close;

    if LTotalIniciadas > 0 then
    begin
      MessageDlg(Format('No se puede duplicar al día %s porque ya existen órdenes de fabricación ' +
                        'en proceso ("EN AMASADO") o terminadas ("FINALIZADAS") en esa fecha.',
                        [FormatDateTime('dd/MM/yyyy', LFechaDestino)]), mtError, [mbOK], 0);
      Exit;
    end;

    // Comprobar si hay órdenes pendientes que se vayan a sobrescribir
    LQry.SQL.Text :=
      'SELECT COUNT(*) AS total_pendientes ' +
      'FROM ob_elaboraciones ' +
      'WHERE fecha = :fecha';
    LQry.ParamByName('fecha').AsDate := LFechaDestino;
    LQry.Open;
    LTotalPendientes := LQry.FieldByName('total_pendientes').AsInteger;
    LQry.Close;

    if LTotalPendientes > 0 then
    begin
      if MessageDlg(Format('Atención: Ya existe una planificación con %d órdenes guardadas para el día %s.' + sLineBreak +
                           '¿Desea sobrescribirla con la planificación actual duplicada?',
                           [LTotalPendientes, FormatDateTime('dd/MM/yyyy', LFechaDestino)]),
                    mtConfirmation, [mbYes, mbNo], 0) <> mrYes then
        Exit;
    end;
  finally
    LQry.Free;
  end;

  // 5. Duplicar en memoria las masas y sabores recalculando los códigos de lote para la nueva fecha
  LListaMasasNueva := TObjectList<TMasaBaseItem>.Create(True);
  try
    for i := 0 to FPlan.Masas.Count - 1 do
    begin
      LMasaOrigen := FPlan.Masas[i];
      LMasa := TMasaBaseItem.Create(LMasaOrigen.NumeroMasa);
      LMasa.NombreMasa := LMasaOrigen.NombreMasa;
      LMasa.Multiplicador := LMasaOrigen.Multiplicador;
      LMasa.EsExistente := False;
      LMasa.LoteCodigo := ''; // Se asignará limpio y fresco para la nueva fecha

      for j := 0 to LMasaOrigen.Sabores.Count - 1 do
      begin
        LSaborOrigen := LMasaOrigen.Sabores[j];
        LSabor := TSaborRepartoItem.Create;
        LSabor.ArticuloId := LSaborOrigen.ArticuloId;
        LSabor.ArticuloDesc := LSaborOrigen.ArticuloDesc;
        LSabor.RecetaId := LSaborOrigen.RecetaId;
        LSabor.RecetaDesc := LSaborOrigen.RecetaDesc;
        LSabor.PrefijoLote := LSaborOrigen.PrefijoLote;
        LSabor.Porcentaje := LSaborOrigen.Porcentaje;
        LSabor.UnidadesXL := LSaborOrigen.UnidadesXL;

        // Recalcular lote según la nueva fecha
        if LSabor.ArticuloId > 0 then
          LSabor.LoteCodigo := FormatearCodigoLoteSabor(LSabor.PrefijoLote, LFechaDestino, LMasa.NumeroMasa, LMasa.LoteCodigo, j)
        else
          LSabor.LoteCodigo := '';

        LMasa.Sabores.Add(LSabor);
      end;

      LListaMasasNueva.Add(LMasa);
    end;

    FPlan.Masas.Clear;
    LListaMasasNueva.OwnsObjects := False;
    for i := 0 to LListaMasasNueva.Count - 1 do
      FPlan.Masas.Add(LListaMasasNueva[i]);
    LListaMasasNueva.Clear;
  finally
    LListaMasasNueva.Free;
  end;

  // Resetear lotes de Masa Madre y 1er Empaste para la nueva fecha
  FPlan.LoteMasaMadreCodigo := '';
  FPlan.Lote1erEmpasteCodigo := '';
  FPlan.Fecha := LFechaDestino;

  // Cambiar la fecha en el selector visual suprimiendo el evento onChange
  FUpdatingControls := True;
  try
    dtpFechaLote.Date := LFechaDestino;
  finally
    FUpdatingControls := False;
  end;

  // Reconstruir interfaz de forma suave con bloqueo de repintado
  LockWindowUpdate(Self.Handle);
  try
    ReconstruirFilasReparto;
    ActualizarArbolProduccion;
    ValidarSumaPorcentajesSlots;
  finally
    LockWindowUpdate(0);
  end;

  // 6. Ofrecer guardar inmediatamente o revisar en pantalla
  if MessageDlg(Format('La planificación se ha duplicado con éxito para el día %s con sus nuevos códigos de lote calculados.' + sLineBreak + sLineBreak +
                       '¿Desea GUARDAR las órdenes de fabricación y stock en la base de datos ahora mismo?' + sLineBreak +
                       '(Si pulsa "No", la planificación permanecerá en pantalla para su revisión o edición antes de guardar)',
                       [FormatDateTime('dd/MM/yyyy', LFechaDestino)]),
                mtConfirmation, [mbYes, mbNo], 0) = mrYes then
  begin
    btnGuardarPlanClick(btnDuplicarPlan);
  end;
end;

function TfrmPlanificacionMasasProduccion.GenerarTextoInformeProduccion: string;
var
  LSb: TStringBuilder;
  LQry: TFDQuery;
  i, j, LTotalUds: Integer;
  LMasa: TMasaBaseItem;
  LSabor: TSaborRepartoItem;
  LObrStr: string;
  LGranTotalDict: TDictionary<Integer, Double>;
  LGranTotalNombres: TDictionary<Integer, string>;
  LGranTotalUnidades: TDictionary<Integer, string>;
  LDictArtTotales: TDictionary<string, Integer>;
  LArtKeys: TArray<string>;
  LTotalPiezas: Integer;
  LHojaIndex: Integer;
  LMonoElaboracion: Boolean;
  LPorcFactor: Double;
  LRec1er, LRecBase: Integer;
  LFactor: Double;
  LKeys: TArray<Integer>;
  LK: Integer;
  LMpDesc, LUnidad: string;
  LCant: Double;
  LPeso1erEmpasteKg, LPeso2doEmpasteKg, LPesoTotalMasaBaseKg: Double;
  LPesoPorcionMasaBaseKg: Double;

  function AcumularIngredientesReceta(ARecId: Integer; const ATitulo: string; AMultiplicador: Double; const AIndent: string = '    '): Double;
  var
    LMpId: Integer;
    LCantRec: Double;
    LMpDescRec, LUnidadRec: string;
    LUnitClean: string;
    LTotalCallKg: Double;
  begin
    Result := 0.0;
    if (ARecId <= 0) or (AMultiplicador <= 0) then Exit;
    if ATitulo <> '' then
      LSb.AppendLine(Format('%s--- [ %s ] (Factor: %.2f) ---', [AIndent, ATitulo, AMultiplicador]));

    LTotalCallKg := 0.0;
    LQry.Close;
    LQry.SQL.Text :=
      'SELECT mp.id, mp.descripcion, pi.unidad, SUM(pi.cantidad_base) AS cant_base ' +
      'FROM ob_recetas_procesos rp ' +
      'JOIN ob_procesos_ingredientes pi ON pi.proceso_id = rp.id ' +
      'JOIN ge_materias_primas mp ON mp.id = pi.id_materia_prima ' +
      'WHERE rp.receta_id = :receta AND pi.tipo_origen = ''MP'' ' +
      'GROUP BY mp.id, mp.descripcion, pi.unidad ' +
      'ORDER BY mp.descripcion ASC';
    LQry.ParamByName('receta').AsInteger := ARecId;
    LQry.Open;

    if LQry.IsEmpty then
    begin
      if ATitulo <> '' then
        LSb.AppendLine(AIndent + '  (Sin materias primas directas registradas)');
    end
    else
    begin
      while not LQry.Eof do
      begin
        LMpId := LQry.FieldByName('id').AsInteger;
        LMpDescRec := LQry.FieldByName('descripcion').AsString;
        LUnidadRec := LQry.FieldByName('unidad').AsString;
        LUnitClean := LowerCase(Trim(LUnidadRec));
        LCantRec := LQry.FieldByName('cant_base').AsFloat * AMultiplicador;

        if (LUnitClean = 'g') or (LUnitClean = 'gr') or (LUnitClean = 'gramos') then
        begin
          LSb.AppendLine(Format('%s  - %-40s : %8.3f kg   (%9.1f g)', [AIndent, LMpDescRec, LCantRec / 1000.0, LCantRec]));
          LTotalCallKg := LTotalCallKg + (LCantRec / 1000.0);
        end
        else if (LUnitClean = 'kg') or (LUnitClean = 'kilos') then
        begin
          LSb.AppendLine(Format('%s  - %-40s : %8.3f kg   (%9.1f g)', [AIndent, LMpDescRec, LCantRec, LCantRec * 1000.0]));
          LTotalCallKg := LTotalCallKg + LCantRec;
        end
        else
        begin
          LSb.AppendLine(Format('%s  - %-40s : %8.2f %-5s', [AIndent, LMpDescRec, LCantRec, LUnidadRec]));
          LTotalCallKg := LTotalCallKg + LCantRec;
        end;

        if LGranTotalDict.ContainsKey(LMpId) then
          LGranTotalDict[LMpId] := LGranTotalDict[LMpId] + LCantRec
        else
        begin
          LGranTotalDict.Add(LMpId, LCantRec);
          LGranTotalNombres.Add(LMpId, LMpDescRec);
          LGranTotalUnidades.Add(LMpId, LUnidadRec);
        end;

        LQry.Next;
      end;
    end;
    Result := LTotalCallKg;
  end;

  procedure ImprimirTablaResumenUnidades(const ATituloSeccion: string);
  var
    LNom: string;
  begin
    LSb.AppendLine(ATituloSeccion);
    LSb.AppendLine('----------------------------------------------------------------------------------------');
    LSb.AppendLine('  Artículo / Formato Terminado                                          Total Unidades  ');
    LSb.AppendLine('  ------------------------------------------------------------------   ---------------  ');
    for LNom in LArtKeys do
    begin
      LSb.AppendLine(Format('  %-66s   %11d uds', [LNom, LDictArtTotales[LNom]]));
    end;
    LSb.AppendLine('  ------------------------------------------------------------------   ---------------  ');
    LSb.AppendLine(Format('  TOTAL ESTIMADO DE PIEZAS TERMINADAS:                                 %11d uds', [LTotalPiezas]));
    LSb.AppendLine('----------------------------------------------------------------------------------------');
  end;

begin
  LSb := TStringBuilder.Create;
  LQry := TFDQuery.Create(nil);
  LGranTotalDict := TDictionary<Integer, Double>.Create;
  LGranTotalNombres := TDictionary<Integer, string>.Create;
  LGranTotalUnidades := TDictionary<Integer, string>.Create;
  LDictArtTotales := TDictionary<string, Integer>.Create;
  try
    LQry.Connection := dmgMain.dbConn;

    LObrStr := cbbObrador.Text;
    if LObrStr = '' then LObrStr := 'Obrador Central';

    // Pre-calcular resumen de unidades totales agrupadas por artículo / formato final
    LTotalPiezas := 0;
    if FPlan.EsMasaBase then
    begin
      for i := 0 to FPlan.Masas.Count - 1 do
      begin
        LMasa := FPlan.Masas[i];
        for j := 0 to LMasa.Sabores.Count - 1 do
        begin
          LSabor := LMasa.Sabores[j];
          var LDescArt := Trim(LSabor.ArticuloDesc);
          if LDescArt = '' then
            LDescArt := 'Formato / Elaboración sin asignar';
          if LDictArtTotales.ContainsKey(LDescArt) then
            LDictArtTotales[LDescArt] := LDictArtTotales[LDescArt] + LSabor.UnidadesXL
          else
            LDictArtTotales.Add(LDescArt, LSabor.UnidadesXL);
          Inc(LTotalPiezas, LSabor.UnidadesXL);
        end;
      end;
    end
    else
    begin
      var LDescArt := Trim(FPlan.RecetaPrincipalDesc);
      if LDescArt = '' then LDescArt := 'Elaboración única';
      LDictArtTotales.Add(LDescArt, FPlan.CantidadMasasPrincipal);
      LTotalPiezas := FPlan.CantidadMasasPrincipal;
    end;

    LArtKeys := LDictArtTotales.Keys.ToArray;
    TArray.Sort<string>(LArtKeys, TComparer<string>.Construct(
      function(const L, R: string): Integer
      begin
        Result := CompareText(L, R);
      end));

    LSb.AppendLine('========================================================================================');
    LSb.AppendLine('                 HOJA DE PRODUCCIÓN Y PLANIFICACIÓN DE FABRICACIÓN                     ');
    LSb.AppendLine('                           RAÚL ASENCIO PASTELERÍAS                                     ');
    LSb.AppendLine('========================================================================================');
    LSb.AppendLine(Format(' Fecha Planificación: %s          Obrador: %s', [FormatDateTime('dd/MM/yyyy', dtpFechaLote.Date), LObrStr]));
    LSb.AppendLine(Format(' Usuario: %s', [dmgMain.CurrentUserId]));
    LSb.AppendLine('----------------------------------------------------------------------------------------');
    LSb.AppendLine('');

    LSb.AppendLine('1. RESUMEN DE ELABORACIONES Y REPARTO DE MASAS');
    LSb.AppendLine('========================================================================================');

    var LPesoMMRef := FPlan.MasaMadrePorMasaKg;
    if LPesoMMRef <= 0.001 then
      LPesoMMRef := ObtenerPesoTotalRecetaKg(FPlan.RecetaMasaMadreId);
    if LPesoMMRef <= 0.001 then
      LPesoMMRef := 10.005;

    var LFactorMM := FPlan.MasaMadreTotalKg / LPesoMMRef;

    if FPlan.EsMasaBase then
    begin
      LSb.AppendLine(Format(' • MASA MADRE (Receta %d) (Lote: %s): %.2f kg totales a elaborar',
        [FPlan.RecetaMasaMadreId, FPlan.LoteMasaMadreCodigo, FPlan.MasaMadreTotalKg]));
      LSb.AppendLine(Format('     - Consumo para hoy (%d masas base x %.2f kg):       %8.2f kg',
        [FPlan.CantidadMasasPrincipal, LPesoMMRef, FPlan.MasaMadreHoyKg]));
      if FPlan.MasasBaseManana > 0 then
        LSb.AppendLine(Format('     - Reserva para mañana (%d masas x 2,0 kg):        %8.2f kg',
          [FPlan.MasasBaseManana, FPlan.MasaMadreExtraKg]));

      LSb.AppendLine('');
      LSb.AppendLine(' • 1ER EMPASTE (Receta 22) - Órdenes individuales para pesadas reales:');
      for i := 0 to FPlan.Masas.Count - 1 do
      begin
        LMasa := FPlan.Masas[i];
        var LPorcMasa := Round(LMasa.Multiplicador * 100);
        var LPorcText := IfThen(LPorcMasa = 100, '1 masa (93.0 kg)', Format('Porción %d%% (%.1f kg)', [LPorcMasa, LMasa.Multiplicador * 93.0]));
        LSb.AppendLine(Format('     - 1er Empaste %s (Lote: %s): %s', [LMasa.NombreMasa, LMasa.Lote1erEmpasteCodigo, LPorcText]));
      end;
      LSb.AppendLine('');
      LSb.AppendLine(Format(' • 2º EMPASTE - MASA BASE (Receta 5) - %d masas base:', [FPlan.Masas.Count]));
      for i := 0 to FPlan.Masas.Count - 1 do
      begin
        LMasa := FPlan.Masas[i];
        var LPorcMasa := Round(LMasa.Multiplicador * 100);
        var LTagPorc := IfThen(LPorcMasa = 100, '', Format(' [Porción %d%%]', [LPorcMasa]));
        LSb.AppendLine(Format('     - 2º Empaste %s%s (Lote Base: %s) [Origen 1er Empaste: %s]',
          [LMasa.NombreMasa, LTagPorc, LMasa.LoteCodigo, LMasa.Lote1erEmpasteCodigo]));
      end;
      LSb.AppendLine('');

      LTotalUds := 0;
      for i := 0 to FPlan.Masas.Count - 1 do
      begin
        LMasa := FPlan.Masas[i];
        LSb.AppendLine(Format('   [+] %s (Lote Base: %s):', [LMasa.NombreMasa, LMasa.LoteCodigo]));
        for j := 0 to LMasa.Sabores.Count - 1 do
        begin
          LSabor := LMasa.Sabores[j];
          LSb.AppendLine(Format('       - %-32s  %3.0f%%   Lote: %-12s   Est: %4d uds',
            [LSabor.ArticuloDesc, LSabor.Porcentaje, LSabor.LoteCodigo, LSabor.UnidadesXL]));
          Inc(LTotalUds, LSabor.UnidadesXL);
        end;
      end;
      LSb.AppendLine('');
      LSb.AppendLine(Format(' Total estimado de piezas terminadas: %d unidades (En estado PENDIENTE en Stock Envasado)', [LTotalUds]));
      LSb.AppendLine('');

      // Resumen de unidades totales por artículo / formato en Sección 1
      ImprimirTablaResumenUnidades(' RESUMEN DE UNIDADES TOTALES POR ARTÍCULO / FORMATO:');
    end
    else
    begin
      LSb.AppendLine(Format(' • Receta: %s | Cantidad: %d', [FPlan.RecetaPrincipalDesc, FPlan.CantidadMasasPrincipal]));
      if FPlan.EsMasaMadre then
      begin
        LSb.AppendLine(Format(' • MASA MADRE (Receta %d) (Lote: %s): %.2f kg totales a elaborar',
          [FPlan.RecetaPrincipalId, FPlan.LoteMasaMadreCodigo, FPlan.MasaMadreTotalKg]));
        LSb.AppendLine(Format('     - Masa Madre para hoy (%d masas x %.2f kg):       %8.2f kg',
          [FPlan.CantidadMasasPrincipal, LPesoMMRef, FPlan.MasaMadreHoyKg]));
        if FPlan.MasasBaseManana > 0 then
          LSb.AppendLine(Format('     - Reserva para mañana (%d masas x 2,0 kg):        %8.2f kg',
            [FPlan.MasasBaseManana, FPlan.MasaMadreExtraKg]))
        else
          LSb.AppendLine(Format('     - Extra directa añadida:                          %8.2f kg', [FPlan.MasaMadreExtraKg]));
        LSb.AppendLine(Format('     - Total Masa Madre a elaborar:                    %8.2f kg', [FPlan.MasaMadreTotalKg]));
      end;
      LSb.AppendLine('');
      ImprimirTablaResumenUnidades(' RESUMEN DE UNIDADES TOTALES:');
    end;

    // Salto de página para la sección de Masa Madre
    LSb.AppendLine('');
    LSb.AppendLine('========================================================================================');
    LSb.AppendLine('                    >>> CORTE DE PÁGINA (SIGUIENTE HOJA) <<<');
    LSb.AppendLine('========================================================================================');
    LSb.AppendLine('');

    LSb.AppendLine('2. RECETA Y MATERIAS PRIMAS DE LA MASA MADRE');
    LSb.AppendLine('========================================================================================');

    if FPlan.EsMasaBase or FPlan.EsMasaMadre then
    begin
      var LRecMMId := FPlan.RecetaMasaMadreId;
      if LRecMMId <= 0 then LRecMMId := 3;
      var LLoteMM := FPlan.LoteMasaMadreCodigo;
      if LLoteMM = '' then LLoteMM := 'S/Lote';

      LSb.AppendLine(Format(' • Receta: MASA MADRE (Receta %d) | Lote: %s', [LRecMMId, LLoteMM]));
      LSb.AppendLine(Format(' • Total a Elaborar: %.2f kg (Consumo hoy: %.2f kg | Factor de Escala: %.2f)',
        [FPlan.MasaMadreTotalKg, FPlan.MasaMadreHoyKg, LFactorMM]));
      LSb.AppendLine('');

      LSb.AppendLine('  A) Materias Primas Totales de Masa Madre:');
      AcumularIngredientesReceta(LRecMMId, '', LFactorMM, '    ');
      LSb.AppendLine('');

      LSb.AppendLine('  B) Desglose de Procesos / Refrescos de Masa Madre:');
      LQry.Close;
      LQry.SQL.Text :=
        'SELECT rp.id AS proc_id, rp.nombre AS nombre_proceso, rp.duracion_minutos, rp.temperatura, ' +
        '       pi.id_materia_prima, COALESCE(mp.descripcion, a.descripcion, ''Semilla / Masa Madre'') AS ing_desc, ' +
        '       pi.cantidad_base, pi.unidad ' +
        'FROM ob_recetas_procesos rp ' +
        'LEFT JOIN ob_procesos_ingredientes pi ON pi.proceso_id = rp.id ' +
        'LEFT JOIN ge_materias_primas mp ON mp.id = pi.id_materia_prima ' +
        'LEFT JOIN ge_articulos a ON a.id = pi.id_materia_prima ' +
        'WHERE rp.receta_id = :receta_id ' +
        'ORDER BY rp.orden ASC, rp.id ASC, pi.id ASC';
      LQry.ParamByName('receta_id').AsInteger := LRecMMId;
      LQry.Open;

      var LLastProcId := -1;
      var LSubtotalProc := 0.0;
      while not LQry.Eof do
      begin
        var LCurProcId := LQry.FieldByName('proc_id').AsInteger;
        if LCurProcId <> LLastProcId then
        begin
          if LLastProcId <> -1 then
          begin
            LSb.AppendLine(Format('        > Subtotal Proceso                     : %8.3f kg   (%8.1f g)', [LSubtotalProc / 1000.0, LSubtotalProc]));
            LSb.AppendLine('');
          end;
          LLastProcId := LCurProcId;
          LSubtotalProc := 0.0;
          LSb.AppendLine(Format('    * %s (Duración: %d min, Temp: %s°C):',
            [LQry.FieldByName('nombre_proceso').AsString,
             LQry.FieldByName('duracion_minutos').AsInteger,
             LQry.FieldByName('temperatura').AsString]));
        end;

        var LCantG := LQry.FieldByName('cantidad_base').AsFloat * LFactorMM;
        LSubtotalProc := LSubtotalProc + LCantG;
        LSb.AppendLine(Format('        - %-36s : %8.3f kg   (%8.1f g)',
          [LQry.FieldByName('ing_desc').AsString, LCantG / 1000.0, LCantG]));

        LQry.Next;
      end;
      if LLastProcId <> -1 then
      begin
        LSb.AppendLine(Format('        > Subtotal Proceso                     : %8.3f kg   (%8.1f g)', [LSubtotalProc / 1000.0, LSubtotalProc]));
        LSb.AppendLine('');
      end;
    end
    else
    begin
      LSb.AppendLine('  (Esta elaboración no requiere subreceta de masa madre)');
      LSb.AppendLine('');
    end;

    // Salto de página para la primera masa
    LSb.AppendLine('');
    LSb.AppendLine('========================================================================================');
    LSb.AppendLine('                    >>> CORTE DE PÁGINA (SIGUIENTE HOJA) <<<');
    LSb.AppendLine('========================================================================================');
    LSb.AppendLine('');

    // ========================================================================
    // SECCIÓN 3: HOJAS DE PESADO - PRIMER EMPASTE (SEPARADO, POR MASA INDIVIDUAL)
    // ========================================================================
    LSb.AppendLine('3. HOJAS DE PESADO DE MATERIAS PRIMAS - 1ER EMPASTE (PESADAS INDIVIDUALES)');
    LSb.AppendLine('========================================================================================');

    if FPlan.EsMasaBase then
    begin
      LRec1er := FPlan.Receta1erEmpasteId;
      if LRec1er <= 0 then LRec1er := 22;

      for i := 0 to FPlan.Masas.Count - 1 do
      begin
        LMasa := FPlan.Masas[i];
        if i > 0 then
        begin
          LSb.AppendLine('');
          LSb.AppendLine('========================================================================================');
          LSb.AppendLine('                    >>> CORTE DE PÁGINA (SIGUIENTE HOJA) <<<');
          LSb.AppendLine('========================================================================================');
          LSb.AppendLine('');
        end;

        var LPorcMasa1E := Round(LMasa.Multiplicador * 100);
        var LPorcText1E := IfThen(LPorcMasa1E = 100, '1 Masa Completa (93.0 kg)', Format('Porción %d%% (%.1f kg)', [LPorcMasa1E, LMasa.Multiplicador * 93.0]));
        LSb.AppendLine('========================================================================================');
        LSb.AppendLine(Format('      HOJA DE PESADO DE MATERIAS PRIMAS - 1ER EMPASTE: %s ', [UpperCase(LMasa.NombreMasa)]));
        LSb.AppendLine(Format('      Obrador: %s | Fecha: %s', [LObrStr, FormatDateTime('dd/MM/yyyy', dtpFechaLote.Date)]));
        LSb.AppendLine('========================================================================================');
        LSb.AppendLine(Format('>>> 1ER EMPASTE %s  |  LOTE 1ER EMPASTE: %s  (Receta %d)',
          [LMasa.NombreMasa, LMasa.Lote1erEmpasteCodigo, LRec1er]));
        LSb.AppendLine('----------------------------------------------------------------------------------------');
        LSb.AppendLine(Format('  Materias Primas Teóricas a Pesar para %s:', [LPorcText1E]));
        LPeso1erEmpasteKg := AcumularIngredientesReceta(LRec1er, '', LMasa.Multiplicador, '    ') + (LPesoMMRef * LMasa.Multiplicador);
        LSb.AppendLine(Format('    * Masa Madre madura requerida (Lote MM: %s): %8.3f kg   (%8.1f g)',
          [FPlan.LoteMasaMadreCodigo, LPesoMMRef * LMasa.Multiplicador, LPesoMMRef * LMasa.Multiplicador * 1000.0]));
        LSb.AppendLine('');
        LSb.AppendLine(Format('  [TOTAL TEÓRICO 1ER EMPASTE %s] : %6.2f kg', [LMasa.NombreMasa, LPeso1erEmpasteKg]));
        LSb.AppendLine('');
        LSb.AppendLine('========================================================================================');
        LSb.AppendLine('  REGISTRO DE PESADA Y AMASADO REAL DE PLANTA (1ER EMPASTE):');
        LSb.AppendLine('  Pesado por: ___________________  Hora Inicio: _____  Hora Fin: _____  Temp. Masa: _____ °C');
        LSb.AppendLine('  Validación Visual: [ ] OK        Observaciones: _____________________________________');
        LSb.AppendLine('========================================================================================');
        LSb.AppendLine('');
      end;
    end
    else if not FPlan.EsMasaMadre then
    begin
      LSb.AppendLine(Format('>>> %s (Cantidad: %d)', [FPlan.RecetaPrincipalDesc, FPlan.CantidadMasasPrincipal]));
      AcumularIngredientesReceta(FPlan.RecetaPrincipalId, '', FPlan.CantidadMasasPrincipal, '    ');
      LSb.AppendLine('');
    end;

    // ========================================================================
    // SECCIÓN 4: HOJAS DE PESADO - SEGUNDO EMPASTE E INCLUSIONES (SEPARADO)
    // ========================================================================
    if FPlan.EsMasaBase then
    begin
      LSb.AppendLine('');
      LSb.AppendLine('========================================================================================');
      LSb.AppendLine('                    >>> CORTE DE PÁGINA (SIGUIENTE HOJA) <<<');
      LSb.AppendLine('========================================================================================');
      LSb.AppendLine('');

      LSb.AppendLine('4. HOJAS DE PESADO DE MATERIAS PRIMAS - 2º EMPASTE E INCLUSIONES (POR MASA)');
      LSb.AppendLine('========================================================================================');

      LRecBase := FPlan.RecetaPrincipalId;
      if LRecBase <= 0 then LRecBase := 5;

      for i := 0 to FPlan.Masas.Count - 1 do
      begin
        LMasa := FPlan.Masas[i];
        LMonoElaboracion := (LMasa.Sabores.Count <= 1) or
          ((LMasa.Sabores.Count > 0) and (LMasa.Sabores[0].Porcentaje >= 99.99));

        if i > 0 then
        begin
          LSb.AppendLine('');
          LSb.AppendLine('========================================================================================');
          LSb.AppendLine('                    >>> CORTE DE PÁGINA (SIGUIENTE HOJA) <<<');
          LSb.AppendLine('========================================================================================');
          LSb.AppendLine('');
        end;

        LSb.AppendLine('========================================================================================');
        LSb.AppendLine(Format('      HOJA DE PESADO DE MATERIAS PRIMAS - 2º EMPASTE: %s ', [UpperCase(LMasa.NombreMasa)]));
        LSb.AppendLine(Format('      Obrador: %s | Fecha: %s', [LObrStr, FormatDateTime('dd/MM/yyyy', dtpFechaLote.Date)]));
        LSb.AppendLine('========================================================================================');
        LSb.AppendLine(Format('>>> 2º EMPASTE %s  |  LOTE 2º EMPASTE: %s  |  ORIGEN 1ER EMPASTE: %s',
          [LMasa.NombreMasa, LMasa.LoteCodigo, LMasa.Lote1erEmpasteCodigo]));
        LSb.AppendLine('----------------------------------------------------------------------------------------');

        var LPorcMasa2E := Round(LMasa.Multiplicador * 100);
        var LPorcText2E := IfThen(LPorcMasa2E = 100, '1 Masa Completa', Format('Porción %d%%', [LPorcMasa2E]));

        // [A] Materias Primas del 2º Empaste Masa Base
        LSb.AppendLine(Format('    [A] 2º EMPASTE - MASA BASE (Receta %d) - Materias Primas para %s:', [LRecBase, LPorcText2E]));
        LPeso2doEmpasteKg := AcumularIngredientesReceta(LRecBase, '', LMasa.Multiplicador, '        ');
        LSb.AppendLine('');
        LSb.AppendLine(Format('        [PESO MASA BASE 2º EMPASTE] : %6.2f kg (Total con 1er Empaste: %.2f kg)',
          [LPeso2doEmpasteKg, (93.0 * LMasa.Multiplicador) + LPeso2doEmpasteKg]));
        LSb.AppendLine('');

        // [B] Inclusiones / Sabores
        if LMonoElaboracion then
        begin
          LSabor := nil;
          if LMasa.Sabores.Count > 0 then
            LSabor := LMasa.Sabores[0];
          if LSabor <> nil then
          begin
            LSb.AppendLine(Format('    [B] INCLUSIONES / VARIEGATO: %s (Lote Sabor: %s)', [LSabor.ArticuloDesc, LSabor.LoteCodigo]));
            LSb.AppendLine(Format('        Artículo Final: %s ➔ Unidades Estimadas: %d uds', [LSabor.ArticuloDesc, LSabor.UnidadesXL]));
            LSb.AppendLine('');
            if LSabor.RecetaId > 0 then
              AcumularIngredientesReceta(LSabor.RecetaId, '', LMasa.Multiplicador, '        ')
            else
              LSb.AppendLine('        (Sin materias primas directas registradas)');
            LSb.AppendLine('');
          end;
        end
        else
        begin
          LSb.AppendLine('    [B] REPARTO DE MASA BASE E INCLUSIONES POR PORCIONES:');
          for j := 0 to LMasa.Sabores.Count - 1 do
          begin
            LSabor := LMasa.Sabores[j];
            LPorcFactor := LSabor.Porcentaje / 100.0;
            LPesoPorcionMasaBaseKg := ((93.0 * LMasa.Multiplicador) + LPeso2doEmpasteKg) * LPorcFactor;

            LSb.AppendLine(Format('      • PORCIÓN %d: %s (%.1f%%) | Lote Sabor: %s',
              [j + 1, LSabor.ArticuloDesc, LSabor.Porcentaje, LSabor.LoteCodigo]));
            LSb.AppendLine(Format('        Masa Base a separar: %8.3f kg ➔ Unidades Estimadas: %d uds',
              [LPesoPorcionMasaBaseKg, LSabor.UnidadesXL]));
            if LSabor.RecetaId > 0 then
              AcumularIngredientesReceta(LSabor.RecetaId, '', LMasa.Multiplicador * LPorcFactor, '        ')
            else
              LSb.AppendLine('        (Sin materias primas directas registradas)');
            LSb.AppendLine('');
          end;
        end;

        LSb.AppendLine('========================================================================================');
        LSb.AppendLine('  REGISTRO DE PESADA Y AMASADO REAL DE PLANTA (2º EMPASTE):');
        LSb.AppendLine('  Pesado por: ___________________  Hora Inicio: _____  Hora Fin: _____  Temp. Masa: _____ °C');
        LSb.AppendLine('  Validación Visual: [ ] OK        Observaciones: _____________________________________');
        LSb.AppendLine('========================================================================================');
        LSb.AppendLine('');
      end;
    end;

    // Salto de página para el consolidado final
    LSb.AppendLine('');
    LSb.AppendLine('========================================================================================');
    LSb.AppendLine('                    >>> CORTE DE PÁGINA (SIGUIENTE HOJA) <<<');
    LSb.AppendLine('========================================================================================');
    LSb.AppendLine('');

    LSb.AppendLine('========================================================================================');
    LSb.AppendLine('5. CONSOLIDADO TOTAL DE MATERIAS PRIMAS DEL DÍA (A RETIRAR DEL ALMACÉN)');
    LSb.AppendLine(Format('Obrador: %s | Fecha Planificación: %s', [LObrStr, FormatDateTime('dd/MM/yyyy', dtpFechaLote.Date)]));
    LSb.AppendLine('========================================================================================');

    LKeys := LGranTotalDict.Keys.ToArray;
    TArray.Sort<Integer>(LKeys, TComparer<Integer>.Construct(
      function(const L, R: Integer): Integer
      begin
        Result := CompareText(LGranTotalNombres[L], LGranTotalNombres[R]);
      end));

    for LK in LKeys do
    begin
      LMpDesc := LGranTotalNombres[LK];
      LCant := LGranTotalDict[LK];
      LUnidad := LowerCase(Trim(LGranTotalUnidades[LK]));

      if (LUnidad = 'g') or (LUnidad = 'gr') or (LUnidad = 'gramos') then
        LSb.AppendLine(Format('  * %-45s : %10.3f kg   (%11.1f g)', [LMpDesc, LCant / 1000.0, LCant]))
      else if (LUnidad = 'kg') or (LUnidad = 'kilos') then
        LSb.AppendLine(Format('  * %-45s : %10.3f kg   (%11.1f g)', [LMpDesc, LCant, LCant * 1000.0]))
      else
        LSb.AppendLine(Format('  * %-45s : %10.2f %-5s', [LMpDesc, LCant, LUnidad]));
    end;

    LSb.AppendLine('');
    LSb.AppendLine('========================================================================================');
    LSb.AppendLine('6. RESUMEN FINAL CONSOLIDADO DE UNIDADES A FABRICAR POR ARTÍCULO Y FORMATO');
    LSb.AppendLine('========================================================================================');
    ImprimirTablaResumenUnidades('UNIDADES TOTALES A ENVASAR / PRODUCIR POR CADA FORMATO:');

    LSb.AppendLine('');
    LSb.AppendLine('========================================================================================');
    LSb.AppendLine('  * Trazabilidad: Lotes correlativos creados para cada masa y sabor.');
    LSb.AppendLine('  * Stock: Registros creados en ge_stock_envasado con estado PENDIENTE.');
    LSb.AppendLine('========================================================================================');

    Result := LSb.ToString;
  finally
    LDictArtTotales.Free;
    LGranTotalDict.Free;
    LGranTotalNombres.Free;
    LGranTotalUnidades.Free;
    LQry.Free;
    LSb.Free;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnVerInformeClick(Sender: TObject);
var
  LTexto: string;
begin
  LTexto := GenerarTextoInformeProduccion;
  TfrmInformePlanificacionProduccion.MostrarInforme(Self, LTexto, dtpFechaLote.Date, cbbObrador.Text);
end;

procedure TfrmPlanificacionMasasProduccion.btnVerOrdenesFabricacionClick(Sender: TObject);
begin
  if Assigned(frmMain) then
    frmMain.btnOrdenesFabricacionClick(nil)
  else
  begin
    var LFrm := TfrmOrdenesFabricacion.Create(Self);
    try
      LFrm.ShowModal;
    finally
      LFrm.Free;
    end;
  end;
end;

function TfrmPlanificacionMasasProduccion.ObtenerSemillaMasaMadreKg(ARecetaId: Integer): Double;
var
  LQry: TFDQuery;
  LCant: Double;
  LUnidad: string;
begin
  Result := 1.390; // Proporción canónica oficial: 1390g (1.390 kg) por masa de 10 kg
  if ARecetaId <= 0 then ARecetaId := 3;
  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;
    LQry.SQL.Text :=
      'SELECT pi.cantidad_base, pi.unidad ' +
      'FROM ob_recetas_procesos rp ' +
      'JOIN ob_procesos_ingredientes pi ON pi.proceso_id = rp.id ' +
      'LEFT JOIN ge_materias_primas mp ON pi.id_materia_prima = mp.id ' +
      'LEFT JOIN ge_articulos a ON pi.id_materia_prima = a.id ' +
      'WHERE rp.receta_id = :receta_id ' +
      '  AND (pi.id_materia_prima = 3084 OR UPPER(COALESCE(mp.descripcion, a.descripcion)) LIKE ''%MASA MADRE%'') ' +
      'ORDER BY rp.id ASC, pi.id ASC ' +
      'LIMIT 1';
    LQry.ParamByName('receta_id').AsInteger := ARecetaId;
    LQry.Open;
    if not LQry.IsEmpty then
    begin
      LCant := LQry.FieldByName('cantidad_base').AsFloat;
      LUnidad := LowerCase(Trim(LQry.FieldByName('unidad').AsString));
      if (LUnidad = 'g') or (LUnidad = 'gr') or (LUnidad = 'gramos') or (LCant > 50.0) then
        Result := LCant / 1000.0
      else
        Result := LCant;
    end;
  except
    Result := 1.390;
  end;
  LQry.Free;
end;

// =============================================================================
// MÉTODOS DEL MODO CÁLCULO POR PEDIDOS PENDIENTES (DÉFICIT / HEREDADOS)
// =============================================================================

procedure TfrmPlanificacionMasasProduccion.ConfigurarEstructuraTablas;
begin
  mtRecetas.Close;
  mtRecetas.FieldDefs.Clear;
  mtRecetas.FieldDefs.Add('receta_id', ftInteger);
  mtRecetas.FieldDefs.Add('receta_nombre', ftString, 120);
  mtRecetas.FieldDefs.Add('cant_articulos', ftInteger);
  mtRecetas.FieldDefs.Add('total_deficit_uds', ftFloat);
  mtRecetas.FieldDefs.Add('masas_exactas', ftFloat);
  mtRecetas.FieldDefs.Add('masas_ajustadas', ftFloat);
  mtRecetas.FieldDefs.Add('total_masas_receta', ftFloat);
  mtRecetas.FieldDefs.Add('masas_texto', ftString, 40);
  mtRecetas.FieldDefs.Add('proxima_entrega', ftDateTime);
  mtRecetas.FieldDefs.Add('dias_vida', ftInteger);
  mtRecetas.FieldDefs.Add('reduccion_cad_pct', ftFloat);
  mtRecetas.FieldDefs.Add('fecha_planificada', ftDateTime);
  mtRecetas.FieldDefs.Add('ocupacion_obrador', ftString, 40);
  mtRecetas.FieldDefs.Add('estado_lote', ftString, 35);
  mtRecetas.CreateDataSet;
  TFloatField(mtRecetas.FieldByName('total_deficit_uds')).DisplayFormat := '#,##0';
  TFloatField(mtRecetas.FieldByName('masas_exactas')).DisplayFormat := '0.00';
  TFloatField(mtRecetas.FieldByName('reduccion_cad_pct')).DisplayFormat := '0.0"%"';
  TDateTimeField(mtRecetas.FieldByName('proxima_entrega')).DisplayFormat := 'dd/mm/yyyy';
  TDateTimeField(mtRecetas.FieldByName('fecha_planificada')).DisplayFormat := 'dd/mm/yyyy';

  mtArticulos.Close;
  mtArticulos.FieldDefs.Clear;
  mtArticulos.FieldDefs.Add('articulo_id', ftInteger);
  mtArticulos.FieldDefs.Add('articulo_nombre', ftString, 120);
  mtArticulos.FieldDefs.Add('receta_id', ftInteger);
  mtArticulos.FieldDefs.Add('receta_nombre', ftString, 120);
  mtArticulos.FieldDefs.Add('unidades_pendientes', ftFloat);
  mtArticulos.FieldDefs.Add('stock_disponible', ftFloat);
  mtArticulos.FieldDefs.Add('en_ordenes_prod', ftFloat);
  mtArticulos.FieldDefs.Add('deficit_unidades', ftFloat);
  mtArticulos.FieldDefs.Add('unidades_por_masa', ftFloat);
  mtArticulos.FieldDefs.Add('masas_necesarias', ftFloat);
  mtArticulos.FieldDefs.Add('proxima_entrega', ftDateTime);
  mtArticulos.FieldDefs.Add('dias_vida', ftInteger);
  mtArticulos.FieldDefs.Add('fecha_caducidad_est', ftDateTime);
  mtArticulos.FieldDefs.Add('lote_generado', ftString, 50);
  mtArticulos.CreateDataSet;
  TFloatField(mtArticulos.FieldByName('unidades_pendientes')).DisplayFormat := '#,##0';
  TFloatField(mtArticulos.FieldByName('stock_disponible')).DisplayFormat := '#,##0';
  TFloatField(mtArticulos.FieldByName('en_ordenes_prod')).DisplayFormat := '#,##0';
  TFloatField(mtArticulos.FieldByName('deficit_unidades')).DisplayFormat := '#,##0';
  TFloatField(mtArticulos.FieldByName('masas_necesarias')).DisplayFormat := '0.00';
  TDateTimeField(mtArticulos.FieldByName('proxima_entrega')).DisplayFormat := 'dd/mm/yyyy';
  TDateTimeField(mtArticulos.FieldByName('fecha_caducidad_est')).DisplayFormat := 'dd/mm/yyyy';
end;

procedure TfrmPlanificacionMasasProduccion.SetupGrids;
begin
  dbgRecetas.Columns.Clear;
  with dbgRecetas.Columns.Add do
  begin
    FieldName := 'fecha_planificada';
    Title.Caption := 'Fecha Fab. Óptima';
    Width := 110;
    Alignment := taCenter;
  end;
  with dbgRecetas.Columns.Add do
  begin
    FieldName := 'receta_nombre';
    Title.Caption := 'Receta';
    Width := 230;
  end;
  with dbgRecetas.Columns.Add do
  begin
    FieldName := 'cant_articulos';
    Title.Caption := 'Artículos';
    Width := 68;
    Alignment := taCenter;
  end;
  with dbgRecetas.Columns.Add do
  begin
    FieldName := 'total_deficit_uds';
    Title.Caption := 'Déficit (Uds)';
    Width := 90;
    Alignment := taRightJustify;
  end;
  with dbgRecetas.Columns.Add do
  begin
    FieldName := 'masas_exactas';
    Title.Caption := 'Masas Calc.';
    Width := 85;
    Alignment := taRightJustify;
  end;
  with dbgRecetas.Columns.Add do
  begin
    FieldName := 'masas_texto';
    Title.Caption := 'Masas Día (+1/4)';
    Width := 130;
  end;
  with dbgRecetas.Columns.Add do
  begin
    FieldName := 'proxima_entrega';
    Title.Caption := 'Próx. Entrega';
    Width := 95;
    Alignment := taCenter;
  end;
  with dbgRecetas.Columns.Add do
  begin
    FieldName := 'dias_vida';
    Title.Caption := 'Vida (Días)';
    Width := 72;
    Alignment := taCenter;
  end;
  with dbgRecetas.Columns.Add do
  begin
    FieldName := 'reduccion_cad_pct';
    Title.Caption := 'Reducción Cad.';
    Width := 92;
    Alignment := taRightJustify;
  end;
  with dbgRecetas.Columns.Add do
  begin
    FieldName := 'ocupacion_obrador';
    Title.Caption := 'Capacidad Obrador';
    Width := 125;
    Alignment := taCenter;
  end;
  with dbgRecetas.Columns.Add do
  begin
    FieldName := 'estado_lote';
    Title.Caption := 'Estado Plan / Lote';
    Width := 155;
  end;

  dbgArticulos.Columns.Clear;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'articulo_id';
    Title.Caption := 'ID';
    Width := 50;
  end;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'articulo_nombre';
    Title.Caption := 'Artículo';
    Width := 300;
  end;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'unidades_pendientes';
    Title.Caption := 'Pend. Pedidos';
    Width := 95;
    Alignment := taRightJustify;
  end;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'stock_disponible';
    Title.Caption := 'Stock Disp.';
    Width := 85;
    Alignment := taRightJustify;
  end;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'en_ordenes_prod';
    Title.Caption := 'En Ord. Prod.';
    Width := 88;
    Alignment := taRightJustify;
  end;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'deficit_unidades';
    Title.Caption := 'Déficit';
    Width := 80;
    Alignment := taRightJustify;
  end;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'unidades_por_masa';
    Title.Caption := 'Rendim./Masa';
    Width := 95;
    Alignment := taRightJustify;
  end;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'masas_necesarias';
    Title.Caption := 'Aporte Masa';
    Width := 90;
    Alignment := taRightJustify;
  end;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'proxima_entrega';
    Title.Caption := 'Próx. Entrega';
    Width := 95;
    Alignment := taCenter;
  end;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'dias_vida';
    Title.Caption := 'Vida (Días)';
    Width := 75;
    Alignment := taCenter;
  end;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'fecha_caducidad_est';
    Title.Caption := 'Caducidad Est.';
    Width := 95;
    Alignment := taCenter;
  end;
  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'lote_generado';
    Title.Caption := 'Lote Creado';
    Width := 140;
  end;
end;

function TfrmPlanificacionMasasProduccion.AjustarMasasACuartos(AMasas: Double): Double;
begin
  if AMasas <= 0.0 then
    Result := 0.0
  else
    Result := Ceil(AMasas * 4.0) / 4.0;
end;

function TfrmPlanificacionMasasProduccion.FormatearMasasCuartos(AMasas: Double): string;
var
  LEntero: Integer;
  LFrac: Double;
begin
  if AMasas <= 0.0 then
    Exit('0 masas');

  LEntero := Trunc(AMasas);
  LFrac := AMasas - LEntero;

  if SameValue(LFrac, 0.0, 0.01) then
    Result := Format('%d masas', [LEntero])
  else if SameValue(LFrac, 0.25, 0.01) then
    if LEntero = 0 then Result := '1/4 masa (0.25)' else Result := Format('%d y 1/4 masas (%.2f)', [LEntero, AMasas])
  else if SameValue(LFrac, 0.50, 0.01) then
    if LEntero = 0 then Result := '1/2 masa (0.50)' else Result := Format('%d y 1/2 masas (%.2f)', [LEntero, AMasas])
  else if SameValue(LFrac, 0.75, 0.01) then
    if LEntero = 0 then Result := '3/4 masas (0.75)' else Result := Format('%d y 3/4 masas (%.2f)', [LEntero, AMasas])
  else
    Result := Format('%.2f masas', [AMasas]);
end;

procedure TfrmPlanificacionMasasProduccion.CargarDatosPlanificacion;
type
  TRecetaPlanInfo = record
    RecetaId: Integer;
    RecetaNombre: string;
    CantArticulos: Integer;
    TotalDeficitUds: Double;
    MasasExactas: Double;
    MasasAjustadas: Double;
    TotalMasasReceta: Double;
    ProximaEntrega: TDateTime;
    TieneEntrega: Boolean;
    DiasVida: Integer;
    ReduccionCadPct: Double;
    FechaPlanificada: TDateTime;
    EstadoPlan: string;
    OcupacionStr: string;
  end;
var
  LSql: string;
  LAlmId, LObradorId, I, K, LMaxAntelacion, LDiasAntic: Integer;
  LCapacidadDia, LUsadoDia, LHueco, LAsignar, MRestante: Double;
  LFechaIdeal, LFechaMinCad, LFechaAsig, LDia: TDateTime;
  LRecetaList, LCalendarList: TList<TRecetaPlanInfo>;
  LRecetaIdx: TDictionary<Integer, Integer>;
  LOcupacionDia: TDictionary<TDateTime, Double>;
  LPlanPorReceta: TDictionary<Integer, TDateTime>;
  LInfo, LSlot: TRecetaPlanInfo;
begin
  mtRecetas.DisableControls;
  mtArticulos.DisableControls;
  LRecetaList := TList<TRecetaPlanInfo>.Create;
  LCalendarList := TList<TRecetaPlanInfo>.Create;
  LRecetaIdx := TDictionary<Integer, Integer>.Create;
  LOcupacionDia := TDictionary<TDateTime, Double>.Create;
  LPlanPorReceta := TDictionary<Integer, TDateTime>.Create;
  try
    mtRecetas.EmptyDataSet;
    mtArticulos.EmptyDataSet;

    LAlmId := GetSelectedAlmacenId;
    LObradorId := GetSelectedObradorId;
    LCapacidadDia := ObtenerCapacidadObrador(LObradorId);

    LSql :=
      'SELECT r.id AS receta_id, r.descripcion AS receta_nombre, ' +
      '       a.id AS articulo_id, a.descripcion AS articulo_nombre, ' +
      '       COALESCE(a.dias_vida, 0) AS dias_vida, ' +
      '       COALESCE(rp.unidades_base, 189.0) AS unidades_por_masa, ' +
      '       COALESCE(SUM(CASE WHEN p.id IS NOT NULL THEN pl.cantidad ELSE 0 END), 0) AS unidades_pendientes, ' +
      '       MIN(CASE WHEN p.id IS NOT NULL THEN DATE(COALESCE(p.fecha_entrega, p.fecha_pedido)) ELSE NULL END) AS proxima_entrega, ' +
      '       COALESCE((SELECT SUM(se.cantidad_unidades - COALESCE(se.cantidad_reservada, 0)) ' +
      '                 FROM ge_stock_envasado se ' +
      '                 WHERE se.id_articulo = a.id AND se.id_almacen = :alm), 0) AS stock_disponible, ' +
      '       COALESCE((SELECT SUM(GREATEST(0, opl.cantidad - COALESCE(opl.cantidad_fabricada, 0))) ' +
      '                 FROM ge_ordenes_produccion_lineas opl ' +
      '                 JOIN ge_ordenes_produccion op ON op.id = opl.id_orden ' +
      '                 WHERE opl.id_articulo = a.id ' +
      '                   AND op.estado IN (''PLANIFICADA'',''EN_PROCESO'') ' +
      '                   AND opl.estado IN (''PENDIENTE'',''EN_PROCESO'')), 0) AS en_ordenes_prod ' +
      'FROM ob_recetas r ' +
      'JOIN ob_recetas_productos rp ON rp.receta_id = r.id AND rp.activo = 1 ' +
      'JOIN ge_articulos a ON a.id = rp.articulo_id AND a.activo = 1 ' +
      'LEFT JOIN ge_pedidos_lineas pl ON pl.id_articulo = a.id ' +
      'LEFT JOIN ge_pedidos p ON p.id = pl.id_pedido AND p.estado IN (''PENDIENTE'',''CONFIRMADO'') ' +
      'GROUP BY r.id, r.descripcion, a.id, a.descripcion, a.dias_vida, rp.unidades_base ' +
      'ORDER BY r.descripcion, a.descripcion';

    qCargaPlan.Close;
    qCargaPlan.SQL.Text := LSql;
    qCargaPlan.ParamByName('alm').AsInteger := LAlmId;
    qCargaPlan.Open;

    while not qCargaPlan.Eof do
    begin
      var LDef: Double := Round(Max(0.0, qCargaPlan.FieldByName('unidades_pendientes').AsFloat -
                                         qCargaPlan.FieldByName('stock_disponible').AsFloat -
                                         qCargaPlan.FieldByName('en_ordenes_prod').AsFloat));

      if (not chkSoloConDeficit.Checked) or (LDef > 0) then
      begin
        mtArticulos.Append;
        mtArticulos.FieldByName('articulo_id').AsInteger := qCargaPlan.FieldByName('articulo_id').AsInteger;
        mtArticulos.FieldByName('articulo_nombre').AsString := qCargaPlan.FieldByName('articulo_nombre').AsString;
        mtArticulos.FieldByName('receta_id').AsInteger := qCargaPlan.FieldByName('receta_id').AsInteger;
        mtArticulos.FieldByName('receta_nombre').AsString := qCargaPlan.FieldByName('receta_nombre').AsString;
        mtArticulos.FieldByName('unidades_pendientes').AsFloat := Round(qCargaPlan.FieldByName('unidades_pendientes').AsFloat);
        mtArticulos.FieldByName('stock_disponible').AsFloat := Round(qCargaPlan.FieldByName('stock_disponible').AsFloat);
        mtArticulos.FieldByName('en_ordenes_prod').AsFloat := Round(qCargaPlan.FieldByName('en_ordenes_prod').AsFloat);
        mtArticulos.FieldByName('deficit_unidades').AsFloat := LDef;
        mtArticulos.FieldByName('unidades_por_masa').AsFloat := qCargaPlan.FieldByName('unidades_por_masa').AsFloat;

        if qCargaPlan.FieldByName('unidades_por_masa').AsFloat > 0 then
          mtArticulos.FieldByName('masas_necesarias').AsFloat :=
            AjustarMasasACuartos(LDef / qCargaPlan.FieldByName('unidades_por_masa').AsFloat)
        else
          mtArticulos.FieldByName('masas_necesarias').AsFloat := 0.0;

        if not qCargaPlan.FieldByName('proxima_entrega').IsNull then
          mtArticulos.FieldByName('proxima_entrega').AsDateTime := Trunc(qCargaPlan.FieldByName('proxima_entrega').AsDateTime);
        mtArticulos.FieldByName('dias_vida').AsInteger := qCargaPlan.FieldByName('dias_vida').AsInteger;
        mtArticulos.FieldByName('lote_generado').AsString := '';
        mtArticulos.Post;
      end;

      qCargaPlan.Next;
    end;

    // Consolidar por receta con fecha de entrega más temprana y caducidad más corta
    mtArticulos.First;
    while not mtArticulos.Eof do
    begin
      var RId := mtArticulos.FieldByName('receta_id').AsInteger;
      var RNom := mtArticulos.FieldByName('receta_nombre').AsString;
      var MNeed := mtArticulos.FieldByName('masas_necesarias').AsFloat;
      var DefUds := mtArticulos.FieldByName('deficit_unidades').AsFloat;
      var DVida := mtArticulos.FieldByName('dias_vida').AsInteger;
      var HasEnt := not mtArticulos.FieldByName('proxima_entrega').IsNull;
      var FEnt := Date;
      if HasEnt then
        FEnt := Trunc(mtArticulos.FieldByName('proxima_entrega').AsDateTime);

      if LRecetaIdx.TryGetValue(RId, I) then
      begin
        LInfo := LRecetaList[I];
        LInfo.TotalDeficitUds := LInfo.TotalDeficitUds + DefUds;
        LInfo.MasasExactas := LInfo.MasasExactas + MNeed;
        Inc(LInfo.CantArticulos);
        if HasEnt and ((not LInfo.TieneEntrega) or (FEnt < LInfo.ProximaEntrega)) then
        begin
          LInfo.ProximaEntrega := FEnt;
          LInfo.TieneEntrega := True;
        end;
        if (DVida > 0) and ((LInfo.DiasVida <= 0) or (DVida < LInfo.DiasVida)) then
          LInfo.DiasVida := DVida;
        LRecetaList[I] := LInfo;
      end
      else
      begin
        LInfo.RecetaId := RId;
        LInfo.RecetaNombre := RNom;
        LInfo.CantArticulos := 1;
        LInfo.TotalDeficitUds := DefUds;
        LInfo.MasasExactas := MNeed;
        LInfo.MasasAjustadas := 0;
        LInfo.ProximaEntrega := FEnt;
        LInfo.TieneEntrega := HasEnt;
        LInfo.DiasVida := DVida;
        LInfo.FechaPlanificada := Date;
        LInfo.EstadoPlan := 'PENDIENTE';
        LInfo.OcupacionStr := '';
        I := LRecetaList.Add(LInfo);
        LRecetaIdx.Add(RId, I);
      end;

      mtArticulos.Next;
    end;

    for I := 0 to LRecetaList.Count - 1 do
    begin
      LInfo := LRecetaList[I];
      LInfo.MasasAjustadas := AjustarMasasACuartos(LInfo.MasasExactas);
      LRecetaList[I] := LInfo;
    end;

    // Ordenar por fecha de entrega más urgente y, a igual entrega, menor vida útil primero
    LRecetaList.Sort(TComparer<TRecetaPlanInfo>.Construct(
      function(const A, B: TRecetaPlanInfo): Integer
      begin
        if A.TieneEntrega <> B.TieneEntrega then
          Exit(IfThen(A.TieneEntrega, -1, 1));
        if A.ProximaEntrega < B.ProximaEntrega then Exit(-1);
        if A.ProximaEntrega > B.ProximaEntrega then Exit(1);
        if (A.DiasVida > 0) and (B.DiasVida > 0) then
        begin
          if A.DiasVida < B.DiasVida then Exit(-1);
          if A.DiasVida > B.DiasVida then Exit(1);
        end;
        Result := CompareText(A.RecetaNombre, B.RecetaNombre);
      end));

    // Cargar ocupación ya existente del obrador en ob_elaboraciones y ge_ordenes_produccion desde hoy
    if LObradorId > 0 then
    begin
      try
        qExec.Close;
        qExec.SQL.Text :=
          'SELECT DATE(fecha) AS f, COALESCE(SUM(numero_masas), 0) AS masas ' +
          'FROM ob_elaboraciones ' +
          'WHERE id_obrador = :obr AND DATE(fecha) >= :hoy ' +
          'GROUP BY DATE(fecha)';
        qExec.ParamByName('obr').AsInteger := LObradorId;
        qExec.ParamByName('hoy').AsDate := Date;
        qExec.Open;
        while not qExec.Eof do
        begin
          LDia := Trunc(qExec.FieldByName('f').AsDateTime);
          LOcupacionDia.AddOrSetValue(LDia, qExec.FieldByName('masas').AsFloat);
          qExec.Next;
        end;
        qExec.Close;

        // Sumar también masas comprometidas en órdenes de producción activas del obrador
        qExec.SQL.Text :=
          'SELECT op.fecha_produccion AS f, ' +
          '       COALESCE(SUM(GREATEST(0, opl.cantidad - COALESCE(opl.cantidad_fabricada, 0)) / ' +
          '                    COALESCE(NULLIF(rp.unidades_base, 0), 189.0)), 0) AS masas ' +
          'FROM ge_ordenes_produccion op ' +
          'JOIN ge_ordenes_produccion_lineas opl ON opl.id_orden = op.id ' +
          'LEFT JOIN ob_recetas_productos rp ON rp.articulo_id = opl.id_articulo AND rp.activo = 1 ' +
          'WHERE op.estado IN (''PLANIFICADA'',''EN_PROCESO'') ' +
          '  AND opl.estado IN (''PENDIENTE'',''EN_PROCESO'') ' +
          '  AND op.fecha_produccion >= :hoy ' +
          '  AND (op.id_obrador = :obr OR op.id_obrador IS NULL) ' +
          'GROUP BY op.fecha_produccion';
        qExec.ParamByName('obr').AsInteger := LObradorId;
        qExec.ParamByName('hoy').AsDate := Date;
        qExec.Open;
        while not qExec.Eof do
        begin
          LDia := Trunc(qExec.FieldByName('f').AsDateTime);
          if LOcupacionDia.TryGetValue(LDia, LUsadoDia) then
            LOcupacionDia.AddOrSetValue(LDia, LUsadoDia + qExec.FieldByName('masas').AsFloat)
          else
            LOcupacionDia.AddOrSetValue(LDia, qExec.FieldByName('masas').AsFloat);
          qExec.Next;
        end;
        qExec.Close;
      except
        // Si no existen registros o hay error menor, continúa con diccionario vacío
      end;
    end;

    // Programar calendario multi-día respetando capacidad diaria y máximo 20% de pérdida de caducidad
    for I := 0 to LRecetaList.Count - 1 do
    begin
      LInfo := LRecetaList[I];
      LInfo.TotalMasasReceta := LInfo.MasasAjustadas;
      if LInfo.MasasAjustadas <= 0 then
      begin
        LInfo.FechaPlanificada := Date;
        LInfo.ReduccionCadPct := 0;
        LInfo.EstadoPlan := 'SIN DÉFICIT';
        LInfo.OcupacionStr := '-';
        LCalendarList.Add(LInfo);
        Continue;
      end;

      if LInfo.TieneEntrega then
        LFechaIdeal := Max(Date, LInfo.ProximaEntrega - 1)
      else
        LFechaIdeal := Date;

      // Regla 20%: la caducidad desde la fecha de entrega no puede reducirse más de un 20%
      if LInfo.TieneEntrega and (LInfo.DiasVida > 0) then
      begin
        LMaxAntelacion := Floor(LInfo.DiasVida * 0.20);
        LFechaMinCad := Max(Date, LInfo.ProximaEntrega - LMaxAntelacion);
      end
      else
        LFechaMinCad := Date;

      if LCapacidadDia <= 0 then
      begin
        if not LOcupacionDia.TryGetValue(LFechaIdeal, LUsadoDia) then
          LUsadoDia := 0;
        LUsadoDia := LUsadoDia + LInfo.MasasAjustadas;
        LOcupacionDia.AddOrSetValue(LFechaIdeal, LUsadoDia);

        LSlot := LInfo;
        LSlot.FechaPlanificada := LFechaIdeal;
        LDiasAntic := Max(0, Trunc(LSlot.ProximaEntrega - LFechaIdeal));
        if (LSlot.TieneEntrega) and (LSlot.DiasVida > 0) then
          LSlot.ReduccionCadPct := Min(100.0, (LDiasAntic / LSlot.DiasVida) * 100.0)
        else
          LSlot.ReduccionCadPct := 0;
        LSlot.OcupacionStr := Format('%.2f (Sin límite)', [LUsadoDia]);
        LSlot.EstadoPlan := 'ÓPTIMO (<=20% CAD.)';
        LCalendarList.Add(LSlot);
        if not LPlanPorReceta.ContainsKey(LSlot.RecetaId) then
          LPlanPorReceta.Add(LSlot.RecetaId, LFechaIdeal);
        Continue;
      end;

      MRestante := LInfo.MasasAjustadas;

      // 1. Repartir desde LFechaIdeal hacia atrás hasta LFechaMinCad (cumple entrega y <= 20% pérdida caducidad)
      LDia := LFechaIdeal;
      while (LDia >= LFechaMinCad) and (MRestante > 0.001) do
      begin
        if not LOcupacionDia.TryGetValue(LDia, LUsadoDia) then
          LUsadoDia := 0;
        LHueco := Max(0.0, LCapacidadDia - LUsadoDia);
        if LHueco >= 0.25 then
        begin
          LAsignar := Min(MRestante, Floor(LHueco * 4) / 4);
          if LAsignar > 0.001 then
          begin
            LUsadoDia := LUsadoDia + LAsignar;
            LOcupacionDia.AddOrSetValue(LDia, LUsadoDia);

            LSlot := LInfo;
            LSlot.MasasAjustadas := LAsignar;
            LSlot.MasasExactas := LInfo.MasasExactas * (LAsignar / LInfo.TotalMasasReceta);
            LSlot.TotalDeficitUds := LInfo.TotalDeficitUds * (LAsignar / LInfo.TotalMasasReceta);
            LSlot.FechaPlanificada := LDia;
            LDiasAntic := Max(0, Trunc(LSlot.ProximaEntrega - LDia));
            if LSlot.TieneEntrega and (LSlot.DiasVida > 0) then
              LSlot.ReduccionCadPct := Min(100.0, (LDiasAntic / LSlot.DiasVida) * 100.0)
            else
              LSlot.ReduccionCadPct := 0;
            LSlot.OcupacionStr := Format('%.2f / %.0f masas', [LUsadoDia, LCapacidadDia]);
            LSlot.EstadoPlan := 'ÓPTIMO (<=20% CAD.)';
            LCalendarList.Add(LSlot);
            if not LPlanPorReceta.ContainsKey(LSlot.RecetaId) then
              LPlanPorReceta.Add(LSlot.RecetaId, LDia);

            MRestante := MRestante - LAsignar;
          end;
        end;
        LDia := LDia - 1;
      end;

      // 2. Si queda masa pendiente antes de la entrega fuera del margen del 20%, usar días previos hasta Date con alerta
      if (MRestante > 0.001) and (LFechaMinCad > Date) then
      begin
        LDia := LFechaMinCad - 1;
        while (LDia >= Date) and (MRestante > 0.001) do
        begin
          if not LOcupacionDia.TryGetValue(LDia, LUsadoDia) then
            LUsadoDia := 0;
          LHueco := Max(0.0, LCapacidadDia - LUsadoDia);
          if LHueco >= 0.25 then
          begin
            LAsignar := Min(MRestante, Floor(LHueco * 4) / 4);
            if LAsignar > 0.001 then
            begin
              LUsadoDia := LUsadoDia + LAsignar;
              LOcupacionDia.AddOrSetValue(LDia, LUsadoDia);

              LSlot := LInfo;
              LSlot.MasasAjustadas := LAsignar;
              LSlot.MasasExactas := LInfo.MasasExactas * (LAsignar / LInfo.TotalMasasReceta);
              LSlot.TotalDeficitUds := LInfo.TotalDeficitUds * (LAsignar / LInfo.TotalMasasReceta);
              LSlot.FechaPlanificada := LDia;
              LDiasAntic := Max(0, Trunc(LSlot.ProximaEntrega - LDia));
              if LSlot.TieneEntrega and (LSlot.DiasVida > 0) then
                LSlot.ReduccionCadPct := Min(100.0, (LDiasAntic / LSlot.DiasVida) * 100.0)
              else
                LSlot.ReduccionCadPct := 0;
              LSlot.OcupacionStr := Format('%.2f / %.0f masas', [LUsadoDia, LCapacidadDia]);
              LSlot.EstadoPlan := 'ALERTA CADUCIDAD (>20%)';
              LCalendarList.Add(LSlot);
              if not LPlanPorReceta.ContainsKey(LSlot.RecetaId) then
                LPlanPorReceta.Add(LSlot.RecetaId, LDia);

              MRestante := MRestante - LAsignar;
            end;
          end;
          LDia := LDia - 1;
        end;
      end;

      // 3. Si aún queda masa pendiente, asignar hacia adelante tras la entrega con alerta de retraso
      if MRestante > 0.001 then
      begin
        for K := 1 to 90 do
        begin
          if MRestante <= 0.001 then Break;
          LDia := LFechaIdeal + K;
          if not LOcupacionDia.TryGetValue(LDia, LUsadoDia) then
            LUsadoDia := 0;
          LHueco := Max(0.0, LCapacidadDia - LUsadoDia);
          if LHueco >= 0.25 then
          begin
            LAsignar := Min(MRestante, Floor(LHueco * 4) / 4);
            if LAsignar > 0.001 then
            begin
              LUsadoDia := LUsadoDia + LAsignar;
              LOcupacionDia.AddOrSetValue(LDia, LUsadoDia);

              LSlot := LInfo;
              LSlot.MasasAjustadas := LAsignar;
              LSlot.MasasExactas := LInfo.MasasExactas * (LAsignar / LInfo.TotalMasasReceta);
              LSlot.TotalDeficitUds := LInfo.TotalDeficitUds * (LAsignar / LInfo.TotalMasasReceta);
              LSlot.FechaPlanificada := LDia;
              LSlot.ReduccionCadPct := 0;
              LSlot.OcupacionStr := Format('%.2f / %.0f masas', [LUsadoDia, LCapacidadDia]);
              LSlot.EstadoPlan := 'SOBREPASA ENTREGA';
              LCalendarList.Add(LSlot);
              if not LPlanPorReceta.ContainsKey(LSlot.RecetaId) then
                LPlanPorReceta.Add(LSlot.RecetaId, LDia);

              MRestante := MRestante - LAsignar;
            end;
          end;
        end;
      end;
    end;

    // Ordenar calendario cronológicamente por fecha de fabricación planificada
    LCalendarList.Sort(TComparer<TRecetaPlanInfo>.Construct(
      function(const A, B: TRecetaPlanInfo): Integer
      begin
        if A.FechaPlanificada < B.FechaPlanificada then Exit(-1);
        if A.FechaPlanificada > B.FechaPlanificada then Exit(1);
        if A.ProximaEntrega < B.ProximaEntrega then Exit(-1);
        if A.ProximaEntrega > B.ProximaEntrega then Exit(1);
        Result := CompareText(A.RecetaNombre, B.RecetaNombre);
      end));

    // Volcar calendario a mtRecetas
    for I := 0 to LCalendarList.Count - 1 do
    begin
      LInfo := LCalendarList[I];
      mtRecetas.Append;
      mtRecetas.FieldByName('receta_id').AsInteger := LInfo.RecetaId;
      mtRecetas.FieldByName('receta_nombre').AsString := LInfo.RecetaNombre;
      mtRecetas.FieldByName('cant_articulos').AsInteger := LInfo.CantArticulos;
      mtRecetas.FieldByName('total_deficit_uds').AsFloat := Round(LInfo.TotalDeficitUds);
      mtRecetas.FieldByName('masas_exactas').AsFloat := AjustarMasasACuartos(LInfo.MasasExactas);
      mtRecetas.FieldByName('masas_ajustadas').AsFloat := LInfo.MasasAjustadas;
      mtRecetas.FieldByName('total_masas_receta').AsFloat := LInfo.TotalMasasReceta;
      mtRecetas.FieldByName('masas_texto').AsString := FormatearMasasCuartos(LInfo.MasasAjustadas);
      if LInfo.TieneEntrega then
        mtRecetas.FieldByName('proxima_entrega').AsDateTime := LInfo.ProximaEntrega;
      mtRecetas.FieldByName('dias_vida').AsInteger := LInfo.DiasVida;
      mtRecetas.FieldByName('reduccion_cad_pct').AsFloat := LInfo.ReduccionCadPct;
      mtRecetas.FieldByName('fecha_planificada').AsDateTime := LInfo.FechaPlanificada;
      mtRecetas.FieldByName('ocupacion_obrador').AsString := LInfo.OcupacionStr;
      mtRecetas.FieldByName('estado_lote').AsString := LInfo.EstadoPlan;
      mtRecetas.Post;
    end;

    // Actualizar caducidad estimada en mtArticulos según la fecha planificada de su receta
    mtArticulos.First;
    while not mtArticulos.Eof do
    begin
      if (mtArticulos.FieldByName('dias_vida').AsInteger > 0) and
         LPlanPorReceta.TryGetValue(mtArticulos.FieldByName('receta_id').AsInteger, LFechaAsig) then
      begin
        mtArticulos.Edit;
        mtArticulos.FieldByName('fecha_caducidad_est').AsDateTime := LFechaAsig + mtArticulos.FieldByName('dias_vida').AsInteger;
        mtArticulos.Post;
      end;
      mtArticulos.Next;
    end;

    ActualizarKPIs;
    RefrescarCalendarioVisual;
  finally
    LPlanPorReceta.Free;
    LOcupacionDia.Free;
    LRecetaIdx.Free;
    LCalendarList.Free;
    LRecetaList.Free;
    mtArticulos.EnableControls;
    mtRecetas.EnableControls;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.ActualizarKPIs;
var
  LRecetasCount: Integer;
  LMasasTotales, LCapDia: Double;
  LBookmark: TBookmark;
begin
  LRecetasCount := 0;
  LMasasTotales := 0.0;

  LBookmark := mtRecetas.GetBookmark;
  try
    mtRecetas.First;
    while not mtRecetas.Eof do
    begin
      if mtRecetas.FieldByName('masas_ajustadas').AsFloat > 0 then
      begin
        Inc(LRecetasCount);
        LMasasTotales := LMasasTotales + mtRecetas.FieldByName('masas_ajustadas').AsFloat;
      end;
      mtRecetas.Next;
    end;
  finally
    if mtRecetas.BookmarkValid(LBookmark) then
      mtRecetas.GotoBookmark(LBookmark);
    mtRecetas.FreeBookmark(LBookmark);
  end;

  LCapDia := ObtenerCapacidadObrador(GetSelectedObradorId);
  lblKpiRecetasVal.Caption := IntToStr(LRecetasCount);
  lblKpiMasasVal.Caption := Format('%.2f', [LMasasTotales]);
  if LCapDia > 0 then
  begin
    lblKpiMasasVal.Hint := Format('Capacidad diaria del obrador: %.0f masas/día', [LCapDia]);
    lblKpiMasasVal.ShowHint := True;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.mtRecetasAfterScroll(DataSet: TDataSet);
var
  LRecetaId: Integer;
begin
  if mtRecetas.IsEmpty or (mtRecetas.FieldByName('receta_id').IsNull) then
  begin
    mtArticulos.Filtered := False;
    mtArticulos.Filter := 'receta_id = -1';
    mtArticulos.Filtered := True;
    Exit;
  end;

  LRecetaId := mtRecetas.FieldByName('receta_id').AsInteger;
  mtArticulos.Filtered := False;
  mtArticulos.Filter := 'receta_id = ' + IntToStr(LRecetaId);
  mtArticulos.Filtered := True;
end;

procedure TfrmPlanificacionMasasProduccion.chkSoloConDeficitClick(Sender: TObject);
begin
  CargarDatosPlanificacion;
end;

procedure TfrmPlanificacionMasasProduccion.btnRecalcularClick(Sender: TObject);
begin
  CargarDatosPlanificacion;
end;

function TfrmPlanificacionMasasProduccion.GenerarLotesParaReceta(ARecetaId: Integer;
  const ARecetaNombre: string; AMasasAjustadas: Double; out ATotalLotesCreados: Integer): Boolean;
var
  LAlmId, LObradorId, LUserId: Integer;
  LCodigo, LIdLote, LArtId: Integer;
  LCodigoAntiguo, LObs: string;
  LDeficit: Double;
  LBookmark: TBookmark;
begin
  Result := False;
  ATotalLotesCreados := 0;

  LAlmId := GetSelectedAlmacenId;
  LObradorId := GetSelectedObradorId;
  LUserId := StrToIntDef(dmgMain.CurrentUserId, 1);

  var LFechaLotePlan: TDateTime := dtpFechaLote.Date;
  var LPropDia: Double := 1.0;
  if mtRecetas.Active and (not mtRecetas.IsEmpty) and
     (mtRecetas.FieldByName('receta_id').AsInteger = ARecetaId) then
  begin
    if (not mtRecetas.FieldByName('fecha_planificada').IsNull) and
       (mtRecetas.FieldByName('fecha_planificada').AsDateTime > 0) then
      LFechaLotePlan := Trunc(mtRecetas.FieldByName('fecha_planificada').AsDateTime);
    if mtRecetas.FieldByName('total_masas_receta').AsFloat > 0 then
      LPropDia := Min(1.0, AMasasAjustadas / mtRecetas.FieldByName('total_masas_receta').AsFloat);
  end;

  LBookmark := mtArticulos.GetBookmark;
  try
    mtArticulos.Filtered := False;
    mtArticulos.Filter := 'receta_id = ' + IntToStr(ARecetaId);
    mtArticulos.Filtered := True;
    mtArticulos.First;

    AsegurarColumnaArticuloReparto;

  dmgMain.dbConn.StartTransaction;
    try
      var LPrefRec := '';
      qExec.Close;
      qExec.SQL.Text := 'SELECT prefijo_lote FROM ob_recetas WHERE id = :id';
      qExec.ParamByName('id').AsInteger := ARecetaId;
      qExec.Open;
      if not qExec.IsEmpty then
        LPrefRec := qExec.FieldByName('prefijo_lote').AsString;

      var LNextCodigo := dmgMain.GetNextCodigoLote;

      while not mtArticulos.Eof do
      begin
        LDeficit := Round(mtArticulos.FieldByName('deficit_unidades').AsFloat * LPropDia);
        LArtId := mtArticulos.FieldByName('articulo_id').AsInteger;

        if (LDeficit > 0) and (LArtId > 0) then
        begin
          LCodigo := LNextCodigo;
          Inc(LNextCodigo);
          LCodigoAntiguo := FormatearCodigoLoteSabor(LPrefRec, LFechaLotePlan, 1, IntToStr(LCodigo));
          LObs := Format('Planificación Logística - Receta: %s (Masa: %s)',
            [ARecetaNombre, FormatearMasasCuartos(AMasasAjustadas)]);

          qExec.Close;
          qExec.SQL.Text :=
            'INSERT INTO ge_lotes (codigo, codigo_antiguo, id_receta, id_articulo, id_obrador, fecha, observaciones, activo, id_user_creator, id_user_update) ' +
            'VALUES (:codigo, :codigo_antiguo, :id_receta, :id_articulo, :id_obrador, :fecha, :observaciones, 1, :user, :user)';
          qExec.ParamByName('codigo').AsInteger := LCodigo;
          qExec.ParamByName('codigo_antiguo').AsString := LCodigoAntiguo;
          qExec.ParamByName('id_receta').AsInteger := ARecetaId;
          qExec.ParamByName('id_articulo').AsInteger := LArtId;
          qExec.ParamByName('id_obrador').AsInteger := LObradorId;
          qExec.ParamByName('fecha').AsDate := LFechaLotePlan;
          qExec.ParamByName('observaciones').AsString := LObs;
          qExec.ParamByName('user').AsInteger := LUserId;
          qExec.ExecSQL;

          qExec.Close;
          qExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS last_id';
          qExec.Open;
          LIdLote := qExec.FieldByName('last_id').AsInteger;

          // REGISTRO EN STOCK ENVASADO CON ESTADO PENDIENTE
          qExec.Close;
          qExec.SQL.Text :=
            'INSERT INTO ge_stock_envasado (id_almacen, id_articulo, id_lote, id_formato_presentacion, ' +
            '  estado_fabricacion, cantidad_unidades, cantidad_producida, cantidad_reservada, created_at, id_user_creator) ' +
            'VALUES (:id_almacen, :id_articulo, :id_lote, 1, ''PENDIENTE'', :cantidad_unidades, :cantidad_fabricada, 0.0, NOW(), :user) ' +
            'ON DUPLICATE KEY UPDATE ' +
            '  cantidad_unidades = cantidad_unidades + VALUES(cantidad_unidades), ' +
            '  cantidad_producida = cantidad_producida + VALUES(cantidad_producida), ' +
            '  estado_fabricacion = ''PENDIENTE'', ' +
            '  id_user_update = VALUES(id_user_creator)';
          qExec.ParamByName('id_almacen').AsInteger := LAlmId;
          qExec.ParamByName('id_articulo').AsInteger := LArtId;
          qExec.ParamByName('id_lote').AsInteger := LIdLote;
          qExec.ParamByName('cantidad_unidades').AsFloat := LDeficit;
          qExec.ParamByName('cantidad_fabricada').AsFloat := LDeficit;
          qExec.ParamByName('user').AsInteger := LUserId;
          qExec.ExecSQL;

          mtArticulos.Edit;
          mtArticulos.FieldByName('lote_generado').AsString := LCodigoAntiguo;
          mtArticulos.Post;

          Inc(ATotalLotesCreados);
        end;

        mtArticulos.Next;
      end;

      dmgMain.dbConn.Commit;
      Result := True;
    except
      on E: Exception do
      begin
        dmgMain.dbConn.Rollback;
        raise Exception.Create('Error al generar lotes y stock envasado: ' + E.Message);
      end;
    end;
  finally
    if mtArticulos.BookmarkValid(LBookmark) then
      mtArticulos.GotoBookmark(LBookmark);
    mtArticulos.FreeBookmark(LBookmark);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnGenerarLoteRecetaClick(Sender: TObject);
var
  LRecetaId, LCount: Integer;
  LRecetaNom: string;
  LMasasAjust: Double;
begin
  if mtRecetas.IsEmpty then Exit;

  LRecetaId := mtRecetas.FieldByName('receta_id').AsInteger;
  LRecetaNom := mtRecetas.FieldByName('receta_nombre').AsString;
  LMasasAjust := mtRecetas.FieldByName('masas_ajustadas').AsFloat;

  if LMasasAjust <= 0 then
  begin
    MessageDlg('Esta receta no tiene déficit ni masas a generar.', mtInformation, [mbOK], 0);
    Exit;
  end;

  if MessageDlg(Format('¿Desea crear los lotes y el stock envasado PENDIENTE para la receta "%s" (%s)?',
                       [LRecetaNom, FormatearMasasCuartos(LMasasAjust)]),
                mtConfirmation, [mbYes, mbNo], 0) = mrYes then
  begin
    if GenerarLotesParaReceta(LRecetaId, LRecetaNom, LMasasAjust, LCount) then
    begin
      mtRecetas.Edit;
      mtRecetas.FieldByName('estado_lote').AsString := 'LOTES CREADOS';
      mtRecetas.Post;
      MessageDlg(Format('Se han creado %d lote(s) en ge_lotes y ge_stock_envasado (PENDIENTE) con éxito.', [LCount]),
                 mtInformation, [mbOK], 0);
    end;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnGenerarTodosLotesClick(Sender: TObject);
var
  LTotalCreados, LCount, LRecetaId: Integer;
  LRecetaNom: string;
  LMasasAjust: Double;
  LBookmark: TBookmark;
begin
  if mtRecetas.IsEmpty then Exit;

  if MessageDlg('¿Confirma que desea crear los lotes y stock envasado PENDIENTE para TODAS las recetas con déficit?',
                mtConfirmation, [mbYes, mbNo], 0) <> mrYes then Exit;

  LTotalCreados := 0;
  LBookmark := mtRecetas.GetBookmark;
  try
    mtRecetas.First;
    while not mtRecetas.Eof do
    begin
      LMasasAjust := mtRecetas.FieldByName('masas_ajustadas').AsFloat;
      if LMasasAjust > 0 then
      begin
        LRecetaId := mtRecetas.FieldByName('receta_id').AsInteger;
        LRecetaNom := mtRecetas.FieldByName('receta_nombre').AsString;

        if GenerarLotesParaReceta(LRecetaId, LRecetaNom, LMasasAjust, LCount) then
        begin
          LTotalCreados := LTotalCreados + LCount;
          mtRecetas.Edit;
          mtRecetas.FieldByName('estado_lote').AsString := 'LOTES CREADOS';
          mtRecetas.Post;
        end;
      end;
      mtRecetas.Next;
    end;

    MessageDlg(Format('Proceso completado: Se han creado un total de %d lote(s) con stock envasado PENDIENTE.', [LTotalCreados]),
               mtInformation, [mbOK], 0);
  finally
    if mtRecetas.BookmarkValid(LBookmark) then
      mtRecetas.GotoBookmark(LBookmark);
    mtRecetas.FreeBookmark(LBookmark);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.btnExportarClick(Sender: TObject);
var
  LSb: TStringBuilder;
  LFileName: string;
  LBookmark: TBookmark;
begin
  if pcModo.ActivePage = tsPlanManual then
  begin
    btnVerInformeClick(nil);
    Exit;
  end;

  saveDlgExport.FileName := 'Planificacion_Masas_' + FormatDateTime('yyyymmdd', dtpFechaLote.Date) + '.csv';
  if not saveDlgExport.Execute then Exit;

  LFileName := saveDlgExport.FileName;
  LSb := TStringBuilder.Create;
  LBookmark := mtArticulos.GetBookmark;
  try
    LSb.AppendLine('Receta;ArticuloID;Articulo;PendientePedidos;StockDisponible;Deficit;RendimientoPorMasa;AporteMasa;Lote');

    mtArticulos.Filtered := False;
    mtArticulos.First;
    while not mtArticulos.Eof do
    begin
      LSb.AppendLine(Format('"%s";%d;"%s";%.2f;%.2f;%.2f;%.2f;%.4f;"%s"', [
        mtArticulos.FieldByName('receta_nombre').AsString,
        mtArticulos.FieldByName('articulo_id').AsInteger,
        mtArticulos.FieldByName('articulo_nombre').AsString,
        mtArticulos.FieldByName('unidades_pendientes').AsFloat,
        mtArticulos.FieldByName('stock_disponible').AsFloat,
        mtArticulos.FieldByName('deficit_unidades').AsFloat,
        mtArticulos.FieldByName('unidades_por_masa').AsFloat,
        mtArticulos.FieldByName('masas_necesarias').AsFloat,
        mtArticulos.FieldByName('lote_generado').AsString
      ]));
      mtArticulos.Next;
    end;

    TFile.WriteAllText(LFileName, LSb.ToString, TEncoding.UTF8);
    MessageDlg('Archivo exportado correctamente a:' + sLineBreak + LFileName, mtInformation, [mbOK], 0);
  finally
    if mtArticulos.BookmarkValid(LBookmark) then
      mtArticulos.GotoBookmark(LBookmark);
    mtArticulos.FreeBookmark(LBookmark);
    LSb.Free;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.dbgRecetasDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  if (Column.FieldName = 'masas_texto') and (mtRecetas.FieldByName('masas_ajustadas').AsFloat > 0) then
  begin
    dbgRecetas.Canvas.Font.Style := [fsBold];
    dbgRecetas.Canvas.Font.Color := clNavy;
  end
  else if Column.FieldName = 'estado_lote' then
  begin
    if mtRecetas.FieldByName('estado_lote').AsString = 'LOTES CREADOS' then
      dbgRecetas.Canvas.Font.Color := clGreen
    else
      dbgRecetas.Canvas.Font.Color := clGrayText;
  end;
  dbgRecetas.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure TfrmPlanificacionMasasProduccion.dbgArticulosDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  if (Column.FieldName = 'deficit_unidades') and (mtArticulos.FieldByName('deficit_unidades').AsFloat > 0) then
  begin
    dbgArticulos.Canvas.Font.Style := [fsBold];
    dbgArticulos.Canvas.Font.Color := clMaroon;
  end
  else if (Column.FieldName = 'lote_generado') and (Trim(mtArticulos.FieldByName('lote_generado').AsString) <> '') then
  begin
    dbgArticulos.Canvas.Font.Style := [fsBold];
    dbgArticulos.Canvas.Font.Color := clGreen;
  end;
  dbgArticulos.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure TfrmPlanificacionMasasProduccion.btnCerrarClick(Sender: TObject);
begin
  Close;
end;

procedure TfrmPlanificacionMasasProduccion.InicializarPestanaCalendario;
var
  LPnlTop, LPnlDet: TPanel;
  LBtnPrev, LBtnHoy, LBtnNext: TSpeedButton;
  LLegend: TLabel;
  LDummyD: Word;
begin
  DecodeDate(Date, FCalYear, FCalMonth, LDummyD);
  FCalSelectedDate := Date;

  FTabCalendario := TTabSheet.Create(pcModo);
  FTabCalendario.PageControl := pcModo;
  FTabCalendario.Caption := 'Calendario Visual (Masas y Sabores)';

  LPnlTop := TPanel.Create(FTabCalendario);
  LPnlTop.Parent := FTabCalendario;
  LPnlTop.Align := alTop;
  LPnlTop.Height := 40;
  LPnlTop.BevelOuter := bvNone;
  LPnlTop.Color := $00F5F6F8;

  LBtnPrev := TSpeedButton.Create(LPnlTop);
  LBtnPrev.Parent := LPnlTop;
  LBtnPrev.SetBounds(10, 6, 95, 28);
  LBtnPrev.Caption := '< Mes Ant.';
  LBtnPrev.OnClick := CalPrevMonthClick;

  LBtnHoy := TSpeedButton.Create(LPnlTop);
  LBtnHoy.Parent := LPnlTop;
  LBtnHoy.SetBounds(110, 6, 65, 28);
  LBtnHoy.Caption := 'Hoy';
  LBtnHoy.OnClick := CalTodayClick;

  LBtnNext := TSpeedButton.Create(LPnlTop);
  LBtnNext.Parent := LPnlTop;
  LBtnNext.SetBounds(180, 6, 95, 28);
  LBtnNext.Caption := 'Mes Sig. >';
  LBtnNext.OnClick := CalNextMonthClick;

  FLblCalMes := TLabel.Create(LPnlTop);
  FLblCalMes.Parent := LPnlTop;
  FLblCalMes.SetBounds(290, 9, 260, 22);
  FLblCalMes.Font.Name := 'Segoe UI';
  FLblCalMes.Font.Size := 12;
  FLblCalMes.Font.Style := [fsBold];
  FLblCalMes.Font.Color := $002D2B1E;

  FLblCalCap := TLabel.Create(LPnlTop);
  FLblCalCap.Parent := LPnlTop;
  FLblCalCap.SetBounds(560, 12, 230, 18);
  FLblCalCap.Font.Name := 'Segoe UI';
  FLblCalCap.Font.Size := 9;
  FLblCalCap.Font.Style := [fsBold];
  FLblCalCap.Font.Color := $002D2BA1;

  LLegend := TLabel.Create(LPnlTop);
  LLegend.Parent := LPnlTop;
  LLegend.Align := alRight;
  LLegend.Margins.Right := 12;
  LLegend.AlignWithMargins := True;
  LLegend.Layout := tlCenter;
  LLegend.Font.Name := 'Segoe UI';
  LLegend.Font.Size := 8;
  LLegend.Caption := 'Verde: Óptimo (<=20% cad.)  |  Naranja: Alerta >20%  |  Rojo: Sobrepasa entrega';

  LPnlDet := TPanel.Create(FTabCalendario);
  LPnlDet.Parent := FTabCalendario;
  LPnlDet.Align := alBottom;
  LPnlDet.Height := 115;
  LPnlDet.BevelOuter := bvNone;
  LPnlDet.Padding.SetBounds(8, 4, 8, 6);

  FMemoCalDetalle := TMemo.Create(LPnlDet);
  FMemoCalDetalle.Parent := LPnlDet;
  FMemoCalDetalle.Align := alClient;
  FMemoCalDetalle.ReadOnly := True;
  FMemoCalDetalle.ScrollBars := ssVertical;
  FMemoCalDetalle.Font.Name := 'Segoe UI';
  FMemoCalDetalle.Font.Size := 9;
  FMemoCalDetalle.Color := $00FAFBFD;

  FCalGrid := TDrawGrid.Create(FTabCalendario);
  FCalGrid.Parent := FTabCalendario;
  FCalGrid.Align := alClient;
  FCalGrid.ColCount := 7;
  FCalGrid.RowCount := 7;
  FCalGrid.FixedCols := 0;
  FCalGrid.FixedRows := 1;
  FCalGrid.DefaultDrawing := False;
  FCalGrid.Options := [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine];
  FCalGrid.ScrollBars := ssNone;
  FCalGrid.DoubleBuffered := True;
  FTabCalendario.OnResize := CalGridResize;
  FCalGrid.OnDrawCell := CalGridDrawCell;
  FCalGrid.OnSelectCell := CalGridSelectCell;

  RefrescarCalendarioVisual;
end;

procedure TfrmPlanificacionMasasProduccion.CalPrevMonthClick(Sender: TObject);
begin
  if FCalMonth = 1 then
  begin
    FCalMonth := 12;
    Dec(FCalYear);
  end
  else
    Dec(FCalMonth);
  RefrescarCalendarioVisual;
end;

procedure TfrmPlanificacionMasasProduccion.CalNextMonthClick(Sender: TObject);
begin
  if FCalMonth = 12 then
  begin
    FCalMonth := 1;
    Inc(FCalYear);
  end
  else
    Inc(FCalMonth);
  RefrescarCalendarioVisual;
end;

procedure TfrmPlanificacionMasasProduccion.CalTodayClick(Sender: TObject);
var
  LDummyD: Word;
begin
  DecodeDate(Date, FCalYear, FCalMonth, LDummyD);
  FCalSelectedDate := Date;
  RefrescarCalendarioVisual;
end;

procedure TfrmPlanificacionMasasProduccion.CalGridResize(Sender: TObject);
var
  I, LColW, LRowH: Integer;
begin
  if not Assigned(FCalGrid) then Exit;
  LColW := Max(90, (FCalGrid.ClientWidth - 8) div 7);
  for I := 0 to 6 do
    FCalGrid.ColWidths[I] := LColW;

  FCalGrid.RowHeights[0] := 26;
  LRowH := Max(62, (FCalGrid.ClientHeight - 32) div 6);
  for I := 1 to 6 do
    FCalGrid.RowHeights[I] := LRowH;
end;

function TfrmPlanificacionMasasProduccion.GetCalCellDate(ACol, ARow: Integer): TDateTime;
var
  LFirstOfMonth: TDateTime;
  LDow, LOffset: Integer;
begin
  LFirstOfMonth := EncodeDate(FCalYear, FCalMonth, 1);
  // DayOfTheWeek: 1=Lunes .. 7=Domingo
  LDow := DayOfTheWeek(LFirstOfMonth);
  LOffset := (ARow - 1) * 7 + ACol - (LDow - 1);
  Result := LFirstOfMonth + LOffset;
end;

procedure TfrmPlanificacionMasasProduccion.CalGridDrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
const
  CNombresDias: array[0..6] of string = ('Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo');
var
  LC: TCanvas;
  LCellDate: TDateTime;
  LY, LM, LD: Word;
  LIsCurrMonth, LIsToday, LIsSel: Boolean;
  LCapDia, LTotalMasasDia, LMasas: Double;
  LItems: TStringList;
  LBookmark: TBookmark;
  LYPos, I: Integer;
  LSabor, LEst, LLine, LBadge: string;
  LItemColor: TColor;
begin
  LC := FCalGrid.Canvas;
  if ARow = 0 then
  begin
    LC.Brush.Color := $002D2BA1;
    LC.FillRect(Rect);
    LC.Font.Name := 'Segoe UI';
    LC.Font.Size := 9;
    LC.Font.Style := [fsBold];
    LC.Font.Color := clWhite;
    DrawText(LC.Handle, PChar(CNombresDias[ACol]), -1, Rect, DT_CENTER or DT_VCENTER or DT_SINGLELINE);
    Exit;
  end;

  LCellDate := Trunc(GetCalCellDate(ACol, ARow));
  DecodeDate(LCellDate, LY, LM, LD);
  LIsCurrMonth := (LY = FCalYear) and (LM = FCalMonth);
  LIsToday := LCellDate = Trunc(Date);
  LIsSel := LCellDate = Trunc(FCalSelectedDate);

  if LIsSel then
    LC.Brush.Color := $00FFF2F2
  else if LIsToday then
    LC.Brush.Color := $00FFF9E6
  else if LIsCurrMonth then
    LC.Brush.Color := clWhite
  else
    LC.Brush.Color := $00F3F4F6;
  LC.FillRect(Rect);

  if LIsSel then
  begin
    LC.Pen.Color := $002D2BA1;
    LC.Pen.Width := 2;
    LC.Rectangle(Rect.Left + 1, Rect.Top + 1, Rect.Right - 1, Rect.Bottom - 1);
    LC.Pen.Width := 1;
  end;

  // Recopilar masas y sabores del día desde mtRecetas
  LTotalMasasDia := 0;
  LItems := TStringList.Create;
  try
    if mtRecetas.Active and (not mtRecetas.IsEmpty) then
    begin
      LBookmark := mtRecetas.GetBookmark;
      mtRecetas.DisableControls;
      try
        mtRecetas.First;
        while not mtRecetas.Eof do
        begin
          if (not mtRecetas.FieldByName('fecha_planificada').IsNull) and
             (Trunc(mtRecetas.FieldByName('fecha_planificada').AsDateTime) = LCellDate) then
          begin
            LMasas := mtRecetas.FieldByName('masas_ajustadas').AsFloat;
            if LMasas > 0 then
            begin
              LTotalMasasDia := LTotalMasasDia + LMasas;
              LSabor := Trim(mtRecetas.FieldByName('receta_nombre').AsString);
              LSabor := StringReplace(LSabor, 'PANETTONE ', '', [rfIgnoreCase]);
              LEst := mtRecetas.FieldByName('estado_lote').AsString;
              if ContainsText(LEst, 'SOBREPASA') then
                LItemColor := $002828C6
              else if ContainsText(LEst, 'ALERTA') then
                LItemColor := $000977D9
              else
                LItemColor := $00578B2E;
              LItems.AddObject(Format('%.2f m · %s', [LMasas, LSabor]), TObject(LItemColor));
            end;
          end;
          mtRecetas.Next;
        end;
      finally
        if mtRecetas.BookmarkValid(LBookmark) then
          mtRecetas.GotoBookmark(LBookmark);
        mtRecetas.FreeBookmark(LBookmark);
        mtRecetas.EnableControls;
      end;
    end;

    // Número de día
    LC.Font.Name := 'Segoe UI';
    LC.Font.Size := 9;
    LC.Font.Style := [fsBold];
    if LIsCurrMonth then
      LC.Font.Color := $001E293B
    else
      LC.Font.Color := $0094A3B8;
    LC.TextOut(Rect.Left + 5, Rect.Top + 3, IntToStr(LD));

    // Badge total masas del día
    if LTotalMasasDia > 0 then
    begin
      LCapDia := ObtenerCapacidadObrador(GetSelectedObradorId);
      if LCapDia > 0 then
        LBadge := Format('%.2f/%.0f m', [LTotalMasasDia, LCapDia])
      else
        LBadge := Format('%.2f m', [LTotalMasasDia]);

      LC.Font.Size := 8;
      LC.Font.Style := [fsBold];
      if (LCapDia > 0) and (LTotalMasasDia > LCapDia + 0.01) then
        LC.Font.Color := $002828C6
      else
        LC.Font.Color := $00578B2E;
      LC.TextOut(Rect.Right - LC.TextWidth(LBadge) - 5, Rect.Top + 4, LBadge);
    end;

    // Lista de masas y sabores del día
    LYPos := Rect.Top + 21;
    LC.Font.Size := 8;
    LC.Font.Style := [];
    for I := 0 to LItems.Count - 1 do
    begin
      if LYPos + 14 > Rect.Bottom - 2 then
      begin
        LC.Font.Color := $0064748B;
        LC.TextOut(Rect.Left + 5, Rect.Bottom - 15, Format('+ %d más...', [LItems.Count - I]));
        Break;
      end;
      LItemColor := TColor(LItems.Objects[I]);
      LC.Font.Color := LItemColor;
      LLine := LItems[I];
      var LTextRect := System.Classes.Rect(Rect.Left + 5, LYPos, Rect.Right - 4, LYPos + 14);
      DrawText(LC.Handle, PChar(LLine), -1, LTextRect, DT_LEFT or DT_SINGLELINE or DT_END_ELLIPSIS);
      Inc(LYPos, 14);
    end;
  finally
    LItems.Free;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.CalGridSelectCell(Sender: TObject; ACol, ARow: Integer;
  var CanSelect: Boolean);
begin
  if ARow >= 1 then
  begin
    FCalSelectedDate := Trunc(GetCalCellDate(ACol, ARow));
    FCalGrid.Invalidate;
    ActualizarDetalleDiaCalendario(FCalSelectedDate);
  end;
end;

procedure TfrmPlanificacionMasasProduccion.ActualizarDetalleDiaCalendario(ADate: TDateTime);
var
  LBookmark: TBookmark;
  LTotal: Double;
  LCapDia: Double;
  LCount: Integer;
begin
  if not Assigned(FMemoCalDetalle) then Exit;
  FMemoCalDetalle.Lines.BeginUpdate;
  try
    FMemoCalDetalle.Lines.Clear;
    LTotal := 0;
    LCount := 0;
    LCapDia := ObtenerCapacidadObrador(GetSelectedObradorId);

    if mtRecetas.Active and (not mtRecetas.IsEmpty) then
    begin
      LBookmark := mtRecetas.GetBookmark;
      mtRecetas.DisableControls;
      try
        mtRecetas.First;
        while not mtRecetas.Eof do
        begin
          if (not mtRecetas.FieldByName('fecha_planificada').IsNull) and
             (Trunc(mtRecetas.FieldByName('fecha_planificada').AsDateTime) = Trunc(ADate)) then
          begin
            Inc(LCount);
            LTotal := LTotal + mtRecetas.FieldByName('masas_ajustadas').AsFloat;
            FMemoCalDetalle.Lines.Add(Format('• %s  |  %s  |  Déficit: %s uds  |  Entrega: %s  |  Red. Cad.: %.1f%%  |  %s', [
              mtRecetas.FieldByName('receta_nombre').AsString,
              mtRecetas.FieldByName('masas_texto').AsString,
              FormatFloat('#,##0', mtRecetas.FieldByName('total_deficit_uds').AsFloat),
              IfThen(mtRecetas.FieldByName('proxima_entrega').IsNull, '-', FormatDateTime('dd/mm/yyyy', mtRecetas.FieldByName('proxima_entrega').AsDateTime)),
              mtRecetas.FieldByName('reduccion_cad_pct').AsFloat,
              mtRecetas.FieldByName('estado_lote').AsString
            ]));
          end;
          mtRecetas.Next;
        end;
      finally
        if mtRecetas.BookmarkValid(LBookmark) then
          mtRecetas.GotoBookmark(LBookmark);
        mtRecetas.FreeBookmark(LBookmark);
        mtRecetas.EnableControls;
      end;
    end;

    if LCount = 0 then
      FMemoCalDetalle.Lines.Insert(0, Format('Día %s: Sin producción planificada.', [FormatDateTime('dd/mm/yyyy', ADate)]))
    else
      FMemoCalDetalle.Lines.Insert(0, Format('Día %s — Total: %.2f masas%s (%d lote(s) de sabor):', [
        FormatDateTime('dd/mm/yyyy', ADate),
        LTotal,
        IfThen(LCapDia > 0, Format(' / %.0f máx.', [LCapDia]), ''),
        LCount
      ]));
  finally
    FMemoCalDetalle.Lines.EndUpdate;
  end;
end;

procedure TfrmPlanificacionMasasProduccion.RefrescarCalendarioVisual;
const
  CNombresMeses: array[1..12] of string = (
    'ENERO', 'FEBRERO', 'MARZO', 'ABRIL', 'MAYO', 'JUNIO',
    'JULIO', 'AGOSTO', 'SEPTIEMBRE', 'OCTUBRE', 'NOVIEMBRE', 'DICIEMBRE');
var
  LCapDia: Double;
begin
  if not Assigned(FCalGrid) then Exit;
  if (FCalMonth >= 1) and (FCalMonth <= 12) then
    FLblCalMes.Caption := Format('%s %d', [CNombresMeses[FCalMonth], FCalYear]);
  LCapDia := ObtenerCapacidadObrador(GetSelectedObradorId);
  if LCapDia > 0 then
    FLblCalCap.Caption := Format('Capacidad Obrador: %.0f masas/día', [LCapDia])
  else
    FLblCalCap.Caption := 'Capacidad Obrador: Sin límite';
  CalGridResize(nil);
  FCalGrid.Invalidate;
  ActualizarDetalleDiaCalendario(FCalSelectedDate);
end;

end.
